repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
girving/tensorflow
refs/heads/master
tensorflow/python/keras/applications/densenet.py
12
# Copyright 2018 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. # ============================================================================== # pylint: disable=invalid-name """DenseNet models for Keras. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras_applications import densenet from tensorflow.python.keras.applications import keras_modules_injection from tensorflow.python.util.tf_export import tf_export @tf_export('keras.applications.densenet.DenseNet121', 'keras.applications.DenseNet121') @keras_modules_injection def DenseNet121(*args, **kwargs): return densenet.DenseNet121(*args, **kwargs) @tf_export('keras.applications.densenet.DenseNet169', 'keras.applications.DenseNet169') @keras_modules_injection def DenseNet169(*args, **kwargs): return densenet.DenseNet169(*args, **kwargs) @tf_export('keras.applications.densenet.DenseNet201', 'keras.applications.DenseNet201') @keras_modules_injection def DenseNet201(*args, **kwargs): return densenet.DenseNet201(*args, **kwargs) @tf_export('keras.applications.densenet.decode_predictions') @keras_modules_injection def decode_predictions(*args, **kwargs): return densenet.decode_predictions(*args, **kwargs) @tf_export('keras.applications.densenet.preprocess_input') @keras_modules_injection def preprocess_input(*args, **kwargs): return densenet.preprocess_input(*args, **kwargs)
bergercookie/Pump3000
refs/heads/master
python_code/build/bdist.win-amd64/winexe/temp/PyQt4.QtNetwork.py
1
def __load(): import imp, os, sys try: dirname = os.path.dirname(__loader__.archive) except NameError: dirname = sys.prefix path = os.path.join(dirname, 'PyQt4.QtNetwork.pyd') #print "py2exe extension module", __name__, "->", path mod = imp.load_dynamic(__name__, path) ## mod.frozen = 1 __load() del __load
ghchinoy/tensorflow
refs/heads/master
tensorflow/contrib/nearest_neighbor/python/kernel_tests/hyperplane_lsh_probes_test.py
25
# Copyright 2017 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 hyperplane_lsh_probes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.nearest_neighbor.python.ops.nearest_neighbor_ops import hyperplane_lsh_probes from tensorflow.python.platform import test class HyperplaneLshProbesTest(test.TestCase): # We only test the batch functionality of the op here because the multiprobe # tests in hyperplane_lsh_probes_test.cc already cover most of the LSH # functionality. def simple_batch_test(self): with self.cached_session(): hyperplanes = np.eye(4) points = np.array([[1.2, 0.5, -0.9, -1.0], [2.0, -3.0, 1.0, -1.5]]) product = np.dot(points, hyperplanes) num_tables = 2 num_hyperplanes_per_table = 2 num_probes = 4 hashes, tables = hyperplane_lsh_probes(product, num_tables, num_hyperplanes_per_table, num_probes) self.assertAllEqual(hashes.eval(), [[3, 0, 2, 2], [2, 2, 0, 3]]) self.assertAllEqual(tables.eval(), [[0, 1, 0, 1], [0, 1, 1, 1]]) if __name__ == '__main__': test.main()
alrusdi/lettuce
refs/heads/master
tests/integration/lib/Django-1.2.5/django/contrib/gis/db/backends/oracle/introspection.py
388
import cx_Oracle from django.db.backends.oracle.introspection import DatabaseIntrospection class OracleIntrospection(DatabaseIntrospection): # Associating any OBJECTVAR instances with GeometryField. Of course, # this won't work right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, # but it is the only object type supported within Django anyways. data_types_reverse = DatabaseIntrospection.data_types_reverse.copy() data_types_reverse[cx_Oracle.OBJECT] = 'GeometryField' def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information. try: cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s', (table_name.upper(), geo_col.upper())) row = cursor.fetchone() except Exception, msg: raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n' 'Error message: %s.' % (table_name, geo_col, msg)) # TODO: Research way to find a more specific geometry field type for # the column's contents. field_type = 'GeometryField' # Getting the field parameters. field_params = {} dim, srid = row if srid != 4326: field_params['srid'] = srid # Length of object array ( SDO_DIM_ARRAY ) is number of dimensions. dim = len(dim) if dim != 2: field_params['dim'] = dim finally: cursor.close() return field_type, field_params
heyglen/sublime-network
refs/heads/master
lib/iana/ripe/objects/poetic_form.py
2
""" Copyright 2019 Glen Harmon POETIC-FORM Object Description https://www.ripe.net/manage-ips-and-asns/db/support/documentation/ripe-database-documentation/rpsl-object-types/4-3-descriptions-of-secondary-objects/4-3-8-description-of-the-poetic-form-object """ from .rpsl import Rpsl class PoeticForm(Rpsl): def __init__(self): self.handle = None self.description = list() super().__init__() def __str__(self): return '{}'.format(self.handle) def html(self, heading_level=1): return super().html( title='Poetic Form', attributes=[ (None, self.handle), ('Description', self.description), ('Organisation', self.organisation), ('Admin Contact', self.admin_contact), ('Technical Contact', self.technical_contact), ('Remarks', self.remarks), ('Notify', self.notify), ('Maintained By', self.maintained_by), ('Modified', self.modified), ('Type', self.type_), ] )
pap/rethinkdb
refs/heads/next
scripts/VirtuaBuild/smoke_test.py
46
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. # usage: ./smoke_test.py --mode OS_NAME --num-keys SOME_NUMBER_HERE import time, sys, os, socket, random, time, signal, subprocess sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'test', 'common'))) import driver, memcached_workload_common from vcoptparse import * op = OptParser() op["num_keys"] = IntFlag("--num-keys", 500) op["mode"] = StringFlag("--mode", "debug") op["pkg_type"] = StringFlag("--pkg-type", "deb") # "deb" or "rpm" opts = op.parse(sys.argv) num_keys = opts["num_keys"] base_port = 11213 # port that RethinkDB runs from by default if opts["pkg_type"] == "rpm": def install(path): return "rpm -i %s --nodeps" % path def get_binary(path): return "rpm -qpil %s | grep /usr/bin" % path def uninstall(cmd_name): return "which %s | xargs readlink -f | xargs rpm -qf | xargs rpm -e" % cmd_name elif opts["pkg_type"] == "deb": def install(path): return "dpkg -i %s" % path def get_binary(path): return "dpkg -c %s | grep /usr/bin/rethinkdb-.* | sed 's/^.*\(\/usr.*\)$/\\1/'" % path def uninstall(cmd_name): return "which %s | xargs readlink -f | xargs dpkg -S | sed 's/^\(.*\):.*$/\\1/' | xargs dpkg -r" % cmd_name else: print >>sys.stderr, "Error: Unknown package type." exit(0) def purge_installed_packages(): try: old_binaries_raw = exec_command(["ls", "/usr/bin/rethinkdb*"], shell = True).stdout.readlines() except Exception, e: print "Nothing to remove." return old_binaries = map(lambda x: x.strip('\n'), old_binaries_raw) print "Binaries scheduled for removal: ", old_binaries try: exec_command(uninstall(old_binaries[0]), shell = True) except Exception, e: exec_command('rm -f ' + old_binaries[0]) purge_installed_packages() def exec_command(cmd, bg = False, shell = False): if type(cmd) == type("") and not shell: cmd = cmd.split(" ") elif type(cmd) == type([]) and shell: cmd = " ".join(cmd) print cmd if bg: return subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = shell) # doesn't actually run in background: it just skips the waiting part else: proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = shell) proc.wait() if proc.poll(): raise RuntimeError("Error: command ended with signal %d." % proc.poll()) return proc def wait_until_started_up(proc, host, port, timeout = 600): time_limit = time.time() + timeout while time.time() < time_limit: if proc.poll() is not None: raise RuntimeError("Process stopped unexpectedly with return code %d." % proc.poll()) s = socket.socket() try: s.connect((host, port)) except socket.error, e: time.sleep(1) else: break finally: s.close() else: raise RuntimeError("Could not connect to process.") def test_against(host, port, timeout = 600): with memcached_workload_common.make_memcache_connection({"address": (host, port), "mclib": "pylibmc", "protocol": "text"}) as mc: temp = 0 time_limit = time.time() + timeout while not temp and time.time() < time_limit: try: temp = mc.set("test", "test") print temp except Exception, e: print e pass time.sleep(1) goodsets = 0 goodgets = 0 for i in range(num_keys): try: if mc.set(str(i), str(i)): goodsets += 1 except: pass for i in range(num_keys): try: if mc.get(str(i)) == str(i): goodgets += 1 except: pass return goodsets, goodgets cur_dir = exec_command("pwd").stdout.readline().strip('\n') p = exec_command("find build/%s -name *.%s" % (opts["mode"], opts["pkg_type"])) raw = p.stdout.readlines() res_paths = map(lambda x: os.path.join(cur_dir, x.strip('\n')), raw) print "Packages to install:", res_paths failed_test = False for path in res_paths: print "TESTING A NEW PACKAGE" print "Uninstalling old packages..." purge_installed_packages() print "Done uninstalling..." print "Installing RethinkDB..." target_binary_name = exec_command(get_binary(path), shell = True).stdout.readlines()[0].strip('\n') print "Target binary name:", target_binary_name exec_command(install(path)) print "Starting RethinkDB..." exec_command("rm -rf rethinkdb_data") exec_command("rm -f core.*") proc = exec_command("rethinkdb", bg = True) # gets the IP address s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("rethinkdb.com", 80)) ip = s.getsockname()[0] s.close() print "IP Address detected:", ip wait_until_started_up(proc, ip, base_port) print "Testing..." res = test_against(ip, base_port) print "Tests completed. Killing instance now..." proc.send_signal(signal.SIGINT) timeout = 60 # 1 minute to shut down time_limit = time.time() + timeout while proc.poll() is None and time.time() < time_limit: pass if proc.poll() != 0: print "RethinkDB failed to shut down properly. (TEST FAILED)" failed_test = False if res != (num_keys, num_keys): print "Done: FAILED" print "Results: %d successful sets, %d successful gets (%d total)" % (res[0], res[1], num_keys) failed_test = True else: print "Done: PASSED" print "Done." if failed_test: exit(1) else: exit(0)
wangyanxi/web-demos
refs/heads/master
python/arg/arg.py
1
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument( 'source_file', nargs='?', type=argparse.FileType('r'), default=sys.stdin ) parser.add_argument( '-v', '--version', action='version', version='%(prog)s 1.3' ) parser.add_argument( '-f', dest='target_file', type=argparse.FileType('w'), help='output file', # required=True, default=sys.stdout ) args = parser.parse_args() print(args) # parser.print_help() if __name__ == '__main__': main()
dlcs/dlcs-client
refs/heads/master
dlcs/queue_response.py
1
from requests import get, auth import settings mapping = { '@context': 'context', '@id': 'id', '@type': 'type', 'errorImages': 'error_images', 'completedImages': 'completed_images', } class Batch: @staticmethod def get_attribute_name(json_name): if json_name in mapping: return mapping.get(json_name) return json_name def __init__(self, batch_data=None, batch_id=None): self.count = 0 self.completed = 0 self.id = batch_id if batch_data is not None: self.update_data(batch_data) else: self.update() def update(self): url = self.id a = auth.HTTPBasicAuth(settings.DLCS_API_KEY, settings.DLCS_API_SECRET) response = get(url, auth=a) self.update_data(response.json()) def update_data(self, batch_data): for element in batch_data: value = batch_data.get(element) setattr(self, self.get_attribute_name(element), value) def is_completed(self): # TODO check for errors count. e.g. errors + completed == count and return number of errors return self.count > 0 and self.count == int(self.completed)
MechCoder/sympy
refs/heads/master
sympy/polys/domains/modularinteger.py
112
"""Implementation of :class:`ModularInteger` class. """ from __future__ import print_function, division import operator from sympy.polys.polyutils import PicklableWithSlots from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains.domainelement import DomainElement from sympy.utilities import public @public class ModularInteger(PicklableWithSlots, DomainElement): """A class representing a modular integer. """ mod, dom, sym, _parent = None, None, None, None __slots__ = ['val'] def parent(self): return self._parent def __init__(self, val): if isinstance(val, self.__class__): self.val = val.val % self.mod else: self.val = self.dom.convert(val) % self.mod def __hash__(self): return hash((self.val, self.mod)) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.val) def __str__(self): return "%s mod %s" % (self.val, self.mod) def __int__(self): return int(self.to_int()) def to_int(self): if self.sym: if self.val <= self.mod // 2: return self.val else: return self.val - self.mod else: return self.val def __pos__(self): return self def __neg__(self): return self.__class__(-self.val) @classmethod def _get_val(cls, other): if isinstance(other, cls): return other.val else: try: return cls.dom.convert(other) except CoercionFailed: return None def __add__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val + val) else: return NotImplemented def __radd__(self, other): return self.__add__(other) def __sub__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val - val) else: return NotImplemented def __rsub__(self, other): return (-self).__add__(other) def __mul__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * val) else: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def __div__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * self._invert(val)) else: return NotImplemented def __rdiv__(self, other): return self.invert().__mul__(other) __truediv__ = __div__ __rtruediv__ = __rdiv__ def __mod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val % val) else: return NotImplemented def __rmod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(val % self.val) else: return NotImplemented def __pow__(self, exp): if not exp: return self.__class__(self.dom.one) if exp < 0: val, exp = self.invert(), -exp else: val = self.val return self.__class__(val**exp) def _compare(self, other, op): val = self._get_val(other) if val is not None: return op(self.val, val % self.mod) else: return NotImplemented def __eq__(self, other): return self._compare(other, operator.eq) def __ne__(self, other): return self._compare(other, operator.ne) def __lt__(self, other): return self._compare(other, operator.lt) def __le__(self, other): return self._compare(other, operator.le) def __gt__(self, other): return self._compare(other, operator.gt) def __ge__(self, other): return self._compare(other, operator.ge) def __nonzero__(self): return bool(self.val) __bool__ = __nonzero__ @classmethod def _invert(cls, value): return cls.dom.invert(value, cls.mod) def invert(self): return self.__class__(self._invert(self.val)) _modular_integer_cache = {} def ModularIntegerFactory(_mod, _dom, _sym, parent): """Create custom class for specific integer modulus.""" try: _mod = _dom.convert(_mod) except CoercionFailed: ok = False else: ok = True if not ok or _mod < 1: raise ValueError("modulus must be a positive integer, got %s" % _mod) key = _mod, _dom, _sym try: cls = _modular_integer_cache[key] except KeyError: class cls(ModularInteger): mod, dom, sym = _mod, _dom, _sym _parent = parent if _sym: cls.__name__ = "SymmetricModularIntegerMod%s" % _mod else: cls.__name__ = "ModularIntegerMod%s" % _mod _modular_integer_cache[key] = cls return cls
explorerwjy/jw_anly502
refs/heads/master
L02/mrjob_salary_max0.py
6
from mrjob.job import MRJob from mrjob.step import MRStep import heapq, csv cols = 'Name,JobTitle,AgencyID,Agency,HireDate,AnnualSalary,GrossPay'.split(",") class salarymax(MRJob): def mapper(self, _, line): row = dict(zip(cols, [ a.strip() for a in csv.reader([line]).next()])) yield "salary", (float(row["AnnualSalary"][1:]), line) yield "gross", (float(row["GrossPay"][1:]), line) def reducer(self, key, values): for p in heapq.nlargest(10,values): yield key, p combiner = reducer if __name__=="__main__": salarymax.run()
goodwinnk/intellij-community
refs/heads/master
python/testData/refactoring/move/packageImport/after/src/lib1/mod1.py
166
def k(x): return lambda y: x
qk4l/Flexget
refs/heads/develop
flexget/plugins/metainfo/assume_quality.py
9
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import logging from collections import namedtuple import flexget.utils.qualities as qualities from flexget import plugin from flexget.event import event log = logging.getLogger('assume_quality') class AssumeQuality(object): """ Applies quality components to entries that match specified quality requirements. When a quality is applied, any components which are unknown in the entry are filled from the applied quality. Quality requirements are tested in order of increasing precision (ie "720p h264" is more precise than "1080p" so gets tested first), and applied as matches are found. Using the simple configuration is the same as specifying an "any" rule. Examples:: assume_quality: 1080p webdl 10bit truehd assume_quality: hdtv: 720p 720p hdtv: 10bit '!ac3 !mp3': flac any: 720p h264 """ schema = { 'oneOf': [ {'title': 'simple config', 'type': 'string', 'format': 'quality'}, { 'title': 'advanced config', 'type': 'object', # Can't validate dict keys, so allow any 'additionalProperties': {'type': 'string', 'format': 'quality'} } ] } def precision(self, qualityreq): p = 0 for component in qualityreq.components: if component.acceptable: p += 8 if component.min: p += 4 if component.max: p += 4 if component.none_of: p += len(component.none_of) # Still a long way from perfect, but probably good enough. return p def assume(self, entry, quality): newquality = qualities.Quality() log.debug('Current qualities: %s', entry.get('quality')) for component in entry.get('quality').components: qualitycomponent = getattr(quality, component.type) log.debug('\t%s: %s vs %s', component.type, component.name, qualitycomponent.name) if component.name != 'unknown': log.debug('\t%s: keeping %s', component.type, component.name) setattr(newquality, component.type, component) elif qualitycomponent.name != 'unknown': log.debug('\t%s: assuming %s', component.type, qualitycomponent.name) setattr(newquality, component.type, qualitycomponent) entry['assumed_quality'] = True elif component.name == 'unknown' and qualitycomponent.name == 'unknown': log.debug('\t%s: got nothing', component.type) entry['quality'] = newquality log.debug('Quality updated: %s', entry.get('quality')) def on_task_start(self, task, config): if isinstance(config, basestring): config = {'any': config} assume = namedtuple('assume', ['target', 'quality']) self.assumptions = [] for target, quality in list(config.items()): log.verbose('New assumption: %s is %s' % (target, quality)) try: target = qualities.Requirements(target) except ValueError: raise plugin.PluginError('%s is not a valid quality. Forgetting assumption.' % target) try: quality = qualities.get(quality) except ValueError: raise plugin.PluginError('%s is not a valid quality. Forgetting assumption.' % quality) self.assumptions.append(assume(target, quality)) self.assumptions.sort(key=lambda assumption: self.precision(assumption.target), reverse=True) for assumption in self.assumptions: log.debug('Target %s - Priority %s' % (assumption.target, self.precision(assumption.target))) @plugin.priority(100) # run after other plugins which fill quality (series, quality) def on_task_metainfo(self, task, config): for entry in task.entries: log.verbose('%s' % entry.get('title')) for assumption in self.assumptions: log.debug('Trying %s - %s' % (assumption.target, assumption.quality)) if assumption.target.allows(entry.get('quality')): log.debug('Match: %s' % assumption.target) self.assume(entry, assumption.quality) log.verbose('New quality: %s', entry.get('quality')) @event('plugin.register') def register_plugin(): plugin.register(AssumeQuality, 'assume_quality', api_ver=2)
vladmm/intellij-community
refs/heads/master
python/testData/copyPaste/multiLine/IndentMulti21.dst.py
747
class C: def foo(self): <caret>y = 2
thomask77/nucular-keyboard
refs/heads/master
Tools/hex2dfu/intelhex/__init__.py
10
# Copyright (c) 2005-2013, Alexander Belchenko # 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 the author 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. '''Intel HEX file format reader and converter. @author Alexander Belchenko (alexander dot belchenko at gmail dot com) @version 1.5 ''' __docformat__ = "javadoc" from array import array from binascii import hexlify, unhexlify from bisect import bisect_right import os import sys from compat import asbytes, asstr class _DeprecatedParam(object): pass _DEPRECATED = _DeprecatedParam() class IntelHex(object): ''' Intel HEX file reader. ''' def __init__(self, source=None): ''' Constructor. If source specified, object will be initialized with the contents of source. Otherwise the object will be empty. @param source source for initialization (file name of HEX file, file object, addr dict or other IntelHex object) ''' # public members self.padding = 0x0FF # Start Address self.start_addr = None # private members self._buf = {} self._offset = 0 if source is not None: if isinstance(source, basestring) or getattr(source, "read", None): # load hex file self.loadhex(source) elif isinstance(source, dict): self.fromdict(source) elif isinstance(source, IntelHex): self.padding = source.padding if source.start_addr: self.start_addr = source.start_addr.copy() self._buf = source._buf.copy() else: raise ValueError("source: bad initializer type") def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return # empty line if s[0] == ':': try: bin = array('B', unhexlify(asbytes(s[1:]))) except (TypeError, ValueError): # this might be raised by unhexlify when odd hexascii digits raise HexRecordError(line=line) length = len(bin) if length < 5: raise HexRecordError(line=line) else: raise HexRecordError(line=line) record_length = bin[0] if length != (5 + record_length): raise RecordLengthError(line=line) addr = bin[1]*256 + bin[2] record_type = bin[3] if not (0 <= record_type <= 5): raise RecordTypeError(line=line) crc = sum(bin) crc &= 0x0FF if crc != 0: raise RecordChecksumError(line=line) if record_type == 0: # data record addr += self._offset for i in xrange(4, 4+record_length): if not self._buf.get(addr, None) is None: raise AddressOverlapError(address=addr, line=line) self._buf[addr] = bin[i] addr += 1 # FIXME: addr should be wrapped # BUT after 02 record (at 64K boundary) # and after 04 record (at 4G boundary) elif record_type == 1: # end of file record if record_length != 0: raise EOFRecordError(line=line) raise _EndOfFile elif record_type == 2: # Extended 8086 Segment Record if record_length != 2 or addr != 0: raise ExtendedSegmentAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 16 elif record_type == 4: # Extended Linear Address Record if record_length != 2 or addr != 0: raise ExtendedLinearAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 65536 elif record_type == 3: # Start Segment Address Record if record_length != 4 or addr != 0: raise StartSegmentAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'CS': bin[4]*256 + bin[5], 'IP': bin[6]*256 + bin[7], } elif record_type == 5: # Start Linear Address Record if record_length != 4 or addr != 0: raise StartLinearAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'EIP': (bin[4]*16777216 + bin[5]*65536 + bin[6]*256 + bin[7]), } def loadhex(self, fobj): """Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object """ if getattr(fobj, "read", None) is None: fobj = open(fobj, "r") fclose = fobj.close else: fclose = None self._offset = 0 line = 0 try: decode = self._decode_record try: for s in fobj: line += 1 decode(s, line) except _EndOfFile: pass finally: if fclose: fclose() def loadbin(self, fobj, offset=0): """Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting address offset """ fread = getattr(fobj, "read", None) if fread is None: f = open(fobj, "rb") fread = f.read fclose = f.close else: fclose = None try: self.frombytes(array('B', asbytes(fread())), offset=offset) finally: if fclose: fclose() def loadfile(self, fobj, format): """Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == "hex": self.loadhex(fobj) elif format == "bin": self.loadbin(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format) # alias (to be consistent with method tofile) fromfile = loadfile def fromdict(self, dikt): """Load data from dictionary. Dictionary should contain int keys representing addresses. Values should be the data to be stored in those addresses in unsigned char form (i.e. not strings). The dictionary may contain the key, ``start_addr`` to indicate the starting address of the data as described in README. The contents of the dict will be merged with this object and will overwrite any conflicts. This function is not necessary if the object was initialized with source specified. """ s = dikt.copy() start_addr = s.get('start_addr') if start_addr is not None: del s['start_addr'] for k in s.keys(): if type(k) not in (int, long) or k < 0: raise ValueError('Source dictionary should have only int keys') self._buf.update(s) if start_addr is not None: self.start_addr = start_addr def frombytes(self, bytes, offset=0): """Load data from array or list of bytes. Similar to loadbin() method but works directly with iterable bytes. """ for b in bytes: self._buf[offset] = b offset += 1 def _get_start_end(self, start=None, end=None, size=None): """Return default values for start and end if they are None. If this IntelHex object is empty then it's error to invoke this method with both start and end as None. """ if (start,end) == (None,None) and self._buf == {}: raise EmptyIntelHexError if size is not None: if None not in (start, end): raise ValueError("tobinarray: you can't use start,end and size" " arguments in the same time") if (start, end) == (None, None): start = self.minaddr() if start is not None: end = start + size - 1 else: start = end - size + 1 if start < 0: raise ValueError("tobinarray: invalid size (%d) " "for given end address (%d)" % (size,end)) else: if start is None: start = self.minaddr() if end is None: end = self.maxaddr() if start > end: start, end = end, start return start, end def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return array of unsigned char data. ''' if not isinstance(pad, _DeprecatedParam): print "IntelHex.tobinarray: 'pad' parameter is deprecated." if pad is not None: print "Please, use IntelHex.padding attribute instead." else: print "Please, don't pass it explicitly." print "Use syntax like this: ih.tobinarray(start=xxx, end=yyy, size=zzz)" else: pad = None return self._tobinarray_really(start, end, pad, size) def _tobinarray_really(self, start, end, pad, size): if pad is None: pad = self.padding bin = array('B') if self._buf == {} and None in (start, end): return bin if size is not None and size <= 0: raise ValueError("tobinarray: wrong value for size") start, end = self._get_start_end(start, end, size) for i in xrange(start, end+1): bin.append(self._buf.get(i, pad)) return bin def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert to binary form and return as a string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. @return string of binary data. ''' if not isinstance(pad, _DeprecatedParam): print "IntelHex.tobinstr: 'pad' parameter is deprecated." if pad is not None: print "Please, use IntelHex.padding attribute instead." else: print "Please, don't pass it explicitly." print "Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz)" else: pad = None return self._tobinstr_really(start, end, pad, size) def _tobinstr_really(self, start, end, pad, size): return asstr(self._tobinarray_really(start, end, pad, size).tostring()) def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None): '''Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] fill empty spaces with this value (if pad is None then this method uses self.padding). @param size size of the block, used with start or end parameter. ''' if not isinstance(pad, _DeprecatedParam): print "IntelHex.tobinfile: 'pad' parameter is deprecated." if pad is not None: print "Please, use IntelHex.padding attribute instead." else: print "Please, don't pass it explicitly." print "Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)" else: pad = None if getattr(fobj, "write", None) is None: fobj = open(fobj, "wb") close_fd = True else: close_fd = False fobj.write(self._tobinstr_really(start, end, pad, size)) if close_fd: fobj.close() def todict(self): '''Convert to python dictionary. @return dict suitable for initializing another IntelHex object. ''' r = {} r.update(self._buf) if self.start_addr: r['start_addr'] = self.start_addr return r def addresses(self): '''Returns all used addresses in sorted order. @return list of occupied data addresses in sorted order. ''' aa = self._buf.keys() aa.sort() return aa def minaddr(self): '''Get minimal address of HEX content. @return minimal address or None if no data ''' aa = self._buf.keys() if aa == []: return None else: return min(aa) def maxaddr(self): '''Get maximal address of HEX content. @return maximal address or None if no data ''' aa = self._buf.keys() if aa == []: return None else: return max(aa) def __getitem__(self, addr): ''' Get requested byte from address. @param addr address of byte. @return byte if address exists in HEX file, or self.padding if no data found. ''' t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') return self._buf.get(addr, self.padding) elif t == slice: addresses = self._buf.keys() ih = IntelHex() if addresses: addresses.sort() start = addr.start or addresses[0] stop = addr.stop or (addresses[-1]+1) step = addr.step or 1 for i in xrange(start, stop, step): x = self._buf.get(i) if x is not None: ih[i] = x return ih else: raise TypeError('Address has unsupported type: %s' % t) def __setitem__(self, addr, byte): """Set byte at address.""" t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') self._buf[addr] = byte elif t == slice: if not isinstance(byte, (list, tuple)): raise ValueError('Slice operation expects sequence of bytes') start = addr.start stop = addr.stop step = addr.step or 1 if None not in (start, stop): ra = range(start, stop, step) if len(ra) != len(byte): raise ValueError('Length of bytes sequence does not match ' 'address range') elif (start, stop) == (None, None): raise TypeError('Unsupported address range') elif start is None: start = stop - len(byte) elif stop is None: stop = start + len(byte) if start < 0: raise TypeError('start address cannot be negative') if stop < 0: raise TypeError('stop address cannot be negative') j = 0 for i in xrange(start, stop, step): self._buf[i] = byte[j] j += 1 else: raise TypeError('Address has unsupported type: %s' % t) def __delitem__(self, addr): """Delete byte at address.""" t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') del self._buf[addr] elif t == slice: addresses = self._buf.keys() if addresses: addresses.sort() start = addr.start or addresses[0] stop = addr.stop or (addresses[-1]+1) step = addr.step or 1 for i in xrange(start, stop, step): x = self._buf.get(i) if x is not None: del self._buf[i] else: raise TypeError('Address has unsupported type: %s' % t) def __len__(self): """Return count of bytes with real values.""" return len(self._buf.keys()) def write_hex_file(self, f, write_start_addr=True): """Write data to file f in HEX format. @param f filename or file-like object for writing @param write_start_addr enable or disable writing start address record to file (enabled by default). If there is no start address in obj, nothing will be written regardless of this setting. """ fwrite = getattr(f, "write", None) if fwrite: fobj = f fclose = None else: fobj = open(f, 'w') fwrite = fobj.write fclose = fobj.close # Translation table for uppercasing hex ascii string. # timeit shows that using hexstr.translate(table) # is faster than hexstr.upper(): # 0.452ms vs. 0.652ms (translate vs. upper) if sys.version_info[0] >= 3: table = bytes(range(256)).upper() else: table = ''.join(chr(i).upper() for i in range(256)) # start address record if any if self.start_addr and write_start_addr: keys = self.start_addr.keys() keys.sort() bin = array('B', asbytes('\0'*9)) if keys == ['CS','IP']: # Start Segment Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 3 # rectyp cs = self.start_addr['CS'] bin[4] = (cs >> 8) & 0x0FF bin[5] = cs & 0x0FF ip = self.start_addr['IP'] bin[6] = (ip >> 8) & 0x0FF bin[7] = ip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') elif keys == ['EIP']: # Start Linear Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 5 # rectyp eip = self.start_addr['EIP'] bin[4] = (eip >> 24) & 0x0FF bin[5] = (eip >> 16) & 0x0FF bin[6] = (eip >> 8) & 0x0FF bin[7] = eip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') else: if fclose: fclose() raise InvalidStartAddressValueError(start_addr=self.start_addr) # data addresses = self._buf.keys() addresses.sort() addr_len = len(addresses) if addr_len: minaddr = addresses[0] maxaddr = addresses[-1] if maxaddr > 65535: need_offset_record = True else: need_offset_record = False high_ofs = 0 cur_addr = minaddr cur_ix = 0 while cur_addr <= maxaddr: if need_offset_record: bin = array('B', asbytes('\0'*7)) bin[0] = 2 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 4 # rectyp high_ofs = int(cur_addr>>16) b = divmod(high_ofs, 256) bin[4] = b[0] # msb of high_ofs bin[5] = b[1] # lsb of high_ofs bin[6] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') while True: # produce one record low_addr = cur_addr & 0x0FFFF # chain_len off by 1 chain_len = min(15, 65535-low_addr, maxaddr-cur_addr) # search continuous chain stop_addr = cur_addr + chain_len if chain_len: ix = bisect_right(addresses, stop_addr, cur_ix, min(cur_ix+chain_len+1, addr_len)) chain_len = ix - cur_ix # real chain_len # there could be small holes in the chain # but we will catch them by try-except later # so for big continuous files we will work # at maximum possible speed else: chain_len = 1 # real chain_len bin = array('B', asbytes('\0'*(5+chain_len))) b = divmod(low_addr, 256) bin[1] = b[0] # msb of low_addr bin[2] = b[1] # lsb of low_addr bin[3] = 0 # rectype try: # if there is small holes we'll catch them for i in range(chain_len): bin[4+i] = self._buf[cur_addr+i] except KeyError: # we catch a hole so we should shrink the chain chain_len = i bin = bin[:5+i] bin[0] = chain_len bin[4+chain_len] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') # adjust cur_addr/cur_ix cur_ix += chain_len if cur_ix < addr_len: cur_addr = addresses[cur_ix] else: cur_addr = maxaddr + 1 break high_addr = int(cur_addr>>16) if high_addr > high_ofs: break # end-of-file record fwrite(":00000001FF\n") if fclose: fclose() def tofile(self, fobj, format): """Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == 'hex': self.write_hex_file(fobj) elif format == 'bin': self.tobinfile(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format) def gets(self, addr, length): """Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used.""" a = array('B', asbytes('\0'*length)) try: for i in xrange(length): a[i] = self._buf[addr+i] except KeyError: raise NotEnoughDataError(address=addr, length=length) return asstr(a.tostring()) def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B', asbytes(s)) for i in xrange(len(a)): self._buf[addr+i] = a[i] def getsz(self, addr): """Get zero-terminated string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0. """ i = 0 try: while True: if self._buf[addr+i] == 0: break i += 1 except KeyError: raise NotEnoughDataError(msg=('Bad access at 0x%X: ' 'not enough data to read zero-terminated string') % addr) return self.gets(addr, i) def putsz(self, addr, s): """Put string in object at addr and append terminating zero at end.""" self.puts(addr, s) self._buf[addr+len(s)] = 0 def dump(self, tofile=None): """Dump object content to specified file object or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump to """ if tofile is None: tofile = sys.stdout # start addr possibly if self.start_addr is not None: cs = self.start_addr.get('CS') ip = self.start_addr.get('IP') eip = self.start_addr.get('EIP') if eip is not None and cs is None and ip is None: tofile.write('EIP = 0x%08X\n' % eip) elif eip is None and cs is not None and ip is not None: tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip)) else: tofile.write('start_addr = %r\n' % start_addr) # actual data addresses = self._buf.keys() if addresses: addresses.sort() minaddr = addresses[0] maxaddr = addresses[-1] startaddr = int(minaddr>>4)*16 endaddr = int((maxaddr>>4)+1)*16 maxdigits = max(len(str(endaddr)), 4) templa = '%%0%dX' % maxdigits range16 = range(16) for i in xrange(startaddr, endaddr, 16): tofile.write(templa % i) tofile.write(' ') s = [] for j in range16: x = self._buf.get(i+j) if x is not None: tofile.write(' %02X' % x) if 32 <= x < 127: # GNU less does not like 0x7F (128 decimal) so we'd better show it as dot s.append(chr(x)) else: s.append('.') else: tofile.write(' --') s.append(' ') tofile.write(' |' + ''.join(s) + '|\n') def merge(self, other, overlap='error'): """Merge content of other IntelHex object into current object (self). @param other other IntelHex object. @param overlap action on overlap of data or starting addr: - error: raising OverlapError; - ignore: ignore other data and keep current data in overlapping region; - replace: replace data with other data in overlapping region. @raise TypeError if other is not instance of IntelHex @raise ValueError if other is the same object as self (it can't merge itself) @raise ValueError if overlap argument has incorrect value @raise AddressOverlapError on overlapped data """ # check args if not isinstance(other, IntelHex): raise TypeError('other should be IntelHex object') if other is self: raise ValueError("Can't merge itself") if overlap not in ('error', 'ignore', 'replace'): raise ValueError("overlap argument should be either " "'error', 'ignore' or 'replace'") # merge data this_buf = self._buf other_buf = other._buf for i in other_buf: if i in this_buf: if overlap == 'error': raise AddressOverlapError( 'Data overlapped at address 0x%X' % i) elif overlap == 'ignore': continue this_buf[i] = other_buf[i] # merge start_addr if self.start_addr != other.start_addr: if self.start_addr is None: # set start addr from other self.start_addr = other.start_addr elif other.start_addr is None: # keep existing start addr pass else: # conflict if overlap == 'error': raise AddressOverlapError( 'Starting addresses are different') elif overlap == 'replace': self.start_addr = other.start_addr #/IntelHex class IntelHex16bit(IntelHex): """Access to data as 16-bit words. Intended to use with Microchip HEX files.""" def __init__(self, source=None): """Construct class from HEX file or from instance of ordinary IntelHex class. If IntelHex object is passed as source, the original IntelHex object should not be used again because this class will alter it. This class leaves padding alone unless it was precisely 0xFF. In that instance it is sign extended to 0xFFFF. @param source file name of HEX file or file object or instance of ordinary IntelHex class. Will also accept dictionary from todict method. """ if isinstance(source, IntelHex): # from ihex8 self.padding = source.padding self.start_addr = source.start_addr # private members self._buf = source._buf self._offset = source._offset elif isinstance(source, dict): raise IntelHexError("IntelHex16bit does not support initialization from dictionary yet.\n" "Patches are welcome.") else: IntelHex.__init__(self, source) if self.padding == 0x0FF: self.padding = 0x0FFFF def __getitem__(self, addr16): """Get 16-bit word from address. Raise error if only one byte from the pair is set. We assume a Little Endian interpretation of the hex file. @param addr16 address of word (addr8 = 2 * addr16). @return word if bytes exists in HEX file, or self.padding if no data found. """ addr1 = addr16 * 2 addr2 = addr1 + 1 byte1 = self._buf.get(addr1, None) byte2 = self._buf.get(addr2, None) if byte1 != None and byte2 != None: return byte1 | (byte2 << 8) # low endian if byte1 == None and byte2 == None: return self.padding raise BadAccess16bit(address=addr16) def __setitem__(self, addr16, word): """Sets the address at addr16 to word assuming Little Endian mode. """ addr_byte = addr16 * 2 b = divmod(word, 256) self._buf[addr_byte] = b[1] self._buf[addr_byte+1] = b[0] def minaddr(self): '''Get minimal address of HEX content in 16-bit mode. @return minimal address used in this object ''' aa = self._buf.keys() if aa == []: return 0 else: return min(aa)>>1 def maxaddr(self): '''Get maximal address of HEX content in 16-bit mode. @return maximal address used in this object ''' aa = self._buf.keys() if aa == []: return 0 else: return max(aa)>>1 def tobinarray(self, start=None, end=None, size=None): '''Convert this object to binary form as array (of 2-bytes word data). If start and end unspecified, they will be inferred from the data. @param start start address of output data. @param end end address of output data (inclusive). @param size size of the block (number of words), used with start or end parameter. @return array of unsigned short (uint16_t) data. ''' bin = array('H') if self._buf == {} and None in (start, end): return bin if size is not None and size <= 0: raise ValueError("tobinarray: wrong value for size") start, end = self._get_start_end(start, end, size) for addr in xrange(start, end+1): bin.append(self[addr]) return bin #/class IntelHex16bit def hex2bin(fin, fout, start=None, end=None, size=None, pad=None): """Hex-to-Bin convertor engine. @return 0 if all OK @param fin input hex file (filename or file-like object) @param fout output bin file (filename or file-like object) @param start start of address range (optional) @param end end of address range (inclusive; optional) @param size size of resulting file (in bytes) (optional) @param pad padding byte (optional) """ try: h = IntelHex(fin) except HexReaderError, e: txt = "ERROR: bad HEX file: %s" % str(e) print(txt) return 1 # start, end, size if size != None and size != 0: if end == None: if start == None: start = h.minaddr() end = start + size - 1 else: if (end+1) >= size: start = end + 1 - size else: start = 0 try: if pad is not None: # using .padding attribute rather than pad argument to function call h.padding = pad h.tobinfile(fout, start, end) except IOError, e: txt = "ERROR: Could not write to file: %s: %s" % (fout, str(e)) print(txt) return 1 return 0 #/def hex2bin def bin2hex(fin, fout, offset=0): """Simple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin """ h = IntelHex() try: h.loadbin(fin, offset) except IOError, e: txt = 'ERROR: unable to load bin file:', str(e) print(txt) return 1 try: h.tofile(fout, format='hex') except IOError, e: txt = "ERROR: Could not write to file: %s: %s" % (fout, str(e)) print(txt) return 1 return 0 #/def bin2hex def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): """Diff 2 IntelHex objects and produce unified diff output for their hex dumps. @param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to write output @param name1 name of the first hex file to show in the diff header @param name2 name of the first hex file to show in the diff header @param n_context number of context lines in the unidiff output """ def prepare_lines(ih): from cStringIO import StringIO sio = StringIO() ih.dump(sio) dump = sio.getvalue() lines = dump.splitlines() return lines a = prepare_lines(ih1) b = prepare_lines(ih2) import difflib result = list(difflib.unified_diff(a, b, fromfile=name1, tofile=name2, n=n_context, lineterm='')) if tofile is None: tofile = sys.stdout output = '\n'.join(result)+'\n' tofile.write(output) class Record(object): """Helper methods to build valid ihex records.""" def _from_bytes(bytes): """Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record """ assert len(bytes) >= 4 # calculate checksum s = (-sum(bytes)) & 0x0FF bin = array('B', bytes + [s]) return ':' + asstr(hexlify(bin.tostring())).upper() _from_bytes = staticmethod(_from_bytes) def data(offset, bytes): """Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @return String representation of one HEX record """ assert 0 <= offset < 65536 assert 0 < len(bytes) < 256 b = [len(bytes), (offset>>8)&0x0FF, offset&0x0FF, 0x00] + bytes return Record._from_bytes(b) data = staticmethod(data) def eof(): """Return End of File record as a string. @return String representation of Intel Hex EOF record """ return ':00000001FF' eof = staticmethod(eof) def extended_segment_address(usba): """Return Extended Segment Address Record. @param usba Upper Segment Base Address. @return String representation of Intel Hex USBA record. """ b = [2, 0, 0, 0x02, (usba>>8)&0x0FF, usba&0x0FF] return Record._from_bytes(b) extended_segment_address = staticmethod(extended_segment_address) def start_segment_address(cs, ip): """Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register. @return String representation of Intel Hex SSA record. """ b = [4, 0, 0, 0x03, (cs>>8)&0x0FF, cs&0x0FF, (ip>>8)&0x0FF, ip&0x0FF] return Record._from_bytes(b) start_segment_address = staticmethod(start_segment_address) def extended_linear_address(ulba): """Return Extended Linear Address Record. @param ulba Upper Linear Base Address. @return String representation of Intel Hex ELA record. """ b = [2, 0, 0, 0x04, (ulba>>8)&0x0FF, ulba&0x0FF] return Record._from_bytes(b) extended_linear_address = staticmethod(extended_linear_address) def start_linear_address(eip): """Return Start Linear Address Record. @param eip 32-bit linear address for the EIP register. @return String representation of Intel Hex SLA record. """ b = [4, 0, 0, 0x05, (eip>>24)&0x0FF, (eip>>16)&0x0FF, (eip>>8)&0x0FF, eip&0x0FF] return Record._from_bytes(b) start_linear_address = staticmethod(start_linear_address) class _BadFileNotation(Exception): """Special error class to use with _get_file_and_addr_range.""" pass def _get_file_and_addr_range(s, _support_drive_letter=None): """Special method for hexmerge.py script to split file notation into 3 parts: (filename, start, end) @raise _BadFileNotation when string cannot be safely split. """ if _support_drive_letter is None: _support_drive_letter = (os.name == 'nt') drive = '' if _support_drive_letter: if s[1:2] == ':' and s[0].upper() in ''.join([chr(i) for i in range(ord('A'), ord('Z')+1)]): drive = s[:2] s = s[2:] parts = s.split(':') n = len(parts) if n == 1: fname = parts[0] fstart = None fend = None elif n != 3: raise _BadFileNotation else: fname = parts[0] def ascii_hex_to_int(ascii): if ascii is not None: try: return int(ascii, 16) except ValueError: raise _BadFileNotation return ascii fstart = ascii_hex_to_int(parts[1] or None) fend = ascii_hex_to_int(parts[2] or None) return drive+fname, fstart, fend ## # IntelHex Errors Hierarchy: # # IntelHexError - basic error # HexReaderError - general hex reader error # AddressOverlapError - data for the same address overlap # HexRecordError - hex record decoder base error # RecordLengthError - record has invalid length # RecordTypeError - record has invalid type (RECTYP) # RecordChecksumError - record checksum mismatch # EOFRecordError - invalid EOF record (type 01) # ExtendedAddressRecordError - extended address record base error # ExtendedSegmentAddressRecordError - invalid extended segment address record (type 02) # ExtendedLinearAddressRecordError - invalid extended linear address record (type 04) # StartAddressRecordError - start address record base error # StartSegmentAddressRecordError - invalid start segment address record (type 03) # StartLinearAddressRecordError - invalid start linear address record (type 05) # DuplicateStartAddressRecordError - start address record appears twice # InvalidStartAddressValueError - invalid value of start addr record # _EndOfFile - it's not real error, used internally by hex reader as signal that EOF record found # BadAccess16bit - not enough data to read 16 bit value (deprecated, see NotEnoughDataError) # NotEnoughDataError - not enough data to read N contiguous bytes # EmptyIntelHexError - requested operation cannot be performed with empty object class IntelHexError(Exception): '''Base Exception class for IntelHex module''' _fmt = 'IntelHex base error' #: format string def __init__(self, msg=None, **kw): """Initialize the Exception with the given message. """ self.msg = msg for key, value in kw.items(): setattr(self, key, value) def __str__(self): """Return the message in this Exception.""" if self.msg: return self.msg try: return self._fmt % self.__dict__ except (NameError, ValueError, KeyError), e: return 'Unprintable exception %s: %s' \ % (repr(e), str(e)) class _EndOfFile(IntelHexError): """Used for internal needs only.""" _fmt = 'EOF record reached -- signal to stop read file' class HexReaderError(IntelHexError): _fmt = 'Hex reader base error' class AddressOverlapError(HexReaderError): _fmt = 'Hex file has data overlap at address 0x%(address)X on line %(line)d' # class NotAHexFileError was removed in trunk.revno.54 because it's not used class HexRecordError(HexReaderError): _fmt = 'Hex file contains invalid record at line %(line)d' class RecordLengthError(HexRecordError): _fmt = 'Record at line %(line)d has invalid length' class RecordTypeError(HexRecordError): _fmt = 'Record at line %(line)d has invalid record type' class RecordChecksumError(HexRecordError): _fmt = 'Record at line %(line)d has invalid checksum' class EOFRecordError(HexRecordError): _fmt = 'File has invalid End-of-File record' class ExtendedAddressRecordError(HexRecordError): _fmt = 'Base class for extended address exceptions' class ExtendedSegmentAddressRecordError(ExtendedAddressRecordError): _fmt = 'Invalid Extended Segment Address Record at line %(line)d' class ExtendedLinearAddressRecordError(ExtendedAddressRecordError): _fmt = 'Invalid Extended Linear Address Record at line %(line)d' class StartAddressRecordError(HexRecordError): _fmt = 'Base class for start address exceptions' class StartSegmentAddressRecordError(StartAddressRecordError): _fmt = 'Invalid Start Segment Address Record at line %(line)d' class StartLinearAddressRecordError(StartAddressRecordError): _fmt = 'Invalid Start Linear Address Record at line %(line)d' class DuplicateStartAddressRecordError(StartAddressRecordError): _fmt = 'Start Address Record appears twice at line %(line)d' class InvalidStartAddressValueError(StartAddressRecordError): _fmt = 'Invalid start address value: %(start_addr)s' class NotEnoughDataError(IntelHexError): _fmt = ('Bad access at 0x%(address)X: ' 'not enough data to read %(length)d contiguous bytes') class BadAccess16bit(NotEnoughDataError): _fmt = 'Bad access at 0x%(address)X: not enough data to read 16 bit value' class EmptyIntelHexError(IntelHexError): _fmt = "Requested operation cannot be executed with empty object"
jspraul/bite-project
refs/heads/master
deps/mrtaskman/server/models/events.py
16
# 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. """Representation of an Event and related functionality.""" __author__ = 'jeff.carollo@gmail.com (Jeff Carollo)' from google.appengine.ext import db import logging class Error(Exception): pass class ServerEventError(Error): pass class ClientEventError(Error): pass EVENT_TYPES = [ 'STARTUP', 'SHUTDOWN', 'RECOVERABLE_FAILURE', 'UNRECOVERABLE_FAILURE', 'OFFLINE', 'RESUME', 'SERVER_ERROR', 'CLIENT_ERROR' ] EVENT_SEVERITY = [ 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL' ] class Event(db.Model): """MrTaskman's representation of an Event.""" worker_name = db.StringProperty(required=True) event_type = db.StringProperty(required=True, choices=EVENT_TYPES) event_severity = db.StringProperty(required=True, choices=EVENT_SEVERITY) event_name = db.StringProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) worker_version = db.StringProperty() event_info = db.TextProperty() # Long text description of event. task_id = db.IntegerProperty() task_info = db.TextProperty() # TODO(jeff.carollo): Extract into common library somewhere # along with ClientError and ServerError types. def CheckRequiredProperty(model_name, model, prop_name): """Raises a ClientEventError if model[prop_name] equates to False.""" if not model.get(prop_name, None): raise ClientEventError('%s is a required %s field.' % ( prop_name, model_name)) def AddOptionalModelStrProperty(model, src, prop): val = src.get(prop, None) if val: if not isinstance(val, basestring): raise ClientEventError('%s must be a string type.', prop) try: setattr(model, prop, val) except Exception, e: raise ClientEventError('%s is invalid. %s', prop, e) def AddOptionalModelIntProperty(model, src, prop): val = src.get(prop, None) if val: if not isinstance(val, int): try: val = int(val) except TypeError: raise ClientEventError('%s must be an int or int-convertible.', prop) try: setattr(model, prop, val) except Exception, e: raise ClientEventError('%s is invalid. %s', prop, e) def CreateEvent(event): """Creates an Event from the given event dictionary and stores it.""" CheckRequiredProperty('Event', event, 'worker_name') CheckRequiredProperty('Event', event, 'event_type') CheckRequiredProperty('Event', event, 'event_severity') CheckRequiredProperty('Event', event, 'event_name') e = Event(worker_name=event['worker_name'], event_type=event['event_type'], event_severity=event['event_severity'], event_name=event['event_name']) AddOptionalModelStrProperty(e, event, 'worker_version') AddOptionalModelStrProperty(e, event, 'event_info') AddOptionalModelIntProperty(e, event, 'task_id') AddOptionalModelStrProperty(e, event, 'task_info') if db.put(e): return e def GetEventById(event_id): """Gets a single Event with given integer event_id.""" event_key = db.Key.from_path('Event', event_id) return db.get(event_key) def DeleteEventById(event_id): """Deletes a single Event with given integer event_id.""" event_key = db.Key.from_path('Event', event_id) try: db.delete(event_key) except db.Error, e: logging.exception(e) return False return True def GetEventList(): """Returns all Events in a list.""" return Event.all().order('-__key__').fetch(1000)
xq262144/hue
refs/heads/master
desktop/core/ext-py/tablib-0.10.0/tablib/packages/openpyxl/reader/excel.py
61
# file openpyxl/reader/excel.py # Copyright (c) 2010 openpyxl # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # @license: http://www.opensource.org/licenses/mit-license.php # @author: Eric Gazoni """Read an xlsx file into Python""" # Python stdlib imports from zipfile import ZipFile, ZIP_DEFLATED, BadZipfile # package imports from ..shared.exc import OpenModeError, InvalidFileException from ..shared.ooxml import ARC_SHARED_STRINGS, ARC_CORE, ARC_APP, \ ARC_WORKBOOK, PACKAGE_WORKSHEETS, ARC_STYLE from ..workbook import Workbook from ..reader.strings import read_string_table from ..reader.style import read_style_table from ..reader.workbook import read_sheets_titles, read_named_ranges, \ read_properties_core, get_sheet_ids from ..reader.worksheet import read_worksheet from ..reader.iter_worksheet import unpack_worksheet def load_workbook(filename, use_iterators = False): """Open the given filename and return the workbook :param filename: the path to open :type filename: string :param use_iterators: use lazy load for cells :type use_iterators: bool :rtype: :class:`openpyxl.workbook.Workbook` .. note:: When using lazy load, all worksheets will be :class:`openpyxl.reader.iter_worksheet.IterableWorksheet` and the returned workbook will be read-only. """ if isinstance(filename, file): # fileobject must have been opened with 'rb' flag # it is required by zipfile if 'b' not in filename.mode: raise OpenModeError("File-object must be opened in binary mode") try: archive = ZipFile(filename, 'r', ZIP_DEFLATED) except (BadZipfile, RuntimeError, IOError, ValueError): raise InvalidFileException() wb = Workbook() if use_iterators: wb._set_optimized_read() try: _load_workbook(wb, archive, filename, use_iterators) except KeyError: raise InvalidFileException() finally: archive.close() return wb def _load_workbook(wb, archive, filename, use_iterators): # get workbook-level information wb.properties = read_properties_core(archive.read(ARC_CORE)) try: string_table = read_string_table(archive.read(ARC_SHARED_STRINGS)) except KeyError: string_table = {} style_table = read_style_table(archive.read(ARC_STYLE)) # get worksheets wb.worksheets = [] # remove preset worksheet sheet_names = read_sheets_titles(archive.read(ARC_APP)) for i, sheet_name in enumerate(sheet_names): sheet_codename = 'sheet%d.xml' % (i + 1) worksheet_path = '%s/%s' % (PACKAGE_WORKSHEETS, sheet_codename) if not use_iterators: new_ws = read_worksheet(archive.read(worksheet_path), wb, sheet_name, string_table, style_table) else: xml_source = unpack_worksheet(archive, worksheet_path) new_ws = read_worksheet(xml_source, wb, sheet_name, string_table, style_table, filename, sheet_codename) #new_ws = read_worksheet(archive.read(worksheet_path), wb, sheet_name, string_table, style_table, filename, sheet_codename) wb.add_sheet(new_ws, index = i) wb._named_ranges = read_named_ranges(archive.read(ARC_WORKBOOK), wb)
patrickwestphal/owlapy
refs/heads/master
owlapy/model/swrlsameindividualatom.py
1
from .owlobjectvisitor import OWLObjectVisitor, OWLObjectVisitorEx from .swrlbinaryatom import SWRLBinaryAtom from .swrlobjectvisitor import SWRLObjectVisitor, SWRLObjectVisitorEx from owlapy.util import accept_default, accept_default_ex from owlapy.vocab.owlrdfvocabulary import OWLRDFVocabulary class SWRLSameIndividualAtom(SWRLBinaryAtom): """TODO: implement""" def __init__(self, data_factory, arg0, arg1): """ :param data_factory: an owlapy.model.OWLDataFactory object :param arg0: an owlapy.model.SWRLIArgument object :param arg1: an owlapy.model.SWRLIArgument object """ super().__init__( data_factory.get_owl_object_property( OWLRDFVocabulary.OWL_DIFFERENT_FROM.iri), arg0, arg1) self._accept_fn_for_visitor_cls[OWLObjectVisitor] = accept_default self._accept_fn_for_visitor_cls[OWLObjectVisitorEx] = accept_default_ex self._accept_fn_for_visitor_cls[SWRLObjectVisitor] = accept_default self._accept_fn_for_visitor_cls[SWRLObjectVisitorEx] = accept_default_ex
chrxr/wagtail
refs/heads/master
wagtail/wagtaildocs/views/multiple.py
9
from __future__ import absolute_import, unicode_literals from django.core.exceptions import PermissionDenied from django.http import HttpResponseBadRequest, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import render_to_string from django.utils.encoding import force_text from django.views.decorators.http import require_POST from django.views.decorators.vary import vary_on_headers from wagtail.wagtailadmin.utils import PermissionPolicyChecker from wagtail.wagtailsearch.backends import get_search_backends from ..forms import get_document_form, get_document_multi_form from ..models import get_document_model from ..permissions import permission_policy permission_checker = PermissionPolicyChecker(permission_policy) @permission_checker.require('add') @vary_on_headers('X-Requested-With') def add(request): Document = get_document_model() DocumentForm = get_document_form(Document) DocumentMultiForm = get_document_multi_form(Document) collections = permission_policy.collections_user_has_permission_for(request.user, 'add') if len(collections) > 1: collections_to_choose = collections else: # no need to show a collections chooser collections_to_choose = None if request.method == 'POST': if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if not request.FILES: return HttpResponseBadRequest("Must upload a file") # Build a form for validation form = DocumentForm({ 'title': request.FILES['files[]'].name, 'collection': request.POST.get('collection'), }, { 'file': request.FILES['files[]'] }, user=request.user) if form.is_valid(): # Save it doc = form.save(commit=False) doc.uploaded_by_user = request.user doc.file_size = doc.file.size doc.save() # Success! Send back an edit form for this document to the user return JsonResponse({ 'success': True, 'doc_id': int(doc.id), 'form': render_to_string('wagtaildocs/multiple/edit_form.html', { 'doc': doc, 'form': DocumentMultiForm( instance=doc, prefix='doc-%d' % doc.id, user=request.user ), }, request=request), }) else: # Validation error return JsonResponse({ 'success': False, # https://github.com/django/django/blob/stable/1.6.x/django/forms/util.py#L45 'error_message': '\n'.join(['\n'.join([force_text(i) for i in v]) for k, v in form.errors.items()]), }) else: form = DocumentForm(user=request.user) return render(request, 'wagtaildocs/multiple/add.html', { 'help_text': form.fields['file'].help_text, 'collections': collections_to_choose, }) @require_POST def edit(request, doc_id, callback=None): Document = get_document_model() DocumentMultiForm = get_document_multi_form(Document) doc = get_object_or_404(Document, id=doc_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if not permission_policy.user_has_permission_for_instance(request.user, 'change', doc): raise PermissionDenied form = DocumentMultiForm( request.POST, request.FILES, instance=doc, prefix='doc-' + doc_id, user=request.user ) if form.is_valid(): form.save() # Reindex the doc to make sure all tags are indexed for backend in get_search_backends(): backend.add(doc) return JsonResponse({ 'success': True, 'doc_id': int(doc_id), }) else: return JsonResponse({ 'success': False, 'doc_id': int(doc_id), 'form': render_to_string('wagtaildocs/multiple/edit_form.html', { 'doc': doc, 'form': form, }, request=request), }) @require_POST def delete(request, doc_id): Document = get_document_model() doc = get_object_or_404(Document, id=doc_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if not permission_policy.user_has_permission_for_instance(request.user, 'delete', doc): raise PermissionDenied doc.delete() return JsonResponse({ 'success': True, 'doc_id': int(doc_id), })
azaghal/ansible
refs/heads/devel
test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py
38
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: test_docs_removed_precedence short_description: Test module description: - Test module author: - Ansible Core Team deprecated: alternative: new_module why: Updated module released with more functionality removed_at_date: '2022-06-01' removed_in: '2.14' ''' EXAMPLES = ''' ''' RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict(), ) module.exit_json() if __name__ == '__main__': main()
Grirrane/odoo
refs/heads/master
addons/l10n_ma/__init__.py
8
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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/>. # ############################################################################## import l10n_ma
xiandiancloud/edxplaltfom-xusong
refs/heads/master
common/lib/xmodule/xmodule/modulestore/mixed.py
2
""" MixedModuleStore allows for aggregation between multiple modulestores. In this way, courses can be served up both - say - XMLModuleStore or MongoModuleStore """ import logging from contextlib import contextmanager import itertools import functools from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey from . import ModuleStoreWriteBase from . import ModuleStoreEnum from .exceptions import ItemNotFoundError, DuplicateCourseError from .draft_and_published import ModuleStoreDraftAndPublished from .split_migrator import SplitMigrator log = logging.getLogger(__name__) def strip_key(func): """ A decorator for stripping version and branch information from return values that are, or contain, UsageKeys or CourseKeys. Additionally, the decorated function is called with an optional 'field_decorator' parameter that can be used to strip any location(-containing) fields, which are not directly returned by the function. The behavior can be controlled by passing 'remove_version' and 'remove_branch' booleans to the decorated function's kwargs. """ @functools.wraps(func) def inner(*args, **kwargs): """ Supported kwargs: remove_version - If True, calls 'version_agnostic' on all return values, including those in lists and dicts. remove_branch - If True, calls 'for_branch(None)' on all return values, including those in lists and dicts. Note: The 'field_decorator' parameter passed to the decorated function is a function that honors the values of these kwargs. """ # remove version and branch, by default rem_vers = kwargs.pop('remove_version', True) rem_branch = kwargs.pop('remove_branch', True) # helper function for stripping individual values def strip_key_func(val): """ Strips the version and branch information according to the settings of rem_vers and rem_branch. Recursively calls this function if the given value has a 'location' attribute. """ retval = val if rem_vers and hasattr(retval, 'version_agnostic'): retval = retval.version_agnostic() if rem_branch and hasattr(retval, 'for_branch'): retval = retval.for_branch(None) if hasattr(retval, 'location'): retval.location = strip_key_func(retval.location) return retval # function for stripping both, collection of, and individual, values def strip_key_collection(field_value): """ Calls strip_key_func for each element in the given value. """ if rem_vers or rem_branch: if isinstance(field_value, list): field_value = [strip_key_func(fv) for fv in field_value] elif isinstance(field_value, dict): for key, val in field_value.iteritems(): field_value[key] = strip_key_func(val) else: field_value = strip_key_func(field_value) return field_value # call the decorated function retval = func(field_decorator=strip_key_collection, *args, **kwargs) # strip the return value return strip_key_collection(retval) return inner class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase): """ ModuleStore knows how to route requests to the right persistence ms """ def __init__(self, contentstore, mappings, stores, i18n_service=None, create_modulestore_instance=None, **kwargs): """ Initialize a MixedModuleStore. Here we look into our passed in kwargs which should be a collection of other modulestore configuration information """ super(MixedModuleStore, self).__init__(contentstore, **kwargs) if create_modulestore_instance is None: raise ValueError('MixedModuleStore constructor must be passed a create_modulestore_instance function') self.modulestores = [] self.mappings = {} for course_id, store_name in mappings.iteritems(): try: self.mappings[CourseKey.from_string(course_id)] = store_name except InvalidKeyError: try: self.mappings[SlashSeparatedCourseKey.from_deprecated_string(course_id)] = store_name except InvalidKeyError: log.exception("Invalid MixedModuleStore configuration. Unable to parse course_id %r", course_id) continue for store_settings in stores: key = store_settings['NAME'] is_xml = 'XMLModuleStore' in store_settings['ENGINE'] if is_xml: # restrict xml to only load courses in mapping store_settings['OPTIONS']['course_ids'] = [ course_key.to_deprecated_string() for course_key, store_key in self.mappings.iteritems() if store_key == key ] store = create_modulestore_instance( store_settings['ENGINE'], self.contentstore, store_settings.get('DOC_STORE_CONFIG', {}), store_settings.get('OPTIONS', {}), i18n_service=i18n_service, ) # replace all named pointers to the store into actual pointers for course_key, store_name in self.mappings.iteritems(): if store_name == key: self.mappings[course_key] = store self.modulestores.append(store) def _clean_course_id_for_mapping(self, course_id): """ In order for mapping to work, the course_id must be minimal--no version, no branch-- as we never store one version or one branch in one ms and another in another ms. :param course_id: the CourseKey """ if hasattr(course_id, 'version_agnostic'): course_id = course_id.version_agnostic() if hasattr(course_id, 'branch'): course_id = course_id.replace(branch=None) return course_id def _get_modulestore_for_courseid(self, course_id=None): """ For a given course_id, look in the mapping table and see if it has been pinned to a particular modulestore If course_id is None, returns the first (ordered) store as the default """ if course_id is not None: course_id = self._clean_course_id_for_mapping(course_id) mapping = self.mappings.get(course_id, None) if mapping is not None: return mapping else: for store in self.modulestores: if store.has_course(course_id): self.mappings[course_id] = store return store # return the default store return self.default_modulestore def _get_modulestore_by_type(self, modulestore_type): """ This method should only really be used by tests and migration scripts when necessary. Returns the module store as requested by type. The type can be a value from ModuleStoreEnum.Type. """ for store in self.modulestores: if store.get_modulestore_type() == modulestore_type: return store return None def fill_in_run(self, course_key): """ Some course_keys are used without runs. This function calls the corresponding fill_in_run function on the appropriate modulestore. """ store = self._get_modulestore_for_courseid(course_key) if not hasattr(store, 'fill_in_run'): return course_key return store.fill_in_run(course_key) def has_item(self, usage_key, **kwargs): """ Does the course include the xblock who's id is reference? """ store = self._get_modulestore_for_courseid(usage_key.course_key) return store.has_item(usage_key, **kwargs) @strip_key def get_item(self, usage_key, depth=0, **kwargs): """ see parent doc """ store = self._get_modulestore_for_courseid(usage_key.course_key) return store.get_item(usage_key, depth, **kwargs) @strip_key def get_items(self, course_key, **kwargs): """ Returns: list of XModuleDescriptor instances for the matching items within the course with the given course_key NOTE: don't use this to look for courses as the course_key is required. Use get_courses. Args: course_key (CourseKey): the course identifier kwargs: settings (dict): fields to look for which have settings scope. Follows same syntax and rules as kwargs below content (dict): fields to look for which have content scope. Follows same syntax and rules as kwargs below. qualifiers (dict): what to look for within the course. Common qualifiers are ``category`` or any field name. if the target field is a list, then it searches for the given value in the list not list equivalence. Substring matching pass a regex object. For some modulestores, ``name`` is another commonly provided key (Location based stores) For some modulestores, you can search by ``edited_by``, ``edited_on`` providing either a datetime for == (probably useless) or a function accepting one arg to do inequality """ if not isinstance(course_key, CourseKey): raise Exception("Must pass in a course_key when calling get_items()") store = self._get_modulestore_for_courseid(course_key) return store.get_items(course_key, **kwargs) @strip_key def get_courses(self, **kwargs): ''' Returns a list containing the top level XModuleDescriptors of the courses in this modulestore. ''' courses = {} for store in self.modulestores: # filter out ones which were fetched from earlier stores but locations may not be == for course in store.get_courses(**kwargs): course_id = self._clean_course_id_for_mapping(course.id) if course_id not in courses: # course is indeed unique. save it in result courses[course_id] = course return courses.values() def make_course_key(self, org, course, run): """ Return a valid :class:`~opaque_keys.edx.keys.CourseKey` for this modulestore that matches the supplied `org`, `course`, and `run`. This key may represent a course that doesn't exist in this modulestore. """ # If there is a mapping that match this org/course/run, use that for course_id, store in self.mappings.iteritems(): candidate_key = store.make_course_key(org, course, run) if candidate_key == course_id: return candidate_key # Otherwise, return the key created by the default store return self.default_modulestore.make_course_key(org, course, run) @strip_key def get_course(self, course_key, depth=0, **kwargs): """ returns the course module associated with the course_id. If no such course exists, it returns None :param course_key: must be a CourseKey """ assert(isinstance(course_key, CourseKey)) store = self._get_modulestore_for_courseid(course_key) try: return store.get_course(course_key, depth=depth, **kwargs) except ItemNotFoundError: return None @strip_key def has_course(self, course_id, ignore_case=False, **kwargs): """ returns the course_id of the course if it was found, else None Note: we return the course_id instead of a boolean here since the found course may have a different id than the given course_id when ignore_case is True. Args: * course_id (CourseKey) * ignore_case (bool): If True, do a case insensitive search. If False, do a case sensitive search """ assert(isinstance(course_id, CourseKey)) store = self._get_modulestore_for_courseid(course_id) return store.has_course(course_id, ignore_case, **kwargs) def delete_course(self, course_key, user_id): """ See xmodule.modulestore.__init__.ModuleStoreWrite.delete_course """ assert(isinstance(course_key, CourseKey)) store = self._get_modulestore_for_courseid(course_key) return store.delete_course(course_key, user_id) @strip_key def get_parent_location(self, location, **kwargs): """ returns the parent locations for a given location """ store = self._get_modulestore_for_courseid(location.course_key) return store.get_parent_location(location, **kwargs) def get_modulestore_type(self, course_id): """ Returns a type which identifies which modulestore is servicing the given course_id. The return can be one of: "xml" (for XML based courses), "mongo" for old-style MongoDB backed courses, "split" for new-style split MongoDB backed courses. """ return self._get_modulestore_for_courseid(course_id).get_modulestore_type() @strip_key def get_orphans(self, course_key, **kwargs): """ Get all of the xblocks in the given course which have no parents and are not of types which are usually orphaned. NOTE: may include xblocks which still have references via xblocks which don't use children to point to their dependents. """ store = self._get_modulestore_for_courseid(course_key) return store.get_orphans(course_key, **kwargs) def get_errored_courses(self): """ Return a dictionary of course_dir -> [(msg, exception_str)], for each course_dir where course loading failed. """ errs = {} for store in self.modulestores: errs.update(store.get_errored_courses()) return errs @strip_key def create_course(self, org, course, run, user_id, **kwargs): """ Creates and returns the course. Args: org (str): the organization that owns the course course (str): the name of the course run (str): the name of the run user_id: id of the user creating the course fields (dict): Fields to set on the course at initialization kwargs: Any optional arguments understood by a subset of modulestores to customize instantiation Returns: a CourseDescriptor """ # first make sure an existing course doesn't already exist in the mapping course_key = self.make_course_key(org, course, run) if course_key in self.mappings: raise DuplicateCourseError(course_key, course_key) # create the course store = self._verify_modulestore_support(None, 'create_course') course = store.create_course(org, course, run, user_id, **kwargs) # add new course to the mapping self.mappings[course_key] = store return course @strip_key def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, **kwargs): """ See the superclass for the general documentation. If cloning w/in a store, delegates to that store's clone_course which, in order to be self- sufficient, should handle the asset copying (call the same method as this one does) If cloning between stores, * copy the assets * migrate the courseware """ source_modulestore = self._get_modulestore_for_courseid(source_course_id) # for a temporary period of time, we may want to hardcode dest_modulestore as split if there's a split # to have only course re-runs go to split. This code, however, uses the config'd priority dest_modulestore = self._get_modulestore_for_courseid(dest_course_id) if source_modulestore == dest_modulestore: return source_modulestore.clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) # ensure super's only called once. The delegation above probably calls it; so, don't move # the invocation above the delegation call super(MixedModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) if dest_modulestore.get_modulestore_type() == ModuleStoreEnum.Type.split: split_migrator = SplitMigrator(dest_modulestore, source_modulestore) split_migrator.migrate_mongo_course( source_course_id, user_id, dest_course_id.org, dest_course_id.course, dest_course_id.run, fields, **kwargs ) @strip_key def create_item(self, user_id, course_key, block_type, block_id=None, fields=None, **kwargs): """ Creates and saves a new item in a course. Returns the newly created item. Args: user_id: ID of the user creating and saving the xmodule course_key: A :class:`~opaque_keys.edx.CourseKey` identifying which course to create this item in block_type: The typo of block to create block_id: a unique identifier for the new item. If not supplied, a new identifier will be generated fields (dict): A dictionary specifying initial values for some or all fields in the newly created block """ modulestore = self._verify_modulestore_support(course_key, 'create_item') return modulestore.create_item(user_id, course_key, block_type, block_id=block_id, fields=fields, **kwargs) @strip_key def create_child(self, user_id, parent_usage_key, block_type, block_id=None, fields=None, **kwargs): """ Creates and saves a new xblock that is a child of the specified block Returns the newly created item. Args: user_id: ID of the user creating and saving the xmodule parent_usage_key: a :class:`~opaque_key.edx.UsageKey` identifying the block that this item should be parented under block_type: The typo of block to create block_id: a unique identifier for the new item. If not supplied, a new identifier will be generated fields (dict): A dictionary specifying initial values for some or all fields in the newly created block """ modulestore = self._verify_modulestore_support(parent_usage_key.course_key, 'create_child') return modulestore.create_child(user_id, parent_usage_key, block_type, block_id=block_id, fields=fields, **kwargs) @strip_key def import_xblock(self, user_id, course_key, block_type, block_id, fields=None, runtime=None, **kwargs): """ See :py:meth `ModuleStoreDraftAndPublished.import_xblock` Defer to the course's modulestore if it supports this method """ store = self._verify_modulestore_support(course_key, 'import_xblock') return store.import_xblock(user_id, course_key, block_type, block_id, fields, runtime) @strip_key def update_item(self, xblock, user_id, allow_not_found=False, **kwargs): """ Update the xblock persisted to be the same as the given for all types of fields (content, children, and metadata) attribute the change to the given user. """ store = self._verify_modulestore_support(xblock.location.course_key, 'update_item') return store.update_item(xblock, user_id, allow_not_found, **kwargs) @strip_key def delete_item(self, location, user_id, **kwargs): """ Delete the given item from persistence. kwargs allow modulestore specific parameters. """ store = self._verify_modulestore_support(location.course_key, 'delete_item') return store.delete_item(location, user_id=user_id, **kwargs) def revert_to_published(self, location, user_id): """ Reverts an item to its last published version (recursively traversing all of its descendants). If no published version exists, a VersionConflictError is thrown. If a published version exists but there is no draft version of this item or any of its descendants, this method is a no-op. :raises InvalidVersionError: if no published version exists for the location specified """ store = self._verify_modulestore_support(location.course_key, 'revert_to_published') return store.revert_to_published(location, user_id) def close_all_connections(self): """ Close all db connections """ for modulestore in self.modulestores: modulestore.close_connections() def _drop_database(self): """ A destructive operation to drop all databases and close all db connections. Intended to be used by test code for cleanup. """ for modulestore in self.modulestores: # drop database if the store supports it (read-only stores do not) if hasattr(modulestore, '_drop_database'): modulestore._drop_database() # pylint: disable=protected-access @strip_key def create_xblock(self, runtime, course_key, block_type, block_id=None, fields=None, **kwargs): """ Create the new xmodule but don't save it. Returns the new module. Args: runtime: :py:class `xblock.runtime` from another xblock in the same course. Providing this significantly speeds up processing (inheritance and subsequent persistence) course_key: :py:class `opaque_keys.CourseKey` block_type: :py:class `string`: the string identifying the xblock type block_id: the string uniquely identifying the block within the given course fields: :py:class `dict` field_name, value pairs for initializing the xblock fields. Values should be the pythonic types not the json serialized ones. """ store = self._verify_modulestore_support(course_key, 'create_xblock') return store.create_xblock(runtime, course_key, block_type, block_id, fields or {}, **kwargs) @strip_key def get_courses_for_wiki(self, wiki_slug, **kwargs): """ Return the list of courses which use this wiki_slug :param wiki_slug: the course wiki root slug :return: list of course keys """ courses = [] for modulestore in self.modulestores: courses.extend(modulestore.get_courses_for_wiki(wiki_slug, **kwargs)) return courses def heartbeat(self): """ Delegate to each modulestore and package the results for the caller. """ # could be done in parallel threads if needed return dict( itertools.chain.from_iterable( store.heartbeat().iteritems() for store in self.modulestores ) ) def compute_publish_state(self, xblock): """ Returns whether this xblock is draft, public, or private. Returns: PublishState.draft - content is in the process of being edited, but still has a previous version deployed to LMS PublishState.public - content is locked and deployed to LMS PublishState.private - content is editable and not deployed to LMS """ course_id = xblock.scope_ids.usage_id.course_key store = self._get_modulestore_for_courseid(course_id) return store.compute_publish_state(xblock) @strip_key def publish(self, location, user_id, **kwargs): """ Save a current draft to the underlying modulestore Returns the newly published item. """ store = self._verify_modulestore_support(location.course_key, 'publish') return store.publish(location, user_id, **kwargs) @strip_key def unpublish(self, location, user_id, **kwargs): """ Save a current draft to the underlying modulestore Returns the newly unpublished item. """ store = self._verify_modulestore_support(location.course_key, 'unpublish') return store.unpublish(location, user_id, **kwargs) def convert_to_draft(self, location, user_id): """ Create a copy of the source and mark its revision as draft. Note: This method is to support the Mongo Modulestore and may be deprecated. :param location: the location of the source (its revision must be None) """ store = self._verify_modulestore_support(location.course_key, 'convert_to_draft') return store.convert_to_draft(location, user_id) def has_changes(self, xblock): """ Checks if the given block has unpublished changes :param xblock: the block to check :return: True if the draft and published versions differ """ store = self._verify_modulestore_support(xblock.location.course_key, 'has_changes') return store.has_changes(xblock) def _verify_modulestore_support(self, course_key, method): """ Finds and returns the store that contains the course for the given location, and verifying that the store supports the given method. Raises NotImplementedError if the found store does not support the given method. """ store = self._get_modulestore_for_courseid(course_key) if hasattr(store, method): return store else: raise NotImplementedError(u"Cannot call {} on store {}".format(method, store)) @property def default_modulestore(self): """ Return the default modulestore """ thread_local_default_store = getattr(self.thread_cache, 'default_store', None) if thread_local_default_store: # return the thread-local cache, if found return thread_local_default_store else: # else return the default store return self.modulestores[0] @contextmanager def default_store(self, store_type): """ A context manager for temporarily changing the default store in the Mixed modulestore to the given store type """ # find the store corresponding to the given type store = next((store for store in self.modulestores if store.get_modulestore_type() == store_type), None) if not store: raise Exception(u"Cannot find store of type {}".format(store_type)) prev_thread_local_store = getattr(self.thread_cache, 'default_store', None) try: self.thread_cache.default_store = store yield finally: self.thread_cache.default_store = prev_thread_local_store @contextmanager def branch_setting(self, branch_setting, course_id=None): """ A context manager for temporarily setting the branch value for the given course' store to the given branch_setting. If course_id is None, the default store is used. """ store = self._verify_modulestore_support(course_id, 'branch_setting') with store.branch_setting(branch_setting, course_id): yield @contextmanager def bulk_write_operations(self, course_id): """ A context manager for notifying the store of bulk write events. If course_id is None, the default store is used. """ store = self._get_modulestore_for_courseid(course_id) with store.bulk_write_operations(course_id): yield
CuonDeveloper/cuon
refs/heads/master
cuon_client/CUON/cuon/Databases/xbase.py
7
import struct, datetime, decimal, itertools def dbfreader(f): """Returns an iterator over records in a Xbase DBF file. The first row returned contains the field names. The second row contains field specs: (type, size, decimal places). Subsequent rows contain the data records. If a record is marked as deleted, it is skipped. File should be opened for binary reads. """ # See DBF format spec at: # http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32)) numfields = (lenheader - 33) // 32 fields = [] for fieldno in xrange(numfields): name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32)) name = name.replace('\0', '') # eliminate NULs from string fields.append((name, typ, size, deci)) yield [field[0] for field in fields] yield [tuple(field[1:]) for field in fields] terminator = f.read(1) assert terminator == '\r' fields.insert(0, ('DeletionFlag', 'C', 1, 0)) fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields]) fmtsiz = struct.calcsize(fmt) for i in xrange(numrec): record = struct.unpack(fmt, f.read(fmtsiz)) if record[0] != ' ': continue # deleted record result = [] for (name, typ, size, deci), value in itertools.izip(fields, record): print value if name == 'DeletionFlag': continue if typ == "N": value = value.replace('\0', '').lstrip() if value == '': value = 0 elif deci: value = decimal.Decimal(value) else: value = int(value) elif typ == 'D': try: y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8]) value = datetime.date(y, m, d) except: value = `value` elif typ == 'L': value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?' result.append(value) yield result def dbfwriter(f, fieldnames, fieldspecs, records): """ Return a string suitable for writing directly to a binary dbf file. File f should be open for writing in a binary mode. Fieldnames should be no longer than ten characters and not include \x00. Fieldspecs are in the form (type, size, deci) where type is one of: C for ascii character data M for ascii character memo data (real memo fields not supported) D for datetime objects N for ints or decimal objects L for logical values 'T', 'F', or '?' size is the field width deci is the number of decimal places in the provided decimal object Records can be an iterable over the records (sequences of field values). """ # header info ver = 3 now = datetime.datetime.now() yr, mon, day = now.year-1900, now.month, now.day numrec = len(records) numfields = len(fieldspecs) lenheader = numfields * 32 + 33 lenrecord = sum(field[1] for field in fieldspecs) + 1 hdr = struct.pack('<BBBBLHH20x', ver, yr, mon, day, numrec, lenheader, lenrecord) f.write(hdr) # field specs for name, (typ, size, deci) in itertools.izip(fieldnames, fieldspecs): name = name.ljust(11, '\x00') fld = struct.pack('<11sc4xBB14x', name, typ, size, deci) f.write(fld) # terminator f.write('\r') # records for record in records: f.write(' ') # deletion flag for (typ, size, deci), value in itertools.izip(fieldspecs, record): if typ == "N": value = str(value).rjust(size, ' ') elif typ == 'D': value = value.strftime('%Y%m%d') elif typ == 'L': value = str(value)[0].upper() else: value = str(value)[:size].ljust(size, ' ') assert len(value) == size f.write(value) # End of file f.write('\x1A') # ------------------------------------------------------- # Example calls if __name__ == '__main__': import sys, csv from cStringIO import StringIO from operator import itemgetter # Read a database filename = '/home/jhamel/test/taxonno.dbf' #if len(sys.argv) == 2: # filename = sys.argv[1] f = open(filename, 'rb') db = list(dbfreader(f)) f.close() for record in db: print record fieldnames, fieldspecs, records = db[0], db[1], db[2:] ## # Alter the database ## del records[4] ## records.sort(key=itemgetter(4)) ## ## # Remove a field ## del fieldnames[0] ## del fieldspecs[0] ## records = [rec[1:] for rec in records] ## ## # Create a new DBF ## f = StringIO() ## dbfwriter(f, fieldnames, fieldspecs, records) ## ## # Read the data back from the new DBF ## print '-' * 20 ## f.seek(0) ## for line in dbfreader(f): ## print line ## f.close() ## ## # Convert to CSV ## print '.' * 20 ## f = StringIO() ## csv.writer(f).writerow(fieldnames) ## csv.writer(f).writerows(records) ## print f.getvalue() ## f.close()
spark0001/spark2.1.1
refs/heads/master
examples/src/main/python/sql/streaming/structured_network_wordcount_windowed.py
76
# # 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. # """ Counts words in UTF8 encoded, '\n' delimited text received from the network over a sliding window of configurable duration. Each line from the network is tagged with a timestamp that is used to determine the windows into which it falls. Usage: structured_network_wordcount_windowed.py <hostname> <port> <window duration> [<slide duration>] <hostname> and <port> describe the TCP server that Structured Streaming would connect to receive data. <window duration> gives the size of window, specified as integer number of seconds <slide duration> gives the amount of time successive windows are offset from one another, given in the same units as above. <slide duration> should be less than or equal to <window duration>. If the two are equal, successive windows have no overlap. If <slide duration> is not provided, it defaults to <window duration>. To run this on your local machine, you need to first run a Netcat server `$ nc -lk 9999` and then run the example `$ bin/spark-submit examples/src/main/python/sql/streaming/structured_network_wordcount_windowed.py localhost 9999 <window duration> [<slide duration>]` One recommended <window duration>, <slide duration> pair is 10, 5 """ from __future__ import print_function import sys from pyspark.sql import SparkSession from pyspark.sql.functions import explode from pyspark.sql.functions import split from pyspark.sql.functions import window if __name__ == "__main__": if len(sys.argv) != 5 and len(sys.argv) != 4: msg = ("Usage: structured_network_wordcount_windowed.py <hostname> <port> " "<window duration in seconds> [<slide duration in seconds>]") print(msg, file=sys.stderr) exit(-1) host = sys.argv[1] port = int(sys.argv[2]) windowSize = int(sys.argv[3]) slideSize = int(sys.argv[4]) if (len(sys.argv) == 5) else windowSize if slideSize > windowSize: print("<slide duration> must be less than or equal to <window duration>", file=sys.stderr) windowDuration = '{} seconds'.format(windowSize) slideDuration = '{} seconds'.format(slideSize) spark = SparkSession\ .builder\ .appName("StructuredNetworkWordCountWindowed")\ .getOrCreate() # Create DataFrame representing the stream of input lines from connection to host:port lines = spark\ .readStream\ .format('socket')\ .option('host', host)\ .option('port', port)\ .option('includeTimestamp', 'true')\ .load() # Split the lines into words, retaining timestamps # split() splits each line into an array, and explode() turns the array into multiple rows words = lines.select( explode(split(lines.value, ' ')).alias('word'), lines.timestamp ) # Group the data by window and word and compute the count of each group windowedCounts = words.groupBy( window(words.timestamp, windowDuration, slideDuration), words.word ).count().orderBy('window') # Start running the query that prints the windowed word counts to the console query = windowedCounts\ .writeStream\ .outputMode('complete')\ .format('console')\ .option('truncate', 'false')\ .start() query.awaitTermination()
neutrongenious/xrt
refs/heads/master
X-Art Parser/beautifulsoup4-4.3.1/bs4/tests/test_docs.py
607
"Test harness for doctests." # pylint: disable-msg=E0611,W0142 __metaclass__ = type __all__ = [ 'additional_tests', ] import atexit import doctest import os #from pkg_resources import ( # resource_filename, resource_exists, resource_listdir, cleanup_resources) import unittest DOCTEST_FLAGS = ( doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF) # def additional_tests(): # "Run the doc tests (README.txt and docs/*, if any exist)" # doctest_files = [ # os.path.abspath(resource_filename('bs4', 'README.txt'))] # if resource_exists('bs4', 'docs'): # for name in resource_listdir('bs4', 'docs'): # if name.endswith('.txt'): # doctest_files.append( # os.path.abspath( # resource_filename('bs4', 'docs/%s' % name))) # kwargs = dict(module_relative=False, optionflags=DOCTEST_FLAGS) # atexit.register(cleanup_resources) # return unittest.TestSuite(( # doctest.DocFileSuite(*doctest_files, **kwargs)))
40223234/40223234
refs/heads/master
static/Brython3.1.1-20150328-091302/Lib/unittest/test/testmock/testhelpers.py
737
import unittest from unittest.mock import ( call, _Call, create_autospec, MagicMock, Mock, ANY, _CallList, patch, PropertyMock ) from datetime import datetime class SomeClass(object): def one(self, a, b): pass def two(self): pass def three(self, a=None): pass class AnyTest(unittest.TestCase): def test_any(self): self.assertEqual(ANY, object()) mock = Mock() mock(ANY) mock.assert_called_with(ANY) mock = Mock() mock(foo=ANY) mock.assert_called_with(foo=ANY) def test_repr(self): self.assertEqual(repr(ANY), '<ANY>') self.assertEqual(str(ANY), '<ANY>') def test_any_and_datetime(self): mock = Mock() mock(datetime.now(), foo=datetime.now()) mock.assert_called_with(ANY, foo=ANY) def test_any_mock_calls_comparison_order(self): mock = Mock() d = datetime.now() class Foo(object): def __eq__(self, other): return False def __ne__(self, other): return True for d in datetime.now(), Foo(): mock.reset_mock() mock(d, foo=d, bar=d) mock.method(d, zinga=d, alpha=d) mock().method(a1=d, z99=d) expected = [ call(ANY, foo=ANY, bar=ANY), call.method(ANY, zinga=ANY, alpha=ANY), call(), call().method(a1=ANY, z99=ANY) ] self.assertEqual(expected, mock.mock_calls) self.assertEqual(mock.mock_calls, expected) class CallTest(unittest.TestCase): def test_call_with_call(self): kall = _Call() self.assertEqual(kall, _Call()) self.assertEqual(kall, _Call(('',))) self.assertEqual(kall, _Call(((),))) self.assertEqual(kall, _Call(({},))) self.assertEqual(kall, _Call(('', ()))) self.assertEqual(kall, _Call(('', {}))) self.assertEqual(kall, _Call(('', (), {}))) self.assertEqual(kall, _Call(('foo',))) self.assertEqual(kall, _Call(('bar', ()))) self.assertEqual(kall, _Call(('baz', {}))) self.assertEqual(kall, _Call(('spam', (), {}))) kall = _Call(((1, 2, 3),)) self.assertEqual(kall, _Call(((1, 2, 3),))) self.assertEqual(kall, _Call(('', (1, 2, 3)))) self.assertEqual(kall, _Call(((1, 2, 3), {}))) self.assertEqual(kall, _Call(('', (1, 2, 3), {}))) kall = _Call(((1, 2, 4),)) self.assertNotEqual(kall, _Call(('', (1, 2, 3)))) self.assertNotEqual(kall, _Call(('', (1, 2, 3), {}))) kall = _Call(('foo', (1, 2, 4),)) self.assertNotEqual(kall, _Call(('', (1, 2, 4)))) self.assertNotEqual(kall, _Call(('', (1, 2, 4), {}))) self.assertNotEqual(kall, _Call(('bar', (1, 2, 4)))) self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {}))) kall = _Call(({'a': 3},)) self.assertEqual(kall, _Call(('', (), {'a': 3}))) self.assertEqual(kall, _Call(('', {'a': 3}))) self.assertEqual(kall, _Call(((), {'a': 3}))) self.assertEqual(kall, _Call(({'a': 3},))) def test_empty__Call(self): args = _Call() self.assertEqual(args, ()) self.assertEqual(args, ('foo',)) self.assertEqual(args, ((),)) self.assertEqual(args, ('foo', ())) self.assertEqual(args, ('foo',(), {})) self.assertEqual(args, ('foo', {})) self.assertEqual(args, ({},)) def test_named_empty_call(self): args = _Call(('foo', (), {})) self.assertEqual(args, ('foo',)) self.assertEqual(args, ('foo', ())) self.assertEqual(args, ('foo',(), {})) self.assertEqual(args, ('foo', {})) self.assertNotEqual(args, ((),)) self.assertNotEqual(args, ()) self.assertNotEqual(args, ({},)) self.assertNotEqual(args, ('bar',)) self.assertNotEqual(args, ('bar', ())) self.assertNotEqual(args, ('bar', {})) def test_call_with_args(self): args = _Call(((1, 2, 3), {})) self.assertEqual(args, ((1, 2, 3),)) self.assertEqual(args, ('foo', (1, 2, 3))) self.assertEqual(args, ('foo', (1, 2, 3), {})) self.assertEqual(args, ((1, 2, 3), {})) def test_named_call_with_args(self): args = _Call(('foo', (1, 2, 3), {})) self.assertEqual(args, ('foo', (1, 2, 3))) self.assertEqual(args, ('foo', (1, 2, 3), {})) self.assertNotEqual(args, ((1, 2, 3),)) self.assertNotEqual(args, ((1, 2, 3), {})) def test_call_with_kwargs(self): args = _Call(((), dict(a=3, b=4))) self.assertEqual(args, (dict(a=3, b=4),)) self.assertEqual(args, ('foo', dict(a=3, b=4))) self.assertEqual(args, ('foo', (), dict(a=3, b=4))) self.assertEqual(args, ((), dict(a=3, b=4))) def test_named_call_with_kwargs(self): args = _Call(('foo', (), dict(a=3, b=4))) self.assertEqual(args, ('foo', dict(a=3, b=4))) self.assertEqual(args, ('foo', (), dict(a=3, b=4))) self.assertNotEqual(args, (dict(a=3, b=4),)) self.assertNotEqual(args, ((), dict(a=3, b=4))) def test_call_with_args_call_empty_name(self): args = _Call(((1, 2, 3), {})) self.assertEqual(args, call(1, 2, 3)) self.assertEqual(call(1, 2, 3), args) self.assertTrue(call(1, 2, 3) in [args]) def test_call_ne(self): self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2)) self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3)) self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3)) def test_call_non_tuples(self): kall = _Call(((1, 2, 3),)) for value in 1, None, self, int: self.assertNotEqual(kall, value) self.assertFalse(kall == value) def test_repr(self): self.assertEqual(repr(_Call()), 'call()') self.assertEqual(repr(_Call(('foo',))), 'call.foo()') self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))), "call(1, 2, 3, a='b')") self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))), "call.bar(1, 2, 3, a='b')") self.assertEqual(repr(call), 'call') self.assertEqual(str(call), 'call') self.assertEqual(repr(call()), 'call()') self.assertEqual(repr(call(1)), 'call(1)') self.assertEqual(repr(call(zz='thing')), "call(zz='thing')") self.assertEqual(repr(call().foo), 'call().foo') self.assertEqual(repr(call(1).foo.bar(a=3).bing), 'call().foo.bar().bing') self.assertEqual( repr(call().foo(1, 2, a=3)), "call().foo(1, 2, a=3)" ) self.assertEqual(repr(call()()), "call()()") self.assertEqual(repr(call(1)(2)), "call()(2)") self.assertEqual( repr(call()().bar().baz.beep(1)), "call()().bar().baz.beep(1)" ) def test_call(self): self.assertEqual(call(), ('', (), {})) self.assertEqual(call('foo', 'bar', one=3, two=4), ('', ('foo', 'bar'), {'one': 3, 'two': 4})) mock = Mock() mock(1, 2, 3) mock(a=3, b=6) self.assertEqual(mock.call_args_list, [call(1, 2, 3), call(a=3, b=6)]) def test_attribute_call(self): self.assertEqual(call.foo(1), ('foo', (1,), {})) self.assertEqual(call.bar.baz(fish='eggs'), ('bar.baz', (), {'fish': 'eggs'})) mock = Mock() mock.foo(1, 2 ,3) mock.bar.baz(a=3, b=6) self.assertEqual(mock.method_calls, [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)]) def test_extended_call(self): result = call(1).foo(2).bar(3, a=4) self.assertEqual(result, ('().foo().bar', (3,), dict(a=4))) mock = MagicMock() mock(1, 2, a=3, b=4) self.assertEqual(mock.call_args, call(1, 2, a=3, b=4)) self.assertNotEqual(mock.call_args, call(1, 2, 3)) self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)]) self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)]) mock = MagicMock() mock.foo(1).bar()().baz.beep(a=6) last_call = call.foo(1).bar()().baz.beep(a=6) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock.mock_calls, last_call.call_list()) def test_call_list(self): mock = MagicMock() mock(1) self.assertEqual(call(1).call_list(), mock.mock_calls) mock = MagicMock() mock(1).method(2) self.assertEqual(call(1).method(2).call_list(), mock.mock_calls) mock = MagicMock() mock(1).method(2)(3) self.assertEqual(call(1).method(2)(3).call_list(), mock.mock_calls) mock = MagicMock() int(mock(1).method(2)(3).foo.bar.baz(4)(5)) kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__() self.assertEqual(kall.call_list(), mock.mock_calls) def test_call_any(self): self.assertEqual(call, ANY) m = MagicMock() int(m) self.assertEqual(m.mock_calls, [ANY]) self.assertEqual([ANY], m.mock_calls) def test_two_args_call(self): args = _Call(((1, 2), {'a': 3}), two=True) self.assertEqual(len(args), 2) self.assertEqual(args[0], (1, 2)) self.assertEqual(args[1], {'a': 3}) other_args = _Call(((1, 2), {'a': 3})) self.assertEqual(args, other_args) class SpecSignatureTest(unittest.TestCase): def _check_someclass_mock(self, mock): self.assertRaises(AttributeError, getattr, mock, 'foo') mock.one(1, 2) mock.one.assert_called_with(1, 2) self.assertRaises(AssertionError, mock.one.assert_called_with, 3, 4) self.assertRaises(TypeError, mock.one, 1) mock.two() mock.two.assert_called_with() self.assertRaises(AssertionError, mock.two.assert_called_with, 3) self.assertRaises(TypeError, mock.two, 1) mock.three() mock.three.assert_called_with() self.assertRaises(AssertionError, mock.three.assert_called_with, 3) self.assertRaises(TypeError, mock.three, 3, 2) mock.three(1) mock.three.assert_called_with(1) mock.three(a=1) mock.three.assert_called_with(a=1) def test_basic(self): for spec in (SomeClass, SomeClass()): mock = create_autospec(spec) self._check_someclass_mock(mock) def test_create_autospec_return_value(self): def f(): pass mock = create_autospec(f, return_value='foo') self.assertEqual(mock(), 'foo') class Foo(object): pass mock = create_autospec(Foo, return_value='foo') self.assertEqual(mock(), 'foo') def test_autospec_reset_mock(self): m = create_autospec(int) int(m) m.reset_mock() self.assertEqual(m.__int__.call_count, 0) def test_mocking_unbound_methods(self): class Foo(object): def foo(self, foo): pass p = patch.object(Foo, 'foo') mock_foo = p.start() Foo().foo(1) mock_foo.assert_called_with(1) def test_create_autospec_unbound_methods(self): # see mock issue 128 # this is expected to fail until the issue is fixed return class Foo(object): def foo(self): pass klass = create_autospec(Foo) instance = klass() self.assertRaises(TypeError, instance.foo, 1) # Note: no type checking on the "self" parameter klass.foo(1) klass.foo.assert_called_with(1) self.assertRaises(TypeError, klass.foo) def test_create_autospec_keyword_arguments(self): class Foo(object): a = 3 m = create_autospec(Foo, a='3') self.assertEqual(m.a, '3') def test_create_autospec_keyword_only_arguments(self): def foo(a, *, b=None): pass m = create_autospec(foo) m(1) m.assert_called_with(1) self.assertRaises(TypeError, m, 1, 2) m(2, b=3) m.assert_called_with(2, b=3) def test_function_as_instance_attribute(self): obj = SomeClass() def f(a): pass obj.f = f mock = create_autospec(obj) mock.f('bing') mock.f.assert_called_with('bing') def test_spec_as_list(self): # because spec as a list of strings in the mock constructor means # something very different we treat a list instance as the type. mock = create_autospec([]) mock.append('foo') mock.append.assert_called_with('foo') self.assertRaises(AttributeError, getattr, mock, 'foo') class Foo(object): foo = [] mock = create_autospec(Foo) mock.foo.append(3) mock.foo.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.foo, 'foo') def test_attributes(self): class Sub(SomeClass): attr = SomeClass() sub_mock = create_autospec(Sub) for mock in (sub_mock, sub_mock.attr): self._check_someclass_mock(mock) def test_builtin_functions_types(self): # we could replace builtin functions / methods with a function # with *args / **kwargs signature. Using the builtin method type # as a spec seems to work fairly well though. class BuiltinSubclass(list): def bar(self, arg): pass sorted = sorted attr = {} mock = create_autospec(BuiltinSubclass) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.append, 'foo') mock.bar('foo') mock.bar.assert_called_with('foo') self.assertRaises(TypeError, mock.bar, 'foo', 'bar') self.assertRaises(AttributeError, getattr, mock.bar, 'foo') mock.sorted([1, 2]) mock.sorted.assert_called_with([1, 2]) self.assertRaises(AttributeError, getattr, mock.sorted, 'foo') mock.attr.pop(3) mock.attr.pop.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.attr, 'foo') def test_method_calls(self): class Sub(SomeClass): attr = SomeClass() mock = create_autospec(Sub) mock.one(1, 2) mock.two() mock.three(3) expected = [call.one(1, 2), call.two(), call.three(3)] self.assertEqual(mock.method_calls, expected) mock.attr.one(1, 2) mock.attr.two() mock.attr.three(3) expected.extend( [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)] ) self.assertEqual(mock.method_calls, expected) def test_magic_methods(self): class BuiltinSubclass(list): attr = {} mock = create_autospec(BuiltinSubclass) self.assertEqual(list(mock), []) self.assertRaises(TypeError, int, mock) self.assertRaises(TypeError, int, mock.attr) self.assertEqual(list(mock), []) self.assertIsInstance(mock['foo'], MagicMock) self.assertIsInstance(mock.attr['foo'], MagicMock) def test_spec_set(self): class Sub(SomeClass): attr = SomeClass() for spec in (Sub, Sub()): mock = create_autospec(spec, spec_set=True) self._check_someclass_mock(mock) self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar') self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar') def test_descriptors(self): class Foo(object): @classmethod def f(cls, a, b): pass @staticmethod def g(a, b): pass class Bar(Foo): pass class Baz(SomeClass, Bar): pass for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()): mock = create_autospec(spec) mock.f(1, 2) mock.f.assert_called_once_with(1, 2) mock.g(3, 4) mock.g.assert_called_once_with(3, 4) def test_recursive(self): class A(object): def a(self): pass foo = 'foo bar baz' bar = foo A.B = A mock = create_autospec(A) mock() self.assertFalse(mock.B.called) mock.a() mock.B.a() self.assertEqual(mock.method_calls, [call.a(), call.B.a()]) self.assertIs(A.foo, A.bar) self.assertIsNot(mock.foo, mock.bar) mock.foo.lower() self.assertRaises(AssertionError, mock.bar.lower.assert_called_with) def test_spec_inheritance_for_classes(self): class Foo(object): def a(self): pass class Bar(object): def f(self): pass class_mock = create_autospec(Foo) self.assertIsNot(class_mock, class_mock()) for this_mock in class_mock, class_mock(): this_mock.a() this_mock.a.assert_called_with() self.assertRaises(TypeError, this_mock.a, 'foo') self.assertRaises(AttributeError, getattr, this_mock, 'b') instance_mock = create_autospec(Foo()) instance_mock.a() instance_mock.a.assert_called_with() self.assertRaises(TypeError, instance_mock.a, 'foo') self.assertRaises(AttributeError, getattr, instance_mock, 'b') # The return value isn't isn't callable self.assertRaises(TypeError, instance_mock) instance_mock.Bar.f() instance_mock.Bar.f.assert_called_with() self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g') instance_mock.Bar().f() instance_mock.Bar().f.assert_called_with() self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g') def test_inherit(self): class Foo(object): a = 3 Foo.Foo = Foo # class mock = create_autospec(Foo) instance = mock() self.assertRaises(AttributeError, getattr, instance, 'b') attr_instance = mock.Foo() self.assertRaises(AttributeError, getattr, attr_instance, 'b') # instance mock = create_autospec(Foo()) self.assertRaises(AttributeError, getattr, mock, 'b') self.assertRaises(TypeError, mock) # attribute instance call_result = mock.Foo() self.assertRaises(AttributeError, getattr, call_result, 'b') def test_builtins(self): # used to fail with infinite recursion create_autospec(1) create_autospec(int) create_autospec('foo') create_autospec(str) create_autospec({}) create_autospec(dict) create_autospec([]) create_autospec(list) create_autospec(set()) create_autospec(set) create_autospec(1.0) create_autospec(float) create_autospec(1j) create_autospec(complex) create_autospec(False) create_autospec(True) def test_function(self): def f(a, b): pass mock = create_autospec(f) self.assertRaises(TypeError, mock) mock(1, 2) mock.assert_called_with(1, 2) f.f = f mock = create_autospec(f) self.assertRaises(TypeError, mock.f) mock.f(3, 4) mock.f.assert_called_with(3, 4) def test_skip_attributeerrors(self): class Raiser(object): def __get__(self, obj, type=None): if obj is None: raise AttributeError('Can only be accessed via an instance') class RaiserClass(object): raiser = Raiser() @staticmethod def existing(a, b): return a + b s = create_autospec(RaiserClass) self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3)) s.existing(1, 2) self.assertRaises(AttributeError, lambda: s.nonexisting) # check we can fetch the raiser attribute and it has no spec obj = s.raiser obj.foo, obj.bar def test_signature_class(self): class Foo(object): def __init__(self, a, b=3): pass mock = create_autospec(Foo) self.assertRaises(TypeError, mock) mock(1) mock.assert_called_once_with(1) mock(4, 5) mock.assert_called_with(4, 5) def test_class_with_no_init(self): # this used to raise an exception # due to trying to get a signature from object.__init__ class Foo(object): pass create_autospec(Foo) def test_signature_callable(self): class Callable(object): def __init__(self): pass def __call__(self, a): pass mock = create_autospec(Callable) mock() mock.assert_called_once_with() self.assertRaises(TypeError, mock, 'a') instance = mock() self.assertRaises(TypeError, instance) instance(a='a') instance.assert_called_once_with(a='a') instance('a') instance.assert_called_with('a') mock = create_autospec(Callable()) mock(a='a') mock.assert_called_once_with(a='a') self.assertRaises(TypeError, mock) mock('a') mock.assert_called_with('a') def test_signature_noncallable(self): class NonCallable(object): def __init__(self): pass mock = create_autospec(NonCallable) instance = mock() mock.assert_called_once_with() self.assertRaises(TypeError, mock, 'a') self.assertRaises(TypeError, instance) self.assertRaises(TypeError, instance, 'a') mock = create_autospec(NonCallable()) self.assertRaises(TypeError, mock) self.assertRaises(TypeError, mock, 'a') def test_create_autospec_none(self): class Foo(object): bar = None mock = create_autospec(Foo) none = mock.bar self.assertNotIsInstance(none, type(None)) none.foo() none.foo.assert_called_once_with() def test_autospec_functions_with_self_in_odd_place(self): class Foo(object): def f(a, self): pass a = create_autospec(Foo) a.f(self=10) a.f.assert_called_with(self=10) def test_autospec_property(self): class Foo(object): @property def foo(self): return 3 foo = create_autospec(Foo) mock_property = foo.foo # no spec on properties self.assertTrue(isinstance(mock_property, MagicMock)) mock_property(1, 2, 3) mock_property.abc(4, 5, 6) mock_property.assert_called_once_with(1, 2, 3) mock_property.abc.assert_called_once_with(4, 5, 6) def test_autospec_slots(self): class Foo(object): __slots__ = ['a'] foo = create_autospec(Foo) mock_slot = foo.a # no spec on slots mock_slot(1, 2, 3) mock_slot.abc(4, 5, 6) mock_slot.assert_called_once_with(1, 2, 3) mock_slot.abc.assert_called_once_with(4, 5, 6) class TestCallList(unittest.TestCase): def test_args_list_contains_call_list(self): mock = Mock() self.assertIsInstance(mock.call_args_list, _CallList) mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) for kall in call(1, 2), call(a=3), call(3, 4), call(b=6): self.assertTrue(kall in mock.call_args_list) calls = [call(a=3), call(3, 4)] self.assertTrue(calls in mock.call_args_list) calls = [call(1, 2), call(a=3)] self.assertTrue(calls in mock.call_args_list) calls = [call(3, 4), call(b=6)] self.assertTrue(calls in mock.call_args_list) calls = [call(3, 4)] self.assertTrue(calls in mock.call_args_list) self.assertFalse(call('fish') in mock.call_args_list) self.assertFalse([call('fish')] in mock.call_args_list) def test_call_list_str(self): mock = Mock() mock(1, 2) mock.foo(a=3) mock.foo.bar().baz('fish', cat='dog') expected = ( "[call(1, 2),\n" " call.foo(a=3),\n" " call.foo.bar(),\n" " call.foo.bar().baz('fish', cat='dog')]" ) self.assertEqual(str(mock.mock_calls), expected) def test_propertymock(self): p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock) mock = p.start() try: SomeClass.one mock.assert_called_once_with() s = SomeClass() s.one mock.assert_called_with() self.assertEqual(mock.mock_calls, [call(), call()]) s.one = 3 self.assertEqual(mock.mock_calls, [call(), call(), call(3)]) finally: p.stop() def test_propertymock_returnvalue(self): m = MagicMock() p = PropertyMock() type(m).foo = p returned = m.foo p.assert_called_once_with() self.assertIsInstance(returned, MagicMock) self.assertNotIsInstance(returned, PropertyMock) if __name__ == '__main__': unittest.main()
littlstar/chromium.src
refs/heads/nw
content/test/gpu/page_sets/gpu_process_tests.py
34
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class GpuProcessTestsPage(page_module.Page): def __init__(self, url, name, page_set): super(GpuProcessTestsPage, self).__init__(url=url, page_set=page_set, name=name) self.user_agent_type = 'desktop' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) class FunctionalVideoPage(GpuProcessTestsPage): def __init__(self, page_set): super(FunctionalVideoPage, self).__init__( url='file://../../data/gpu/functional_video.html', name='GpuProcess.video', page_set=page_set) def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.WaitForJavaScriptCondition( 'domAutomationController._finished', timeout_in_seconds=30) class GpuProcessTestsPageSet(page_set_module.PageSet): """ Tests that accelerated content triggers the creation of a GPU process """ def __init__(self): super(GpuProcessTestsPageSet, self).__init__( serving_dirs=set(['../../../../content/test/data']), user_agent_type='desktop') urls_and_names_list = [ ('file://../../data/gpu/functional_canvas_demo.html', 'GpuProcess.canvas2d'), ('file://../../data/gpu/functional_3d_css.html', 'GpuProcess.css3d'), ('file://../../data/gpu/functional_webgl.html', 'GpuProcess.webgl') ] for url, name in urls_and_names_list: self.AddPage(GpuProcessTestsPage(url, name, self)) self.AddPage(FunctionalVideoPage(self))
jscott1989/django-allauth
refs/heads/master
allauth/socialaccount/providers/facebook/south_migrations/0004_auto__del_facebookapp__del_facebookaccesstoken__del_unique_facebookacc.py
82
# encoding: utf-8 from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'FacebookAccessToken', fields ['app', 'account'] db.delete_unique('facebook_facebookaccesstoken', ['app_id', 'account_id']) # Deleting model 'FacebookApp' db.delete_table('facebook_facebookapp') # Deleting model 'FacebookAccessToken' db.delete_table('facebook_facebookaccesstoken') # Deleting model 'FacebookAccount' db.delete_table('facebook_facebookaccount') def backwards(self, orm): # Adding model 'FacebookApp' db.create_table('facebook_facebookapp', ( ('application_id', self.gf('django.db.models.fields.CharField')(max_length=80)), ('name', self.gf('django.db.models.fields.CharField')(max_length=40)), ('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'])), ('api_key', self.gf('django.db.models.fields.CharField')(max_length=80)), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('application_secret', self.gf('django.db.models.fields.CharField')(max_length=80)), )) db.send_create_signal('facebook', ['FacebookApp']) # Adding model 'FacebookAccessToken' db.create_table('facebook_facebookaccesstoken', ( ('access_token', self.gf('django.db.models.fields.CharField')(max_length=200)), ('account', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['facebook.FacebookAccount'])), ('app', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['facebook.FacebookApp'])), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), )) db.send_create_signal('facebook', ['FacebookAccessToken']) # Adding unique constraint on 'FacebookAccessToken', fields ['app', 'account'] db.create_unique('facebook_facebookaccesstoken', ['app_id', 'account_id']) # Adding model 'FacebookAccount' db.create_table('facebook_facebookaccount', ( ('socialaccount_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['socialaccount.SocialAccount'], unique=True, primary_key=True)), ('social_id', self.gf('django.db.models.fields.CharField')(max_length=255, unique=True)), ('link', self.gf('django.db.models.fields.URLField')(max_length=200)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), )) db.send_create_signal('facebook', ['FacebookAccount']) models = { } complete_apps = ['facebook']
Itxaka/st2
refs/heads/master
st2common/tests/resources/loadableplugin/plugin/sampleplugin.py
26
import plugin.util.randomutil class SamplePlugin(object): def __init__(self): self.__count = 10 def do_work(self): return plugin.util.randomutil.get_random_numbers(self.__count)
lexyan/SickBeard
refs/heads/master
sickbeard/gh_api.py
8
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. try: import json except ImportError: from lib import simplejson as json import urllib class GitHub(object): """ Simple api wrapper for the Github API v3. Currently only supports the small thing that SB needs it for - list of cimmots. """ def _access_API(self, path, params=None): """ Access the API at the path given and with the optional params given. path: A list of the path elements to use (eg. ['repos', 'midgetspy', 'Sick-Beard', 'commits']) params: Optional dict of name/value pairs for extra params to send. (eg. {'per_page': 10}) Returns a deserialized json object of the result. Doesn't do any error checking (hope it works). """ url = 'https://api.github.com/' + '/'.join(path) if params and type(params) is dict: url += '?' + '&'.join([str(x) + '=' + str(params[x]) for x in params.keys()]) return json.load(urllib.urlopen(url)) def commits(self, user, repo, branch='master'): """ Uses the API to get a list of the 100 most recent commits from the specified user/repo/branch, starting from HEAD. user: The github username of the person whose repo you're querying repo: The repo name to query branch: Optional, the branch name to show commits from Returns a deserialized json object containing the commit info. See http://developer.github.com/v3/repos/commits/ """ return self._access_API(['repos', user, repo, 'commits'], {'per_page': 100, 'sha': branch})
grnet/ac16
refs/heads/master
src/verifier.py
1
import prover from bplib.bp import GTElem def step1(gk, A1, A2, g1_sum, g2_sum): return prover.step1c(gk, A1, A2, g1_sum, g2_sum) def step2(gk, n): p1 = [gk.q.random() for i in range(n)] p2 = [gk.q.random() for j in range(3)] p3 = [[gk.q.random() for j in range(3)] for i in range(n)] p4 = [gk.q.random() for j in range(3)] return p1, p2, p3, p4 def get_infT(gk): return GTElem.one(gk.G) def step3(gk, e, A1, A2, p1, pi_1sp, g1alpha, g2alpha, g2rho, pair_alpha): inf1, inf2 = prover.get_infs(gk) infT = get_infT(gk) prodT = infT prod1 = inf1 sum_p = 0 for (Ai1, Ai2, p1i, pi_1spi) in zip(A1, A2, p1, pi_1sp): prodT *= e(p1i * (Ai1 + g1alpha), Ai2 + g2alpha) prod1 += p1i * pi_1spi sum_p = (sum_p + p1i) % gk.q right = e(prod1, g2rho) * (pair_alpha ** sum_p) return prodT == right def step4(gk, e, p2, p3, pi_c2_1, pi_c2_2, v_primes, g1rho, g2beta): inf1, inf2 = prover.get_infs(gk) def pi_c_prod(inf, pi_c2_): prod_c2_ = inf for (p2j, pi_c2_j) in zip(p2, pi_c2_): prod_c2_ += p2j * pi_c2_j return prod_c2_ def nested_prods(inf, flag): outer_prod = inf for vi_prime, p3i in zip(v_primes, p3): inner_prod = inf vi_f_prime = vi_prime[flag] for (vi_f_prime_j, p3ij) in zip(vi_f_prime, p3i): inner_prod += p3ij * vi_f_prime_j outer_prod += inner_prod return outer_prod left = e(g1rho, pi_c_prod(inf2, pi_c2_2) + nested_prods(inf2, 1)) right = e(pi_c_prod(inf1, pi_c2_1) + nested_prods(inf1, 0), g2beta) return left == right def step5(gk, pk1, g2rho, pi_c1_1, pi_c1_2, pi_c2_1, e, p4): inf1, _ = prover.get_infs(gk) g1hat, h1 = pk1 pair1 = e(g1hat, p4[1] * pi_c1_2 + p4[2] * (pi_c1_1 + pi_c1_2)) pair2 = e(h1, p4[0] * pi_c1_1 + p4[1] * pi_c1_2) prod = inf1 for (p4j, pi_c2_1j) in zip(p4, pi_c2_1): prod += p4j * pi_c2_1j pair3 = e(prod, g2rho) return pair1 * pair2 * pair3.inv() def step6(gk, e, vs, v_primes, A2, p4, R, g2_polys): def do_inner(vi): vi1 = vi[0] inf1, _ = prover.get_infs(gk) inner_prod = inf1 for (p4j, vi1j) in zip(p4, vi1): inner_prod += p4j * vi1j return inner_prod infT = get_infT(gk) outer_numer = infT for (vi_prime, g2_poly_i) in zip(v_primes, g2_polys): outer_numer *= e(do_inner(vi_prime), g2_poly_i) outer_denom = infT for (vi, Ai2) in zip(vs, A2): outer_denom *= e(do_inner(vi), Ai2) return outer_numer * outer_denom.inv() == R def verify(n, crs, vs, v_primes, A1, A2, pi_1sp, pi_c1_1, pi_c1_2, pi_c2_1, pi_c2_2): gk = crs.gk A1, A2 = step1(gk, A1, A2, crs.g1_sum, crs.g2_sum) p1, p2, p3, p4 = step2(gk, n) perm_ok = step3(gk, gk.e, A1, A2, p1, pi_1sp, crs.g1alpha, crs.g2alpha, crs.g2rho, crs.pair_alpha) valid = step4( gk, gk.e, p2, p3, pi_c2_1, pi_c2_2, v_primes, crs.g1rho, crs.g2beta) R = step5(gk, crs.pk1, crs.g2rho, pi_c1_1, pi_c1_2, pi_c2_1, gk.e, p4) consistent = step6(gk, gk.e, vs, v_primes, A2, p4, R, crs.g2_polys) return perm_ok, valid, consistent
benvermaercke/pyqtgraph
refs/heads/develop
pyqtgraph/console/__init__.py
56
from .Console import ConsoleWidget
josephlewis42/autopilot
refs/heads/master
extern/gtest/test/gtest_break_on_failure_unittest.py
2140
#!/usr/bin/env python # # Copyright 2006, 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. """Unit test for Google Test's break-on-failure mode. A user can ask Google Test to seg-fault when an assertion fails, using either the GTEST_BREAK_ON_FAILURE environment variable or the --gtest_break_on_failure flag. This script tests such functionality by invoking gtest_break_on_failure_unittest_ (a program written with Google Test) with different environments and command line flags. """ __author__ = 'wan@google.com (Zhanyong Wan)' import gtest_test_utils import os import sys # Constants. IS_WINDOWS = os.name == 'nt' # The environment variable for enabling/disabling the break-on-failure mode. BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE' # The command line flag for enabling/disabling the break-on-failure mode. BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure' # The environment variable for enabling/disabling the throw-on-failure mode. THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE' # The environment variable for enabling/disabling the catch-exceptions mode. CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS' # Path to the gtest_break_on_failure_unittest_ program. EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'gtest_break_on_failure_unittest_') environ = gtest_test_utils.environ SetEnvVar = gtest_test_utils.SetEnvVar # Tests in this file run a Google-Test-based test program and expect it # to terminate prematurely. Therefore they are incompatible with # the premature-exit-file protocol by design. Unset the # premature-exit filepath to prevent Google Test from creating # the file. SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) def Run(command): """Runs a command; returns 1 if it was killed by a signal, or 0 otherwise.""" p = gtest_test_utils.Subprocess(command, env=environ) if p.terminated_by_signal: return 1 else: return 0 # The tests. class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase): """Tests using the GTEST_BREAK_ON_FAILURE environment variable or the --gtest_break_on_failure flag to turn assertion failures into segmentation faults. """ def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault): """Runs gtest_break_on_failure_unittest_ and verifies that it does (or does not) have a seg-fault. Args: env_var_value: value of the GTEST_BREAK_ON_FAILURE environment variable; None if the variable should be unset. flag_value: value of the --gtest_break_on_failure flag; None if the flag should not be present. expect_seg_fault: 1 if the program is expected to generate a seg-fault; 0 otherwise. """ SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value) if env_var_value is None: env_var_value_msg = ' is not set' else: env_var_value_msg = '=' + env_var_value if flag_value is None: flag = '' elif flag_value == '0': flag = '--%s=0' % BREAK_ON_FAILURE_FLAG else: flag = '--%s' % BREAK_ON_FAILURE_FLAG command = [EXE_PATH] if flag: command.append(flag) if expect_seg_fault: should_or_not = 'should' else: should_or_not = 'should not' has_seg_fault = Run(command) SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None) msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' % (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command), should_or_not)) self.assert_(has_seg_fault == expect_seg_fault, msg) def testDefaultBehavior(self): """Tests the behavior of the default mode.""" self.RunAndVerify(env_var_value=None, flag_value=None, expect_seg_fault=0) def testEnvVar(self): """Tests using the GTEST_BREAK_ON_FAILURE environment variable.""" self.RunAndVerify(env_var_value='0', flag_value=None, expect_seg_fault=0) self.RunAndVerify(env_var_value='1', flag_value=None, expect_seg_fault=1) def testFlag(self): """Tests using the --gtest_break_on_failure flag.""" self.RunAndVerify(env_var_value=None, flag_value='0', expect_seg_fault=0) self.RunAndVerify(env_var_value=None, flag_value='1', expect_seg_fault=1) def testFlagOverridesEnvVar(self): """Tests that the flag overrides the environment variable.""" self.RunAndVerify(env_var_value='0', flag_value='0', expect_seg_fault=0) self.RunAndVerify(env_var_value='0', flag_value='1', expect_seg_fault=1) self.RunAndVerify(env_var_value='1', flag_value='0', expect_seg_fault=0) self.RunAndVerify(env_var_value='1', flag_value='1', expect_seg_fault=1) def testBreakOnFailureOverridesThrowOnFailure(self): """Tests that gtest_break_on_failure overrides gtest_throw_on_failure.""" SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1') try: self.RunAndVerify(env_var_value=None, flag_value='1', expect_seg_fault=1) finally: SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None) if IS_WINDOWS: def testCatchExceptionsDoesNotInterfere(self): """Tests that gtest_catch_exceptions doesn't interfere.""" SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1') try: self.RunAndVerify(env_var_value='1', flag_value='1', expect_seg_fault=1) finally: SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None) if __name__ == '__main__': gtest_test_utils.Main()
kaiserroll14/301finalproject
refs/heads/master
testreq/requests/packages/urllib3/exceptions.py
62
## Base Exceptions class HTTPError(Exception): "Base exception used by this module." pass class HTTPWarning(Warning): "Base warning used by this module." pass class PoolError(HTTPError): "Base exception for errors caused within a pool." def __init__(self, pool, message): self.pool = pool HTTPError.__init__(self, "%s: %s" % (pool, message)) def __reduce__(self): # For pickling purposes. return self.__class__, (None, None) class RequestError(PoolError): "Base exception for PoolErrors that have associated URLs." def __init__(self, pool, url, message): self.url = url PoolError.__init__(self, pool, message) def __reduce__(self): # For pickling purposes. return self.__class__, (None, self.url, None) class SSLError(HTTPError): "Raised when SSL certificate fails in an HTTPS connection." pass class ProxyError(HTTPError): "Raised when the connection to a proxy fails." pass class DecodeError(HTTPError): "Raised when automatic decoding based on Content-Type fails." pass class ProtocolError(HTTPError): "Raised when something unexpected happens mid-request/response." pass #: Renamed to ProtocolError but aliased for backwards compatibility. ConnectionError = ProtocolError ## Leaf Exceptions class MaxRetryError(RequestError): """Raised when the maximum number of retries is exceeded. :param pool: The connection pool :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` :param string url: The requested Url :param exceptions.Exception reason: The underlying error """ def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s (Caused by %r)" % ( url, reason) RequestError.__init__(self, pool, url, message) class HostChangedError(RequestError): "Raised when an existing pool gets a request for a foreign host." def __init__(self, pool, url, retries=3): message = "Tried to open a foreign host with url: %s" % url RequestError.__init__(self, pool, url, message) self.retries = retries class TimeoutStateError(HTTPError): """ Raised when passing an invalid state to a timeout """ pass class TimeoutError(HTTPError): """ Raised when a socket timeout error occurs. Catching this error will catch both :exc:`ReadTimeoutErrors <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`. """ pass class ReadTimeoutError(TimeoutError, RequestError): "Raised when a socket timeout occurs while receiving data from a server" pass # This timeout error does not have a URL attached and needs to inherit from the # base HTTPError class ConnectTimeoutError(TimeoutError): "Raised when a socket timeout occurs while connecting to a server" pass class NewConnectionError(ConnectTimeoutError, PoolError): "Raised when we fail to establish a new connection. Usually ECONNREFUSED." pass class EmptyPoolError(PoolError): "Raised when a pool runs out of connections and no more are allowed." pass class ClosedPoolError(PoolError): "Raised when a request enters a pool after the pool has been closed." pass class LocationValueError(ValueError, HTTPError): "Raised when there is something wrong with a given URL input." pass class LocationParseError(LocationValueError): "Raised when get_host or similar fails to parse the URL input." def __init__(self, location): message = "Failed to parse: %s" % location HTTPError.__init__(self, message) self.location = location class ResponseError(HTTPError): "Used as a container for an error reason supplied in a MaxRetryError." GENERIC_ERROR = 'too many error responses' SPECIFIC_ERROR = 'too many {status_code} error responses' class SecurityWarning(HTTPWarning): "Warned when perfoming security reducing actions" pass class SubjectAltNameWarning(SecurityWarning): "Warned when connecting to a host with a certificate missing a SAN." pass class InsecureRequestWarning(SecurityWarning): "Warned when making an unverified HTTPS request." pass class SystemTimeWarning(SecurityWarning): "Warned when system time is suspected to be wrong" pass class InsecurePlatformWarning(SecurityWarning): "Warned when certain SSL configuration is not available on a platform." pass class ResponseNotChunked(ProtocolError, ValueError): "Response needs to be chunked in order to read it as chunks." pass class ProxySchemeUnknown(AssertionError, ValueError): "ProxyManager does not support the supplied scheme" # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. def __init__(self, scheme): message = "Not supported proxy scheme %s" % scheme super(ProxySchemeUnknown, self).__init__(message) class HeaderParsingError(HTTPError): "Raised by assert_header_parsing, but we convert it to a log.warning statement." def __init__(self, defects, unparsed_data): message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data) super(HeaderParsingError, self).__init__(message)
b0ri5/nishe-googlecode
refs/heads/master
scons/scons-local-1.3.0/SCons/Tool/textfile.py
5
# -*- python -*- # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ Textfile/Substfile builder for SCons. Create file 'target' which typically is a textfile. The 'source' may be any combination of strings, Nodes, or lists of same. A 'linesep' will be put between any part written and defaults to os.linesep. The only difference between the Textfile builder and the Substfile builder is that strings are converted to Value() nodes for the former and File() nodes for the latter. To insert files in the former or strings in the latter, wrap them in a File() or Value(), respectively. The values of SUBST_DICT first have any construction variables expanded (its keys are not expanded). If a value of SUBST_DICT is a python callable function, it is called and the result is expanded as the value. Values are substituted in a "random" order; if any substitution could be further expanded by another subsitition, it is unpredictible whether the expansion will occur. """ __revision__ = "src/engine/SCons/Tool/textfile.py 4720 2010/03/24 03:14:11 jars" import SCons import os import re from SCons.Node import Node from SCons.Node.Python import Value from SCons.Util import is_String, is_Sequence, is_Dict def _do_subst(node, subs): """ Fetch the node contents and replace all instances of the keys with their values. For example, if subs is {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'}, then all instances of %VERSION% in the file will be replaced with 1.2345 and so forth. """ contents = node.get_text_contents() if not subs: return contents for (k,v) in subs: contents = re.sub(k, v, contents) return contents def _action(target, source, env): # prepare the line separator linesep = env['LINESEPARATOR'] if linesep is None: linesep = os.linesep elif is_String(linesep): pass elif isinstance(linesep, Value): linesep = linesep.get_text_contents() else: raise SCons.Errors.UserError( 'unexpected type/class for LINESEPARATOR: %s' % repr(linesep), None) # create a dictionary to use for the substitutions if not env.has_key('SUBST_DICT'): subs = None # no substitutions else: d = env['SUBST_DICT'] if is_Dict(d): d = d.items() elif is_Sequence(d): pass else: raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence') subs = [] for (k,v) in d: if callable(v): v = v() if is_String(v): v = env.subst(v) else: v = str(v) subs.append((k,v)) # write the file try: fd = open(target[0].get_path(), "wb") except (OSError,IOError), e: raise SCons.Errors.UserError("Can't write target file %s" % target[0]) # separate lines by 'linesep' only if linesep is not empty lsep = None for s in source: if lsep: fd.write(lsep) fd.write(_do_subst(s, subs)) lsep = linesep fd.close() def _strfunc(target, source, env): return "Creating '%s'" % target[0] def _convert_list_R(newlist, sources): for elem in sources: if is_Sequence(elem): _convert_list_R(newlist, elem) elif isinstance(elem, Node): newlist.append(elem) else: newlist.append(Value(elem)) def _convert_list(target, source, env): if len(target) != 1: raise SCons.Errors.UserError("Only one target file allowed") newlist = [] _convert_list_R(newlist, source) return target, newlist _common_varlist = ['SUBST_DICT', 'LINESEPARATOR'] _text_varlist = _common_varlist + ['TEXTFILEPREFIX', 'TEXTFILESUFFIX'] _text_builder = SCons.Builder.Builder( action = SCons.Action.Action(_action, _strfunc, varlist = _text_varlist), source_factory = Value, emitter = _convert_list, prefix = '$TEXTFILEPREFIX', suffix = '$TEXTFILESUFFIX', ) _subst_varlist = _common_varlist + ['SUBSTFILEPREFIX', 'TEXTFILESUFFIX'] _subst_builder = SCons.Builder.Builder( action = SCons.Action.Action(_action, _strfunc, varlist = _subst_varlist), source_factory = SCons.Node.FS.File, emitter = _convert_list, prefix = '$SUBSTFILEPREFIX', suffix = '$SUBSTFILESUFFIX', src_suffix = ['.in'], ) def generate(env): env['LINESEPARATOR'] = os.linesep env['BUILDERS']['Textfile'] = _text_builder env['TEXTFILEPREFIX'] = '' env['TEXTFILESUFFIX'] = '.txt' env['BUILDERS']['Substfile'] = _subst_builder env['SUBSTFILEPREFIX'] = '' env['SUBSTFILESUFFIX'] = '' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
eayunstack/nova
refs/heads/develop
nova/compute/task_states.py
96
# Copyright 2010 OpenStack Foundation # 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. """Possible task states for instances. Compute instance task states represent what is happening to the instance at the current moment. These tasks can be generic, such as 'spawning', or specific, such as 'block_device_mapping'. These task states allow for a better view into what an instance is doing and should be displayed to users/administrators as necessary. """ # possible task states during create() SCHEDULING = 'scheduling' BLOCK_DEVICE_MAPPING = 'block_device_mapping' NETWORKING = 'networking' SPAWNING = 'spawning' # possible task states during snapshot() IMAGE_SNAPSHOT = 'image_snapshot' IMAGE_SNAPSHOT_PENDING = 'image_snapshot_pending' IMAGE_PENDING_UPLOAD = 'image_pending_upload' IMAGE_UPLOADING = 'image_uploading' # possible task states during backup() IMAGE_BACKUP = 'image_backup' # possible task states during set_admin_password() UPDATING_PASSWORD = 'updating_password' # possible task states during resize() RESIZE_PREP = 'resize_prep' RESIZE_MIGRATING = 'resize_migrating' RESIZE_MIGRATED = 'resize_migrated' RESIZE_FINISH = 'resize_finish' # possible task states during revert_resize() RESIZE_REVERTING = 'resize_reverting' # possible task states during confirm_resize() RESIZE_CONFIRMING = 'resize_confirming' # possible task states during reboot() REBOOTING = 'rebooting' REBOOT_PENDING = 'reboot_pending' REBOOT_STARTED = 'reboot_started' REBOOTING_HARD = 'rebooting_hard' REBOOT_PENDING_HARD = 'reboot_pending_hard' REBOOT_STARTED_HARD = 'reboot_started_hard' # possible task states during pause() PAUSING = 'pausing' # possible task states during unpause() UNPAUSING = 'unpausing' # possible task states during suspend() SUSPENDING = 'suspending' # possible task states during resume() RESUMING = 'resuming' # possible task states during power_off() POWERING_OFF = 'powering-off' # possible task states during power_on() POWERING_ON = 'powering-on' # possible task states during rescue() RESCUING = 'rescuing' # possible task states during unrescue() UNRESCUING = 'unrescuing' # possible task states during rebuild() REBUILDING = 'rebuilding' REBUILD_BLOCK_DEVICE_MAPPING = "rebuild_block_device_mapping" REBUILD_SPAWNING = 'rebuild_spawning' # possible task states during live_migrate() MIGRATING = "migrating" # possible task states during delete() DELETING = 'deleting' # possible task states during soft_delete() SOFT_DELETING = 'soft-deleting' # possible task states during restore() RESTORING = 'restoring' # possible task states during shelve() SHELVING = 'shelving' SHELVING_IMAGE_PENDING_UPLOAD = 'shelving_image_pending_upload' SHELVING_IMAGE_UPLOADING = 'shelving_image_uploading' # possible task states during shelve_offload() SHELVING_OFFLOADING = 'shelving_offloading' # possible task states during unshelve() UNSHELVING = 'unshelving'
skylina/test
refs/heads/master
public/BasePage.py
1
 # -*- coding: utf-8 -*- from selenium.webdriver.support.wait import WebDriverWait from selenium import webdriver __author__ = 'lina' import time import sys import xlrd.sheet import time, os class Action: """ BasePage封装所有页面都公用的方法,例如driver, url """ driver = None # 初始化driver、url、等 def __init__(self, base_url=None, pagetitle=None): self.base_url = base_url self.pagetitle = pagetitle # self.driver = webdriver.Firefox() # self.driver.implicitly_wait(30) # self.driver = driver """ 通过传参选择启动浏览器 # self.browser = "Firefox" #传入浏览器对象 # if Action.driver == None: # if self.browser.upper() == 'IE': Action.driver = webdriver.Ie() # elif self.browser.upper() == 'CHROME': Action.driver = webdriver.Chrome() # elif self.browser.upper() == 'FIREFOX': Action.driver = webdriver.Firefox() # elif self.browser.upper() == 'SAFARI': Action.driver = webdriver.Safari() # else: Action.driver = webdriver.Ie() # Action.driver.maximize_window() # #pass # #print u"加载浏览器驱动失败!" # self.driver = Action.driver self.verificationErrors = [] """ # 打开页面,校验页面链接是否加载正确 def _open(self, url, pagetitle): # 使用get打开访问链接地址 self.driver.get(url) self.driver.maximize_window() # 使用assert进行校验,打开的链接地址是否与配置的地址一致。调用on_page()方法 assert self.on_page(pagetitle), u"打开开页面失败 %s" % url # 重写元素定位方法 def find_element(self, *loc): # return self.driver.find_element(*loc) try: WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element(*loc).is_displayed()) return self.driver.find_element(*loc) except: print (u"%s 页面中未能找到 %s 元素" % (self, loc)) # 重写一组元素定位方法 def find_elements(self, *loc): # return self.driver.find_element(*loc) try: if len(self.driver.find_elements(*loc)): return self.driver.find_elements(*loc) except: print (u"%s 页面中未能找到 %s 元素" % (self, loc)) # 定位一组元素中索引为第i个的元素 i从0开始 def find_elements_i(self, loc, index=None): # return self.driver.find_element(*loc) try: if len(self.driver.find_elements(*loc)): return self.driver.find_elements(*loc)[index] except: print (u"%s 页面中未能找到%s的第 %s 个元素 " % (self, loc, index)) # 重写switch_frame方法 def switch_frame(self, loc): return self.driver.switch_to_frame(loc) # 定义open方法,调用_open()进行打开链接 def open(self): self._open(self.base_url, self.pagetitle) # 使用current_url获取当前窗口Url地址,进行与配置地址作比较,返回比较结果(True False) def on_page(self, pagetitle): return pagetitle in self.driver.title # 定义script方法,用于执行js脚本,范围执行结果 def script(self, src): self.driver.execute_script(src) # 重写定义send_keys方法 def send_keys(self, loc, vaule, clear_first=True, click_first=True): try: if click_first: self.find_element(*loc).click() if clear_first: self.find_element(*loc).clear() self.find_element(*loc).send_keys(vaule) except AttributeError: print (u"%s 页面中未能找到 %s 元素" % (self, loc)) def checkTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: self.saveScreenshot(self.driver, "Error") raise msg else: return False # 读取excel文件的table def setTable(self, filepath, sheetname): """ filepath:文件路径 sheetname:Sheet名称 """ data = xlrd.open_workbook(filepath) # 通过索引顺序获取Excel表 table = data.sheet_by_name(sheetname) return table # 读取xls表格,使用生成器yield进行按行存储 def getTabledata(self, filepath, sheetname): """ filepath:文件路径 sheetname:Sheet名称 """ table = self.setTable(filepath, sheetname) for args in range(1, table.nrows): # 使用生成器 yield yield table.row_values(args) # 获取单元格数据 def getcelldata(self, sheetname, RowNum, ColNum): """ sheetname:表格Sheets名称 RowNum:行号 从0开始 ColNum:列号 从0开始 """ table = self.setTable(sheetname=sheetname) celldata = table.cell_value(RowNum, ColNum) return celldata # 读取元素标签和元素唯一标识 def locate(self, index, filepath="dataEngine\\data.xls", sheetname="element"): """ filepath: 文件路径 sheetno:Sheet编号 index: 元素编号 返回值内容为:("id","inputid")、("xpath","/html/body/header/div[1]/nav")格式 """ table = self.setTable(filepath, sheetname) for i in range(1, table.nrows): if index in table.row_values(i): return table.row_values(i)[1:3] # savePngName:生成图片的名称 def savePngName(self, name): """ name:自定义图片的名称 """ day = time.strftime('%Y-%m-%d', time.localtime(time.time())) fp = "result\\" + day + "\\image" tm = self.saveTime() type = ".png" # 判断存放截图的目录是否存在,如果存在打印并返回目录名称,如果不存在,创建该目录后,再返回目录名称 if os.path.exists(fp): filename = str(fp) + "\\" + str(tm) + str(" ") + str(name) + str(type) print (filename) # print "True" return filename else: os.makedirs(fp) filename = str(fp) + "\\" + str(tm) + str(" ") + str(name) + str(type) print (filename) # print "False" return filename # 获取系统当前时间 def saveTime(self): """ 返回当前系统时间以括号中(2015-11-25 15_21_55)展示 """ return time.strftime('%Y-%m-%d %H_%M_%S', time.localtime(time.time())) # saveScreenshot:通过图片名称,进行截图保存 def saveScreenshot(self, driver , name): """ 快照截图 name:图片名称 """ # 获取当前路径 # print os.getcwd() image = self.driver.save_screenshot(self.savePngName(name)) return image def save_img(self, img_name): pic_name = self.savePngName(img_name) print(pic_name) #filepath = path.join(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))), pic_name) #print(filepath) self.driver.save_screenshot(pic_name) time.sleep(5)
Flimm/linkchecker
refs/heads/master
scripts/update_iana_uri_schemes.py
9
import sys import re import csv import requests iana_uri_schemes = "https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml" # CSV format: URI Scheme,Template,Description,Reference csv_iana_uri_schemes_permanent = 'https://www.iana.org/assignments/uri-schemes/uri-schemes-1.csv' csv_iana_uri_schemes_provisional = 'https://www.iana.org/assignments/uri-schemes/uri-schemes-2.csv' csv_iana_uri_schemes_historical = 'https://www.iana.org/assignments/uri-schemes/uri-schemes-3.csv' iana_uri_schemes_permanent = {} iana_uri_schemes_provisional = {} iana_uri_schemes_historical = {} iana_uri_schemes_other = { "clsid": "Microsoft specific", "find" : "Mozilla specific", "isbn" : "ISBN (int. book numbers)", "javascript": "JavaScript", } filter_uri_schemes_permanent = ( "file", "ftp", "http", "https", "mailto", "news", "nntp", ) template = ''' # from %(uri)s ignored_schemes_permanent = r""" %(permanent)s """ ignored_schemes_provisional = r""" %(provisional)s """ ignored_schemes_historical = r""" %(historical)s """ ignored_schemes_other = r""" %(other)s """ ignored_schemes = "^(%%s%%s%%s%%s)$" %% ( ignored_schemes_permanent, ignored_schemes_provisional, ignored_schemes_historical, ignored_schemes_other, ) ignored_schemes_re = re.compile(ignored_schemes, re.VERBOSE) is_unknown_scheme = ignored_schemes_re.match ''' def main(args): parse_csv_file(csv_iana_uri_schemes_permanent, iana_uri_schemes_permanent) parse_csv_file(csv_iana_uri_schemes_provisional, iana_uri_schemes_provisional) parse_csv_file(csv_iana_uri_schemes_historical, iana_uri_schemes_historical) for scheme in iana_uri_schemes_other: if (scheme in iana_uri_schemes_permanent or scheme in iana_uri_schemes_provisional or scheme in iana_uri_schemes_historical): raise ValueError(scheme) for scheme in filter_uri_schemes_permanent: if scheme in iana_uri_schemes_permanent: del iana_uri_schemes_permanent[scheme] args = dict( uri = iana_uri_schemes, permanent = get_regex(iana_uri_schemes_permanent), provisional = get_regex(iana_uri_schemes_provisional), historical = get_regex(iana_uri_schemes_historical), other = get_regex(iana_uri_schemes_other), ) res = template % args print res return 0 def get_regex(schemes): expr = ["|%s # %s" % (re.escape(scheme).ljust(10), description) for scheme, description in sorted(schemes.items())] return "\n".join(expr) def parse_csv_file(url, res): """Parse given URL and write res with {scheme -> description}""" response = requests.get(url, stream=True) reader = csv.reader(response.iter_lines()) first_row = True for row in reader: if first_row: # skip first row first_row = False else: scheme, template, description, reference = row res[scheme] = description if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
paplorinc/intellij-community
refs/heads/master
python/testData/testRunner/env/unit/test_file.py
83
import unittest class GoodTest(unittest.TestCase): def test_passes(self): self.assertEqual(2+2, 4) class BadTest(unittest.TestCase): def test_fails(self): self.assertEqual(2+2, 5) if __name__ == '__main__': unittest.main()
olafkrawczyk/pwr_so_lab
refs/heads/master
lab9/ex1.py
1
#Olaf Krawczyk 218164 18.05.2017 # W zadanym pliku tekstowym znalezc wszystkie slowa ktore maja pierwsze trzy litery takie same import os import sys import re if len(sys.argv) != 2: print "Niepoprawna liczba argumentow" print "Podaj jedynie sciezke do pliku" sys.exit(1) if not os.path.isfile(sys.argv[1]): print "Argument musi byc plikiem!" sys.exit(1) with open(sys.argv[1], 'r') as f: file = f.readlines() for line in file: for word in line.split(" "): match = re.findall(r"(^([A-Za-z])\2{2,}\w*\s*)", word) if match: print match[0][0]
omnirom/android_external_chromium-org
refs/heads/android-5.1
build/linux/unbundle/replace_gyp_files.py
36
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Replaces gyp files in tree with files from here that make the build use system libraries. """ import optparse import os.path import shutil import sys REPLACEMENTS = { 'use_system_expat': 'third_party/expat/expat.gyp', 'use_system_ffmpeg': 'third_party/ffmpeg/ffmpeg.gyp', 'use_system_flac': 'third_party/flac/flac.gyp', 'use_system_harfbuzz': 'third_party/harfbuzz-ng/harfbuzz.gyp', 'use_system_icu': 'third_party/icu/icu.gyp', 'use_system_jsoncpp': 'third_party/jsoncpp/jsoncpp.gyp', 'use_system_libevent': 'third_party/libevent/libevent.gyp', 'use_system_libjpeg': 'third_party/libjpeg/libjpeg.gyp', 'use_system_libpng': 'third_party/libpng/libpng.gyp', 'use_system_libusb': 'third_party/libusb/libusb.gyp', 'use_system_libvpx': 'third_party/libvpx/libvpx.gyp', 'use_system_libwebp': 'third_party/libwebp/libwebp.gyp', 'use_system_libxml': 'third_party/libxml/libxml.gyp', 'use_system_libxnvctrl' : 'third_party/libXNVCtrl/libXNVCtrl.gyp', 'use_system_libxslt': 'third_party/libxslt/libxslt.gyp', 'use_system_openssl': 'third_party/boringssl/boringssl.gyp', 'use_system_opus': 'third_party/opus/opus.gyp', 'use_system_protobuf': 'third_party/protobuf/protobuf.gyp', 'use_system_re2': 'third_party/re2/re2.gyp', 'use_system_snappy': 'third_party/snappy/snappy.gyp', 'use_system_speex': 'third_party/speex/speex.gyp', 'use_system_sqlite': 'third_party/sqlite/sqlite.gyp', 'use_system_v8': 'v8/tools/gyp/v8.gyp', 'use_system_zlib': 'third_party/zlib/zlib.gyp', } def DoMain(argv): my_dirname = os.path.dirname(__file__) source_tree_root = os.path.abspath( os.path.join(my_dirname, '..', '..', '..')) parser = optparse.OptionParser() # Accept arguments in gyp command-line syntax, so that the caller can re-use # command-line for this script and gyp. parser.add_option('-D', dest='defines', action='append') parser.add_option('--undo', action='store_true') options, args = parser.parse_args(argv) for flag, path in REPLACEMENTS.items(): if '%s=1' % flag not in options.defines: continue if options.undo: # Restore original file, and also remove the backup. # This is meant to restore the source tree to its original state. os.rename(os.path.join(source_tree_root, path + '.orig'), os.path.join(source_tree_root, path)) else: # Create a backup copy for --undo. shutil.copyfile(os.path.join(source_tree_root, path), os.path.join(source_tree_root, path + '.orig')) # Copy the gyp file from directory of this script to target path. shutil.copyfile(os.path.join(my_dirname, os.path.basename(path)), os.path.join(source_tree_root, path)) return 0 if __name__ == '__main__': sys.exit(DoMain(sys.argv))
saradbowman/osf.io
refs/heads/develop
api_tests/osf_groups/views/test_osf_groups_list.py
10
import pytest from waffle.testutils import override_flag from api.base.settings.defaults import API_BASE from osf.models import OSFGroup from osf_tests.factories import ( AuthUserFactory, OSFGroupFactory, ) from osf.features import OSF_GROUPS @pytest.fixture() def user(): return AuthUserFactory() @pytest.fixture() def manager(): return AuthUserFactory() @pytest.fixture() def member(): return AuthUserFactory() @pytest.fixture() def osf_group(manager, member): group = OSFGroupFactory(name='Platform Team', creator=manager) group.make_member(member) return group @pytest.mark.django_db class TestGroupList: @pytest.fixture() def url(self): return '/{}groups/'.format(API_BASE) def test_return(self, app, member, manager, user, osf_group, url): with override_flag(OSF_GROUPS, active=True): # test nonauthenticated res = app.get(url) assert res.status_code == 200 data = res.json['data'] assert len(data) == 0 # test authenticated user res = app.get(url, auth=user.auth) assert res.status_code == 200 data = res.json['data'] assert len(data) == 0 # test authenticated member res = app.get(url, auth=member.auth) assert res.status_code == 200 data = res.json['data'] assert len(data) == 1 assert data[0]['id'] == osf_group._id assert data[0]['type'] == 'groups' assert data[0]['attributes']['name'] == osf_group.name # test authenticated manager res = app.get(url, auth=manager.auth) assert res.status_code == 200 data = res.json['data'] assert len(data) == 1 assert data[0]['id'] == osf_group._id assert data[0]['type'] == 'groups' assert data[0]['attributes']['name'] == osf_group.name def test_groups_filter(self, app, member, manager, user, osf_group, url): with override_flag(OSF_GROUPS, active=True): second_group = OSFGroupFactory(name='Apples', creator=manager) res = app.get(url + '?filter[name]=Platform', auth=manager.auth) assert res.status_code == 200 data = res.json['data'] assert len(data) == 1 assert data[0]['id'] == osf_group._id res = app.get(url + '?filter[name]=Apple', auth=manager.auth) assert res.status_code == 200 data = res.json['data'] assert len(data) == 1 assert data[0]['id'] == second_group._id res = app.get(url + '?filter[bad_field]=Apple', auth=manager.auth, expect_errors=True) assert res.status_code == 400 res = app.get(url + '?filter[name]=Platform') assert res.status_code == 200 data = res.json['data'] assert len(data) == 0 res = app.get(url + '?filter[name]=Apple') assert res.status_code == 200 data = res.json['data'] assert len(data) == 0 @pytest.mark.django_db class TestOSFGroupCreate: @pytest.fixture() def url(self): return '/{}groups/'.format(API_BASE) @pytest.fixture() def simple_payload(self): return { 'data': { 'type': 'groups', 'attributes': { 'name': 'My New Lab' }, } } def test_create_osf_group(self, app, url, manager, simple_payload): # Nonauthenticated with override_flag(OSF_GROUPS, active=True): res = app.post_json_api(url, simple_payload, expect_errors=True) assert res.status_code == 401 # Authenticated res = app.post_json_api(url, simple_payload, auth=manager.auth) assert res.status_code == 201 assert res.json['data']['type'] == 'groups' assert res.json['data']['attributes']['name'] == 'My New Lab' group = OSFGroup.objects.get(_id=res.json['data']['id']) assert group.creator_id == manager.id assert group.has_permission(manager, 'manage') is True assert group.has_permission(manager, 'member') is True def test_create_osf_group_validation_errors(self, app, url, manager, simple_payload): # Need data key with override_flag(OSF_GROUPS, active=True): res = app.post_json_api(url, simple_payload['data'], auth=manager.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Request must include /data.' # Incorrect type simple_payload['data']['type'] = 'incorrect_type' res = app.post_json_api(url, simple_payload, auth=manager.auth, expect_errors=True) assert res.status_code == 409 # Required name field payload = { 'data': { 'type': 'groups' } } res = app.post_json_api(url, payload, auth=manager.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'This field is required.'
smuser90/Stream-Framework
refs/heads/master
stream_framework/metrics/statsd.py
9
from __future__ import absolute_import from stream_framework.metrics.base import Metrics from statsd import StatsClient class StatsdMetrics(Metrics): def __init__(self, host='localhost', port=8125, prefix=None): self.statsd = StatsClient(host, port, prefix) def fanout_timer(self, feed_class): return self.statsd.timer('%s.fanout_latency' % feed_class.__name__) def feed_reads_timer(self, feed_class): return self.statsd.timer('%s.read_latency' % feed_class.__name__) def on_feed_read(self, feed_class, activities_count): self.statsd.incr('%s.reads' % feed_class.__name__, activities_count) def on_feed_write(self, feed_class, activities_count): self.statsd.incr('%s.writes' % feed_class.__name__, activities_count) def on_feed_remove(self, feed_class, activities_count): self.statsd.incr('%s.deletes' % feed_class.__name__, activities_count) def on_fanout(self, feed_class, operation, activities_count=1): metric = (feed_class.__name__, operation.__name__) self.statsd.incr('%s.fanout.%s' % metric, activities_count) def on_activity_published(self): self.statsd.incr('activities.published') def on_activity_removed(self): self.statsd.incr('activities.removed')
SoftwareIntrospectionLab/MininGit
refs/heads/master
pycvsanaly2/CVSParser.py
2
# Copyright (C) 2007 LibreSoft # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Authors : # Alvaro Navarro <anavarro@gsyc.escet.urjc.es> # Gregorio Robles <grex@gsyc.escet.urjc.es> # Carlos Garcia Campos <carlosgc@gsyc.escet.urjc.es> import re import datetime from Parser import Parser from ContentHandler import ContentHandler from Repository import Commit, Action, Person class CVSParser(Parser): """A parser for CVS. # These are a couple of tests for the longer regexes that had # to be split up when trying to get PEP-8 line length compliance >>> p = CVSParser() >>> info = "date: 1999/03/05 07:23:11; author: philg; state: Exp; " + \ "lines: +30 -8" >>> re.match(p.patterns['info'], info) #doctest: +ELLIPSIS <_sre.SRE_Match object...> >>> info = "date: 1999/03/05 07:23:11; author: philg;state: Exp; " + \ "lines: +30 -8" >>> re.match(p.patterns['info'], info) """ CONTENT_ORDER = ContentHandler.ORDER_FILE patterns = {} patterns['file'] = re.compile("^RCS file: (.*)$") patterns['revision'] = re.compile("^revision ([\d\.]*)$") patterns['info'] = re.compile("".join([\ "^date: (\d\d\d\d)[/-](\d\d)[/-](\d\d) (\d\d):(\d\d):(\d\d)(.*); ", "author: (.*); ", "state: ([^;]*);( ", "lines: \+(\d+) -(\d+);?)?"])) patterns['branches'] = re.compile("^branches: ([\d\.]*);$") patterns['branch'] = re.compile("^[ \b\t]+(.*): (([0-9]+\.)+)0\.([0-9]+)$") patterns['tag'] = re.compile("^[ \b\t]+(.*): (([0-9]+\.)+([0-9]+))$") patterns['rev-separator'] = re.compile("^[-]+$") patterns['file-separator'] = re.compile("^[=]+$") def __init__(self): Parser.__init__(self) self.root_path = "" self.lines = {} # Parser context self.file = None self.file_added_on_branch = None self.commit = None self.branches = None self.tags = None self.rev_separator = None self.file_separator = None def set_repository(self, repo, uri): Parser.set_repository(self, repo, uri) uri = repo.get_uri() s = uri.rfind(':') if s >= 0: self.root_path = uri[s + 1:] else: self.root_path = uri def _handle_commit(self): if self.commit is not None: # Remove trailing \n from commit message self.commit.message = self.commit.message[:-1] self.handler.commit(self.commit) self.commit = None def flush(self): self._handle_commit() if self.file is not None: self.handler.file(self.file) self.file_added_on_branch = None self.file = None def get_added_removed_lines(self): return self.lines def _parse_line(self, line): if not line: if self.commit is None: return if self.rev_separator is not None: self.rev_separator += '\n' elif self.file_separator is not None: self.file_separator += '\n' elif self.commit.message is not None: self.commit.message += '\n' return # Revision Separator if self.patterns['rev-separator'].match(line): # Ignore separators so that we don't # include it in the commit message if self.rev_separator is None: self.rev_separator = line else: self.rev_separator += line + '\n' return # File Separator if self.patterns['file-separator'].match(line): # Ignore separators so that we don't # include it in the commit message if self.file_separator is None: self.file_separator = line else: self.file_separator += line + '\n' return # File match = self.patterns['file'].match(line) if match: self.flush() path = match.group(1) path = path[len(self.root_path):] path = path[:path.rfind(',')] self.file = path self.branches = {} self.tags = {} self.commit = None self.file_separator = None return # Branch match = self.patterns['branch'].match(line) if match: self.branches[match.group(2) + match.group(4)] = match.group(1) return # Tag (Keep this always after Branch pattern) match = self.patterns['tag'].match(line) if match: revision = match.group(2) # We are ignoring 1.1.1.1 revisions, # so in case there's a tag pointing to that # revision we have to redirect it to 1.1 revision if revision == '1.1.1.1': revision = '1.1' self.tags.setdefault(revision, []).append(match.group(1)) return # Revision match = self.patterns['revision'].match(line) if match and self.rev_separator is not None: self._handle_commit() revision = match.group(1) commit = Commit() # composed rev: revision + | + file path # to make sure revision is unique commit.composed_rev = True commit.revision = "%s|%s" % (revision, self.file) commit.tags = self.tags.get(revision, None) self.commit = commit self.rev_separator = None return # Commit info (date, author, etc.) match = self.patterns['info'].match(line) if match and self.commit is not None: commit = self.commit revision = commit.revision.split('|')[0] if revision == '1.1.1.1': self.commit = None return commit.committer = Person() commit.committer.name = match.group(8) self.handler.committer(commit.committer) commit.commit_date = datetime.datetime(int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)), int(match.group(5)), int(match.group(6))) if match.group(10) is not None: self.lines[commit.revision] = (int(match.group(11)), int(match.group(12))) else: self.lines[commit.revision] = (0, 0) action = Action() act = match.group(9) if act == 'dead': action.type = 'D' self.file = self.file.replace('/Attic', '') commit.revision = commit.revision.replace('/Attic', '') elif revision == '1.1': action.type = 'A' else: action.type = 'M' action.f1 = self.file # Branch try: last_dot = revision.rfind('.') prefix = revision[:last_dot] branch = self.branches[prefix] if self.file_added_on_branch and \ self.file_added_on_branch == prefix and \ revision[last_dot + 1:] == '1': action.type = 'A' self.file_added_on_branch = None except KeyError: branch = 'trunk' commit.branch = branch commit.actions.append(action) return # Branches match = self.patterns['branches'].match(line) if match: if self.commit is None: return action = self.commit.actions[0] revision = self.commit.revision.split('|')[0] if action.type == 'D' and revision == '1.1': # File added on a branch self.file_added_on_branch = match.group(1) # Discard this commit self.commit = None return # Message. if self.commit is not None: if self.rev_separator is not None: # Previous separator was probably a # false positive self.commit.message += self.rev_separator + '\n' self.rev_separator = None if self.file_separator is not None: # Previous separator was probably a # false positive self.commit.message += self.file_separator + '\n' self.file_separator = None self.commit.message += line + '\n'
onlinecity/phone-iso3166
refs/heads/master
phone_iso3166/country.py
1
from .e164 import mapping from .e212 import networks from .errors import InvalidPhone, InvalidNetwork, InvalidCountry def phone_country(phone): ''' Really simple function to get the ISO-3166-1 country from a phone number The phone number must be in E.164, aka international format. Returns an ISO-3166-1 alpha-2 code. ''' m = mapping try: for c in filter(str.isdigit, str(phone)): m = m[int(c)] if isinstance(m, str): return m except: raise InvalidPhone('Invalid phone {}'.format(phone)) def country_prefixes(): ''' Function that return a dictionary, with an ISO-3166-1 alpha-2 code, as the key, and the country prefix as the value. For countries with multiple prefixes, an abitrary one of them is chosen, for United states and Canada code is denoted as 1. ''' def transverse(node, path): if isinstance(node, dict): for k, v in node.items(): for i in transverse(v, path + str(k)): yield i else: yield node, 1 if node in ['US', 'CA'] else int(path) return dict(transverse(mapping, '')) def country_prefix(country_code): ''' Takes an ISO-3166-1 alpha-2 code. and returns the prefix for the country ''' prefixes = country_prefixes() try: return prefixes[country_code.upper()] except: raise InvalidCountry('Invalid country {}'.format(country_code)) def phone_country_prefix(phone): ''' Function that returns (dialingprefix, ISO-3166-1 country) from phone number ''' m = mapping p = '' try: for c in filter(str.isdigit, str(phone)): m = m[int(c)] p += c if isinstance(m, str): return (int(p), m) except: raise InvalidPhone('Invalid phone {}'.format(phone)) def network_country(mcc, mnc): ''' Get the country matching the MCC and MNC. In a few edgecases the MCC is not sufficient to identify the country, since some countries share MCC. However it's not often the case, so you could just specify MCC Returns an ISO-3166-1 alpha-2 code. ''' try: c = networks[mcc] if isinstance(c, str): return c return c[mnc] except: raise InvalidNetwork('Invalid MCC {} MNC {}'.format(mcc, mnc))
ssutee/metageta
refs/heads/master
metageta/formats/ecw.py
2
# -*- coding: utf-8 -*- # Copyright (c) 2013 Australian Government, Department of the Environment # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ''' Metadata driver for ECW imagery ''' format_regex=[r'\.ecw$'] #Well duh... '''Regular expression list of file formats''' #import base dataset modules #import __dataset__ import __default__ # import other modules (use "_" prefix to import privately) import sys, os from metageta import geometry class Dataset(__default__.Dataset): '''Subclass of __default__.Dataset class so we get a load of metadata populated automatically''' def __getmetadata__(self,f=None): '''Read Metadata for a ECW image as GDAL doesn't quite get it all...''' if not f:f=self.fileinfo['filepath'] #Originally we used the ERS to get metadata as they sometimes hold more info than the ECW #however, this caused segfaults under certain circumstances which were unable to be tracked down. #These circumstances were very repeatable and only occurred when the Crawler iterator returned a #certain ECW dataset, not when it was opened, when metadata was extracted nor even when overviews were generated. #Got me stumped! ers=os.path.splitext(f)[0]+'.ers' if os.path.exists(ers) and os.path.basename(f) in open(ers).read(): try: __default__.Dataset.__getmetadata__(self, ers) #autopopulate basic metadata self.metadata['filetype']='ECW/ERMapper Compressed Wavelets' self.metadata['compressiontype']='ECW' self.metadata['filepath']=f self.metadata['filename']=os.path.basename(f) self._gdaldataset=geometry.OpenDataset(f) #ERS may not get handed off to gdal proxy and segfault except:__default__.Dataset.__getmetadata__(self, f) else: __default__.Dataset.__getmetadata__(self) #autopopulate basic metadata #Leave the ECW driver in place even though all it does is call the default class. #This is so ECWs get processed before any ERSs (which could cause a segfault) ##__default__.Dataset.__getmetadata__(self) #autopopulate basic metadata def getoverview(self,*args,**kwargs): '''Check for possibly corrupt files that can crash GDAL and therefore python...''' if self.metadata['compressionratio'] > 10000: raise IOError, 'Unable to generate overview image from %s\nFile may be corrupt' % self.fileinfo['filepath'] else:return __default__.Dataset.getoverview(self,*args,**kwargs)
Antiun/l10n-spain
refs/heads/8.0
payment_redsys/models/__init__.py
16
# -*- coding: utf-8 -*- from . import redsys
jamalmazrui/InPy
refs/heads/master
WebClient_WeatherCheck.py
1
sLocation = ReadValue('LocationID') if not sLocation: sLocation = ReadValue('ZipCode') sLocation = IniFormDialogInput('Input', 'Location', sLocation) if not sLocation: Exit() WriteValue('LocationID', sLocation) # dYahoo = pywapi.get_weather_from_google(sLocation) ; bFound = True # print dYahoo # Exit() try: dYahoo = pywapi.get_weather_from_yahoo(sLocation) ; bFound = True except: bFound = False if bFound: # for sKey, sValue in dYahoo.items(): print sKey, '=', sValue SayLine('Loading results and opeing web page') # print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n" sText = RemoveHtmlTags(dYahoo['html_description']) sText = RegExpReplace(sText, r'Full Forecast(.|\n)+', '') sTitle = dYahoo['condition']['title'] # sText = 'Yahoo and Weather Channel Information\r\n' + 'Location ID ' + sLocation + '\r\n\r\n' + sText sText = 'Yahoo and Weather Channel Information\r\n' + sTitle + '\r\n\r\n' + sText sText = sText.strip() # SayLine('Loading results') StringToFile(sText, sOutputFile) SayLine('Loading results and opeing web page') sAddress = 'http://braille.wunderground.com/cgi-bin/findweather/hdfForecast' dData = {'brand' : 'braille', 'query' : sLocation} sQuery = utf8urlencode(dData) sAddress += '?' + sQuery sText = HtmlGetText(sAddress) sMatch = r'\nFind the Weather (.|\n)*' sText = RegExpReplace(sText, sMatch, '') sText = sText.strip() + '\r\n' StringToFile(sText, sOutputFile) os.startfile(sAddress)
mihneadb/suse_bug_reporter
refs/heads/master
bugreporter/util/interact.py
1
''' Copyright (C) 2011 Mihnea Dobrescu-Balaur This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import bugzilla from getpass import getpass bugzillaURL = 'https://bugzilla.novell.com/xmlrpc.cgi' user = raw_input('Insert user name: ') password = getpass('Insert password: ') cls = bugzilla.getBugzillaClassForURL(bugzillaURL) bz = cls(url=bugzillaURL, user=user, password=password)
phracek/gtk-demos
refs/heads/master
pygtk_textview/textview.py
1
#!/usr/bin/python2 -tt # -*- coding: utf-8 -*- import os import ConfigParser from StringIO import StringIO from gi.repository import Gtk, Gdk from gi.repository import GLib GLADE_FILE = os.path.join(os.path.dirname(__file__), 'textview.glade') class ListViewExample(object): def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file(GLADE_FILE) self.main_win = self.builder.get_object("main_window") self.main_handlers = { "on_main_window_delete_event": self.delete_event, "on_btn_browse_clicked": self.btn_browse_click, "on_fedora_release_changed": self.fedora_release_changed, "on_list_versions_cursor_changed": self.list_view_cursor_changed, } self.builder.connect_signals(self.main_handlers) self.text_entry = self.builder.get_object('directory_entry') self.combo_box = self.builder.get_object('fedora_release') self.listview = self.builder.get_object('list_versions') self.label_release = self.builder.get_object('label_fedora_release') self.text_view = self.builder.get_object('build_view') self.store = Gtk.ListStore(str) renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn("Available versions", renderer, markup=0, text=0) column.set_sort_column_id(0) self.listview.append_column(column) self.listview.set_model(self.store) self.main_win.show_all() Gtk.main() def run(self): self.main_win.show_all() def delete_event(self, widget, event, data=None): Gtk.main_quit() def btn_browse_click(self, widget): print ('I have clicked') dialog = Gtk.FileChooserDialog("Please choose a folder", self.main_win, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, "Select", Gtk.ResponseType.OK) ) dialog.set_default_size(800, 400) response = dialog.run() if response == Gtk.ResponseType.OK: print ('Select clicked') text = dialog.get_filename() self.text_entry.set_text(text) else: print ('Cancel clicked') dialog.destroy() git_config = os.path.join(text, '.git', 'config') if not os.path.exists(git_config): print 'This is not Git repository' self.label_release.set_text("") self.store.clean() else: versions = self._parse_git_config_file(git_config) print (versions) for version in sorted(versions): self.store.append([version]) self.label_release.set_text(sorted(versions)[0]) def fedora_release_changed(self, widget): version = self.combo_box.get_active_text() print(version) def _parse_git_config_file(self, git_config): data = StringIO('\n'.join(line.strip() for line in open(git_config, 'r'))) config = ConfigParser.SafeConfigParser() config.readfp(data) releases = [] tag = 'branch' for section in config.sections(): if section.startswith(tag): releases.append(section.replace(tag, '').replace('"', '').strip()) return releases def list_view_cursor_changed(self, listview): model, listiter = listview.get_selection().get_selected() if listiter is not None: text = model[listiter][0] print ('changed row: %s' % text) self.label_release.set_text(text) text_buffer = self.text_view.get_buffer() text_buffer.insert_at_cursor(text + '\n') if __name__ == "__main__": hw = ListViewExample() #hw.run()
htzy/bigfour
refs/heads/master
cms/djangoapps/contentstore/management/commands/clone_course.py
119
""" Script for cloning a course """ from django.core.management.base import BaseCommand, CommandError from xmodule.modulestore.django import modulestore from student.roles import CourseInstructorRole, CourseStaffRole from opaque_keys.edx.keys import CourseKey from opaque_keys import InvalidKeyError from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.modulestore import ModuleStoreEnum # # To run from command line: ./manage.py cms clone_course --settings=dev master/300/cough edx/111/foo # class Command(BaseCommand): """Clone a MongoDB-backed course to another location""" help = 'Clone a MongoDB backed course to another location' def course_key_from_arg(self, arg): """ Convert the command line arg into a course key """ try: return CourseKey.from_string(arg) except InvalidKeyError: return SlashSeparatedCourseKey.from_deprecated_string(arg) def handle(self, *args, **options): "Execute the command" if len(args) != 2: raise CommandError("clone requires 2 arguments: <source-course_id> <dest-course_id>") source_course_id = self.course_key_from_arg(args[0]) dest_course_id = self.course_key_from_arg(args[1]) mstore = modulestore() print("Cloning course {0} to {1}".format(source_course_id, dest_course_id)) with mstore.bulk_operations(dest_course_id): if mstore.clone_course(source_course_id, dest_course_id, ModuleStoreEnum.UserID.mgmt_command): print("copying User permissions...") # purposely avoids auth.add_user b/c it doesn't have a caller to authorize CourseInstructorRole(dest_course_id).add_users( *CourseInstructorRole(source_course_id).users_with_role() ) CourseStaffRole(dest_course_id).add_users( *CourseStaffRole(source_course_id).users_with_role() )
ftomassetti/intellij-community
refs/heads/master
python/helpers/docutils/parsers/rst/states.py
41
# $Id: states.py 6314 2010-04-26 10:04:17Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This is the ``docutils.parsers.restructuredtext.states`` module, the core of the reStructuredText parser. It defines the following: :Classes: - `RSTStateMachine`: reStructuredText parser's entry point. - `NestedStateMachine`: recursive StateMachine. - `RSTState`: reStructuredText State superclass. - `Inliner`: For parsing inline markup. - `Body`: Generic classifier of the first line of a block. - `SpecializedBody`: Superclass for compound element members. - `BulletList`: Second and subsequent bullet_list list_items - `DefinitionList`: Second+ definition_list_items. - `EnumeratedList`: Second+ enumerated_list list_items. - `FieldList`: Second+ fields. - `OptionList`: Second+ option_list_items. - `RFC2822List`: Second+ RFC2822-style fields. - `ExtensionOptions`: Parses directive option fields. - `Explicit`: Second+ explicit markup constructs. - `SubstitutionDef`: For embedded directives in substitution definitions. - `Text`: Classifier of second line of a text block. - `SpecializedText`: Superclass for continuation lines of Text-variants. - `Definition`: Second line of potential definition_list_item. - `Line`: Second line of overlined section title or transition marker. - `Struct`: An auxiliary collection class. :Exception classes: - `MarkupError` - `ParserError` - `MarkupMismatch` :Functions: - `escape2null()`: Return a string, escape-backslashes converted to nulls. - `unescape()`: Return a string, nulls removed or restored to backslashes. :Attributes: - `state_classes`: set of State classes used with `RSTStateMachine`. Parser Overview =============== The reStructuredText parser is implemented as a recursive state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module. In the description below, references are made to classes defined in this module; please see the individual classes for details. Parsing proceeds as follows: 1. The state machine examines each line of input, checking each of the transition patterns of the state `Body`, in order, looking for a match. The implicit transitions (blank lines and indentation) are checked before any others. The 'text' transition is a catch-all (matches anything). 2. The method associated with the matched transition pattern is called. A. Some transition methods are self-contained, appending elements to the document tree (`Body.doctest` parses a doctest block). The parser's current line index is advanced to the end of the element, and parsing continues with step 1. B. Other transition methods trigger the creation of a nested state machine, whose job is to parse a compound construct ('indent' does a block quote, 'bullet' does a bullet list, 'overline' does a section [first checking for a valid section header], etc.). - In the case of lists and explicit markup, a one-off state machine is created and run to parse contents of the first item. - A new state machine is created and its initial state is set to the appropriate specialized state (`BulletList` in the case of the 'bullet' transition; see `SpecializedBody` for more detail). This state machine is run to parse the compound element (or series of explicit markup elements), and returns as soon as a non-member element is encountered. For example, the `BulletList` state machine ends as soon as it encounters an element which is not a list item of that bullet list. The optional omission of inter-element blank lines is enabled by this nested state machine. - The current line index is advanced to the end of the elements parsed, and parsing continues with step 1. C. The result of the 'text' transition depends on the next line of text. The current state is changed to `Text`, under which the second line is examined. If the second line is: - Indented: The element is a definition list item, and parsing proceeds similarly to step 2.B, using the `DefinitionList` state. - A line of uniform punctuation characters: The element is a section header; again, parsing proceeds as in step 2.B, and `Body` is still used. - Anything else: The element is a paragraph, which is examined for inline markup and appended to the parent element. Processing continues with step 1. """ __docformat__ = 'reStructuredText' import sys import re import roman from types import FunctionType, MethodType from docutils import nodes, statemachine, utils, urischemes from docutils import ApplicationError, DataError from docutils.statemachine import StateMachineWS, StateWS from docutils.nodes import fully_normalize_name as normalize_name from docutils.nodes import whitespace_normalize_name from docutils.utils import escape2null, unescape, column_width import docutils.parsers.rst from docutils.parsers.rst import directives, languages, tableparser, roles from docutils.parsers.rst.languages import en as _fallback_language_module class MarkupError(DataError): pass class UnknownInterpretedRoleError(DataError): pass class InterpretedRoleNotImplementedError(DataError): pass class ParserError(ApplicationError): pass class MarkupMismatch(Exception): pass class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class RSTStateMachine(StateMachineWS): """ reStructuredText's master StateMachine. The entry point to reStructuredText parsing is the `run()` method. """ def run(self, input_lines, document, input_offset=0, match_titles=1, inliner=None): """ Parse `input_lines` and modify the `document` node in place. Extend `StateMachineWS.run()`: set up parse-global data and run the StateMachine. """ self.language = languages.get_language( document.settings.language_code) self.match_titles = match_titles if inliner is None: inliner = Inliner() inliner.init_customizations(document.settings) self.memo = Struct(document=document, reporter=document.reporter, language=self.language, title_styles=[], section_level=0, section_bubble_up_kludge=0, inliner=inliner) self.document = document self.attach_observer(document.note_source) self.reporter = self.memo.reporter self.node = document results = StateMachineWS.run(self, input_lines, input_offset, input_source=document['source']) assert results == [], 'RSTStateMachine.run() results should be empty!' self.node = self.memo = None # remove unneeded references class NestedStateMachine(StateMachineWS): """ StateMachine run from within other StateMachine runs, to parse nested document structures. """ def run(self, input_lines, input_offset, memo, node, match_titles=1): """ Parse `input_lines` and populate a `docutils.nodes.document` instance. Extend `StateMachineWS.run()`: set up document-wide data. """ self.match_titles = match_titles self.memo = memo self.document = memo.document self.attach_observer(self.document.note_source) self.reporter = memo.reporter self.language = memo.language self.node = node results = StateMachineWS.run(self, input_lines, input_offset) assert results == [], ('NestedStateMachine.run() results should be ' 'empty!') return results class RSTState(StateWS): """ reStructuredText State superclass. Contains methods used by all State subclasses. """ nested_sm = NestedStateMachine nested_sm_cache = [] def __init__(self, state_machine, debug=0): self.nested_sm_kwargs = {'state_classes': state_classes, 'initial_state': 'Body'} StateWS.__init__(self, state_machine, debug) def runtime_init(self): StateWS.runtime_init(self) memo = self.state_machine.memo self.memo = memo self.reporter = memo.reporter self.inliner = memo.inliner self.document = memo.document self.parent = self.state_machine.node # enable the reporter to determine source and source-line if not hasattr(self.reporter, 'locator'): self.reporter.locator = self.state_machine.get_source_and_line # print "adding locator to reporter", self.state_machine.input_offset def goto_line(self, abs_line_offset): """ Jump to input line `abs_line_offset`, ignoring jumps past the end. """ try: self.state_machine.goto_line(abs_line_offset) except EOFError: pass def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ src, srcline = self.state_machine.get_source_and_line() self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), source=src, line=srcline) return context, None, [] def bof(self, context): """Called at beginning of file.""" return [], [] def nested_parse(self, block, input_offset, node, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. """ use_default = 0 if state_machine_class is None: state_machine_class = self.nested_sm use_default += 1 if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs use_default += 1 block_length = len(block) state_machine = None if use_default == 2: try: state_machine = self.nested_sm_cache.pop() except IndexError: pass if not state_machine: state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) if use_default == 2: self.nested_sm_cache.append(state_machine) else: state_machine.unlink() new_offset = state_machine.abs_line_offset() # No `block.parent` implies disconnected -- lines aren't in sync: if block.parent and (len(block) - block_length) != 0: # Adjustment for block if modified in nested parse: self.state_machine.next_line(len(block) - block_length) return new_offset def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish def section(self, title, source, style, lineno, messages): """Check for a valid subsection and create one if it checks out.""" if self.check_subsection(source, style, lineno): self.new_subsection(title, lineno, messages) def check_subsection(self, source, style, lineno): """ Check for a valid subsection header. Return 1 (true) or None (false). When a new section is reached that isn't a subsection of the current section, back up the line count (use ``previous_line(-x)``), then ``raise EOFError``. The current StateMachine will finish, then the calling StateMachine can re-examine the title. This will work its way back up the calling chain until the correct section level isreached. @@@ Alternative: Evaluate the title, store the title info & level, and back up the chain until that level is reached. Store in memo? Or return in results? :Exception: `EOFError` when a sibling or supersection encountered. """ memo = self.memo title_styles = memo.title_styles mylevel = memo.section_level try: # check for existing title style level = title_styles.index(style) + 1 except ValueError: # new title style if len(title_styles) == memo.section_level: # new subsection title_styles.append(style) return 1 else: # not at lowest level self.parent += self.title_inconsistent(source, lineno) return None if level <= mylevel: # sibling or supersection memo.section_level = level # bubble up to parent section if len(style) == 2: memo.section_bubble_up_kludge = 1 # back up 2 lines for underline title, 3 for overline title self.state_machine.previous_line(len(style) + 1) raise EOFError # let parent section re-evaluate if level == mylevel + 1: # immediate subsection return 1 else: # invalid subsection self.parent += self.title_inconsistent(source, lineno) return None def title_inconsistent(self, sourcetext, lineno): src, srcline = self.state_machine.get_source_and_line(lineno) error = self.reporter.severe( 'Title level inconsistent:', nodes.literal_block('', sourcetext), source=src, line=srcline) return error def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=1) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if re.search(r'(?<!\\)(\\\\)*::$', data): if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.source, p.line = self.state_machine.get_source_and_line(lineno) return [p] + messages, literalnext def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent) def unindent_warning(self, node_name): # the actual problem is one line below the current line src, srcline = self.state_machine.get_source_and_line() return self.reporter.warning('%s ends without a blank line; ' 'unexpected unindent.' % node_name, source=src, line=srcline+1) def build_regexp(definition, compile=1): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is tuple: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp class Inliner: """ Parse inline markup; call the `parse()` method. """ def __init__(self): self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),] """List of (pattern, bound method) tuples, used by `self.implicit_inline`.""" def init_customizations(self, settings): """Setting-based customizations; run when parsing begins.""" if settings.pep_references: self.implicit_dispatch.append((self.patterns.pep, self.pep_reference)) if settings.rfc_references: self.implicit_dispatch.append((self.patterns.rfc, self.rfc_reference)) def parse(self, text, lineno, memo, parent): # Needs to be refactored for nested inline markup. # Add nested_parse() method? """ Return 2 lists: nodes (text and inline elements), and system_messages. Using `self.patterns.initial`, a pattern which matches start-strings (emphasis, strong, interpreted, phrase reference, literal, substitution reference, and inline target) and complete constructs (simple reference, footnote reference), search for a candidate. When one is found, check for validity (e.g., not a quoted '*' character). If valid, search for the corresponding end string if applicable, and check it for validity. If not found or invalid, generate a warning and ignore the start-string. Implicit inline markup (e.g. standalone URIs) is found last. """ self.reporter = memo.reporter self.document = memo.document self.language = memo.language self.parent = parent pattern_search = self.patterns.initial.search dispatch = self.dispatch remaining = escape2null(text) processed = [] unprocessed = [] messages = [] while remaining: match = pattern_search(remaining) if match: groups = match.groupdict() method = dispatch[groups['start'] or groups['backquote'] or groups['refend'] or groups['fnend']] before, inlines, remaining, sysmessages = method(self, match, lineno) unprocessed.append(before) messages += sysmessages if inlines: processed += self.implicit_inline(''.join(unprocessed), lineno) processed += inlines unprocessed = [] else: break remaining = ''.join(unprocessed) + remaining if remaining: processed += self.implicit_inline(remaining, lineno) return processed, messages openers = u'\'"([{<\u2018\u201c\xab\u00a1\u00bf' # see quoted_start below closers = u'\'")]}>\u2019\u201d\xbb!?' unicode_delimiters = u'\u2010\u2011\u2012\u2013\u2014\u00a0' start_string_prefix = (u'((?<=^)|(?<=[-/: \\n\u2019%s%s]))' % (re.escape(unicode_delimiters), re.escape(openers))) end_string_suffix = (r'((?=$)|(?=[-/:.,; \n\x00%s%s]))' % (re.escape(unicode_delimiters), re.escape(closers))) non_whitespace_before = r'(?<![ \n])' non_whitespace_escape_before = r'(?<![ \n\x00])' non_whitespace_after = r'(?![ \n])' # Alphanumerics with isolated internal [-._+:] chars (i.e. not 2 together): simplename = r'(?:(?!_)\w)+(?:[-._+:](?:(?!_)\w)+)*' # Valid URI characters (see RFC 2396 & RFC 2732); # final \x00 allows backslash escapes in URIs: uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" # Delimiter indicating the end of a URI (not part of the URI): uri_end_delim = r"""[>]""" # Last URI character; same as uric but no punctuation: urilast = r"""[_~*/=+a-zA-Z0-9]""" # End of a URI (either 'urilast' or 'uric followed by a # uri_end_delim'): uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" email_pattern = r""" %(emailc)s+(?:\.%(emailc)s+)* # name (?<!\x00)@ # at %(emailc)s+(?:\.%(emailc)s*)* # host %(uri_end)s # final URI char """ parts = ('initial_inline', start_string_prefix, '', [('start', '', non_whitespace_after, # simple start-strings [r'\*\*', # strong r'\*(?!\*)', # emphasis but not strong r'``', # literal r'_`', # inline internal target r'\|(?!\|)'] # substitution reference ), ('whole', '', end_string_suffix, # whole constructs [# reference name & end-string r'(?P<refname>%s)(?P<refend>__?)' % simplename, ('footnotelabel', r'\[', r'(?P<fnend>\]_)', [r'[0-9]+', # manually numbered r'\#(%s)?' % simplename, # auto-numbered (w/ label?) r'\*', # auto-symbol r'(?P<citationlabel>%s)' % simplename] # citation reference ) ] ), ('backquote', # interpreted text or phrase reference '(?P<role>(:%s:)?)' % simplename, # optional role non_whitespace_after, ['`(?!`)'] # but not literal ) ] ) patterns = Struct( initial=build_regexp(parts), emphasis=re.compile(non_whitespace_escape_before + r'(\*)' + end_string_suffix), strong=re.compile(non_whitespace_escape_before + r'(\*\*)' + end_string_suffix), interpreted_or_phrase_ref=re.compile( r""" %(non_whitespace_escape_before)s ( ` (?P<suffix> (?P<role>:%(simplename)s:)? (?P<refend>__?)? ) ) %(end_string_suffix)s """ % locals(), re.VERBOSE | re.UNICODE), embedded_uri=re.compile( r""" ( (?:[ \n]+|^) # spaces or beginning of line/string < # open bracket %(non_whitespace_after)s ([^<>\x00]+) # anything but angle brackets & nulls %(non_whitespace_before)s > # close bracket w/o whitespace before ) $ # end of string """ % locals(), re.VERBOSE), literal=re.compile(non_whitespace_before + '(``)' + end_string_suffix), target=re.compile(non_whitespace_escape_before + r'(`)' + end_string_suffix), substitution_ref=re.compile(non_whitespace_escape_before + r'(\|_{0,2})' + end_string_suffix), email=re.compile(email_pattern % locals() + '$', re.VERBOSE), uri=re.compile( (r""" %(start_string_prefix)s (?P<whole> (?P<absolute> # absolute URI (?P<scheme> # scheme (http, ftp, mailto) [a-zA-Z][a-zA-Z0-9.+-]* ) : ( ( # either: (//?)? # hierarchical URI %(uric)s* # URI characters %(uri_end)s # final URI char ) ( # optional query \?%(uric)s* %(uri_end)s )? ( # optional fragment \#%(uric)s* %(uri_end)s )? ) ) | # *OR* (?P<email> # email address """ + email_pattern + r""" ) ) %(end_string_suffix)s """) % locals(), re.VERBOSE), pep=re.compile( r""" %(start_string_prefix)s ( (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file | (PEP\s+(?P<pepnum2>\d+)) # reference by name ) %(end_string_suffix)s""" % locals(), re.VERBOSE), rfc=re.compile( r""" %(start_string_prefix)s (RFC(-|\s+)?(?P<rfcnum>\d+)) %(end_string_suffix)s""" % locals(), re.VERBOSE)) def quoted_start(self, match): """Return 1 if inline markup start-string is 'quoted', 0 if not.""" string = match.string start = match.start() end = match.end() if start == 0: # start-string at beginning of text return 0 prestart = string[start - 1] try: poststart = string[end] if self.openers.index(prestart) \ == self.closers.index(poststart): # quoted return 1 except IndexError: # start-string at end of text return 1 except ValueError: # not quoted pass return 0 def inline_obj(self, match, lineno, end_pattern, nodeclass, restore_backslashes=0): string = match.string matchstart = match.start('start') matchend = match.end('start') if self.quoted_start(match): return (string[:matchend], [], string[matchend:], [], '') endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars text = unescape(endmatch.string[:endmatch.start(1)], restore_backslashes) textend = matchend + endmatch.end(1) rawsource = unescape(string[matchstart:textend], 1) return (string[:matchstart], [nodeclass(rawsource, text)], string[textend:], [], endmatch.group(1)) msg = self.reporter.warning( 'Inline %s start-string without end-string.' % nodeclass.__name__, line=lineno) text = unescape(string[matchstart:matchend], 1) rawsource = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, rawsource, msg) return string[:matchstart], [prb], string[matchend:], [msg], '' def problematic(self, text, rawsource, message): msgid = self.document.set_id(message, self.parent) problematic = nodes.problematic(rawsource, text, refid=msgid) prbid = self.document.set_id(problematic) message.add_backref(prbid) return problematic def emphasis(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.emphasis, nodes.emphasis) return before, inlines, remaining, sysmessages def strong(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.strong, nodes.strong) return before, inlines, remaining, sysmessages def interpreted_or_phrase_ref(self, match, lineno): end_pattern = self.patterns.interpreted_or_phrase_ref string = match.string matchstart = match.start('backquote') matchend = match.end('backquote') rolestart = match.start('role') role = match.group('role') position = '' if role: role = role[1:-1] position = 'prefix' elif self.quoted_start(match): return (string[:matchend], [], string[matchend:], []) endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars textend = matchend + endmatch.end() if endmatch.group('role'): if role: msg = self.reporter.warning( 'Multiple roles in interpreted text (both ' 'prefix and suffix present; only one allowed).', line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] role = endmatch.group('suffix')[1:-1] position = 'suffix' escaped = endmatch.string[:endmatch.start(1)] rawsource = unescape(string[matchstart:textend], 1) if rawsource[-1:] == '_': if role: msg = self.reporter.warning( 'Mismatch: both interpreted text role %s and ' 'reference suffix.' % position, line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] return self.phrase_ref(string[:matchstart], string[textend:], rawsource, escaped, unescape(escaped)) else: rawsource = unescape(string[rolestart:textend], 1) nodelist, messages = self.interpreted(rawsource, escaped, role, lineno) return (string[:rolestart], nodelist, string[textend:], messages) msg = self.reporter.warning( 'Inline interpreted text or phrase reference start-string ' 'without end-string.', line=lineno) text = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, text, msg) return string[:matchstart], [prb], string[matchend:], [msg] def phrase_ref(self, before, after, rawsource, escaped, text): match = self.patterns.embedded_uri.search(escaped) if match: text = unescape(escaped[:match.start(0)]) uri_text = match.group(2) uri = ''.join(uri_text.split()) uri = self.adjust_uri(uri) if uri: target = nodes.target(match.group(1), refuri=uri) else: raise ApplicationError('problem with URI: %r' % uri_text) if not text: text = uri else: target = None refname = normalize_name(text) reference = nodes.reference(rawsource, text, name=whitespace_normalize_name(text)) node_list = [reference] if rawsource[-2:] == '__': if target: reference['refuri'] = uri else: reference['anonymous'] = 1 else: if target: reference['refuri'] = uri target['names'].append(refname) self.document.note_explicit_target(target, self.parent) node_list.append(target) else: reference['refname'] = refname self.document.note_refname(reference) return before, node_list, after, [] def adjust_uri(self, uri): match = self.patterns.email.match(uri) if match: return 'mailto:' + uri else: return uri def interpreted(self, rawsource, text, role, lineno): role_fn, messages = roles.role(role, self.language, lineno, self.reporter) if role_fn: nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2 else: msg = self.reporter.error( 'Unknown interpreted text role "%s".' % role, line=lineno) return ([self.problematic(rawsource, rawsource, msg)], messages + [msg]) def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=1) return before, inlines, remaining, sysmessages def inline_internal_target(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.target, nodes.target) if inlines and isinstance(inlines[0], nodes.target): assert len(inlines) == 1 target = inlines[0] name = normalize_name(target.astext()) target['names'].append(name) self.document.note_explicit_target(target, self.parent) return before, inlines, remaining, sysmessages def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages def footnote_reference(self, match, lineno): """ Handles `nodes.footnote_reference` and `nodes.citation_reference` elements. """ label = match.group('footnotelabel') refname = normalize_name(label) string = match.string before = string[:match.start('whole')] remaining = string[match.end('whole'):] if match.group('citationlabel'): refnode = nodes.citation_reference('[%s]_' % label, refname=refname) refnode += nodes.Text(label) self.document.note_citation_ref(refnode) else: refnode = nodes.footnote_reference('[%s]_' % label) if refname[0] == '#': refname = refname[1:] refnode['auto'] = 1 self.document.note_autofootnote_ref(refnode) elif refname == '*': refname = '' refnode['auto'] = '*' self.document.note_symbol_footnote_ref( refnode) else: refnode += nodes.Text(label) if refname: refnode['refname'] = refname self.document.note_footnote_ref(refnode) if utils.get_trim_footnote_ref_space(self.document.settings): before = before.rstrip() return (before, [refnode], remaining, []) def reference(self, match, lineno, anonymous=None): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], []) def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1) def standalone_uri(self, match, lineno): if (not match.group('scheme') or match.group('scheme').lower() in urischemes.schemes): if match.group('email'): addscheme = 'mailto:' else: addscheme = '' text = match.group('whole') unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=addscheme + unescaped)] else: # not a valid scheme raise MarkupMismatch def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = (self.document.settings.pep_base_url + self.document.settings.pep_file_url_template % pepnum) unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] rfc_url = 'rfc%d.html' def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] def implicit_inline(self, text, lineno): """ Check each of the patterns in `self.implicit_dispatch` for a match, and dispatch to the stored method for the pattern. Recursively check the text before and after the match. Return a list of `nodes.Text` and inline element nodes. """ if not text: return [] for pattern, method in self.implicit_dispatch: match = pattern.search(text) if match: try: # Must recurse on strings before *and* after the match; # there may be multiple patterns. return (self.implicit_inline(text[:match.start()], lineno) + method(match, lineno) + self.implicit_inline(text[match.end():], lineno)) except MarkupMismatch: pass return [nodes.Text(unescape(text), rawsource=unescape(text, 1))] dispatch = {'*': emphasis, '**': strong, '`': interpreted_or_phrase_ref, '``': literal, '_`': inline_internal_target, ']_': footnote_reference, '|': substitution_reference, '_': reference, '__': anonymous_reference} def _loweralpha_to_int(s, _zero=(ord('a')-1)): return ord(s) - _zero def _upperalpha_to_int(s, _zero=(ord('A')-1)): return ord(s) - _zero def _lowerroman_to_int(s): return roman.fromRoman(s.upper()) class Body(RSTState): """ Generic classifier of the first line of a block. """ double_width_pad_char = tableparser.TableParser.double_width_pad_char """Padding character for East Asian double-width text.""" enum = Struct() """Enumerated list parsing information.""" enum.formatinfo = { 'parens': Struct(prefix='(', suffix=')', start=1, end=-1), 'rparen': Struct(prefix='', suffix=')', start=0, end=-1), 'period': Struct(prefix='', suffix='.', start=0, end=-1)} enum.formats = enum.formatinfo.keys() enum.sequences = ['arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman'] # ORDERED! enum.sequencepats = {'arabic': '[0-9]+', 'loweralpha': '[a-z]', 'upperalpha': '[A-Z]', 'lowerroman': '[ivxlcdm]+', 'upperroman': '[IVXLCDM]+',} enum.converters = {'arabic': int, 'loweralpha': _loweralpha_to_int, 'upperalpha': _upperalpha_to_int, 'lowerroman': _lowerroman_to_int, 'upperroman': roman.fromRoman} enum.sequenceregexps = {} for sequence in enum.sequences: enum.sequenceregexps[sequence] = re.compile( enum.sequencepats[sequence] + '$') grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') """Matches the top (& bottom) of a full table).""" simple_table_top_pat = re.compile('=+( +=+)+ *$') """Matches the top of a simple table.""" simple_table_border_pat = re.compile('=+[ =]*$') """Matches the bottom & header bottom of a simple table.""" pats = {} """Fragments of patterns used by transitions.""" pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' pats['alpha'] = '[a-zA-Z]' pats['alphanum'] = '[a-zA-Z0-9]' pats['alphanumplus'] = '[a-zA-Z0-9_-]' pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' '|%(upperroman)s|#)' % enum.sequencepats) pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats # @@@ Loosen up the pattern? Allow Unicode? pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats for format in enum.formats: pats[format] = '(?P<%s>%s%s%s)' % ( format, re.escape(enum.formatinfo[format].prefix), pats['enum'], re.escape(enum.formatinfo[format].suffix)) patterns = { 'bullet': u'[-+*\u2022\u2023\u2043]( +|$)', 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)', 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, 'doctest': r'>>>( +|$)', 'line_block': r'\|( +|$)', 'grid_table_top': grid_table_top_pat, 'simple_table_top': simple_table_top_pat, 'explicit_markup': r'\.\.( +|$)', 'anonymous': r'__( +|$)', 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, 'text': r''} initial_transitions = ( 'bullet', 'enumerator', 'field_marker', 'option_marker', 'doctest', 'line_block', 'grid_table_top', 'simple_table_top', 'explicit_markup', 'anonymous', 'line', 'text') def indent(self, match, context, next_state): """Block quote.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() elements = self.block_quote(indented, line_offset) self.parent += elements if not blank_finish: self.parent += self.unindent_warning('Block quote') return context, next_state, [] def block_quote(self, indented, line_offset): elements = [] while indented: (blockquote_lines, attribution_lines, attribution_offset, indented, new_line_offset) = self.split_attribution(indented, line_offset) blockquote = nodes.block_quote() self.nested_parse(blockquote_lines, line_offset, blockquote) elements.append(blockquote) if attribution_lines: attribution, messages = self.parse_attribution( attribution_lines, attribution_offset) blockquote += attribution elements += messages line_offset = new_line_offset while indented and not indented[0]: indented = indented[1:] line_offset += 1 return elements # U+2014 is an em-dash: attribution_pattern = re.compile(u'(---?(?!-)|\u2014) *(?=[^ \\n])') def split_attribution(self, indented, line_offset): """ Check for a block quote attribution and split it off: * First line after a blank line must begin with a dash ("--", "---", em-dash; matches `self.attribution_pattern`). * Every line after that must have consistent indentation. * Attributions must be preceded by block quote content. Return a tuple of: (block quote content lines, content offset, attribution lines, attribution offset, remaining indented lines). """ blank = None nonblank_seen = False for i in range(len(indented)): line = indented[i].rstrip() if line: if nonblank_seen and blank == i - 1: # last line blank match = self.attribution_pattern.match(line) if match: attribution_end, indent = self.check_attribution( indented, i) if attribution_end: a_lines = indented[i:attribution_end] a_lines.trim_left(match.end(), end=1) a_lines.trim_left(indent, start=1) return (indented[:i], a_lines, i, indented[attribution_end:], line_offset + attribution_end) nonblank_seen = True else: blank = i else: return (indented, None, None, None, None) def check_attribution(self, indented, attribution_start): """ Check attribution shape. Return the index past the end of the attribution, and the indent. """ indent = None i = attribution_start + 1 for i in range(attribution_start + 1, len(indented)): line = indented[i].rstrip() if not line: break if indent is None: indent = len(line) - len(line.lstrip()) elif len(line) - len(line.lstrip()) != indent: return None, None # bad shape; not an attribution else: # return index of line after last attribution line: i += 1 return i, (indent or 0) def parse_attribution(self, indented, line_offset): text = '\n'.join(indented).rstrip() lineno = self.state_machine.abs_line_number() + line_offset textnodes, messages = self.inline_text(text, lineno) node = nodes.attribution(text, '', *textnodes) node.line = lineno # report with source and source-line results in # ``IndexError: list index out of range`` # node.source, node.line = self.state_machine.get_source_and_line(lineno) return node, messages def bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, [] def list_item(self, indent): if self.state_machine.line[indent:]: indented, line_offset, blank_finish = ( self.state_machine.get_known_indented(indent)) else: indented, indent, line_offset, blank_finish = ( self.state_machine.get_first_known_indented(indent)) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal), source=src, line=srcline) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, [] def parse_enumerator(self, match, expected_sequence=None): """ Analyze an enumerator and return the results. :Return: - the enumerator format ('period', 'parens', or 'rparen'), - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), - the text of the enumerator, stripped of formatting, and - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; ``None`` is returned for invalid enumerator text). The enumerator format has already been determined by the regular expression match. If `expected_sequence` is given, that sequence is tried first. If not, we check for Roman numeral 1. This way, single-character Roman numerals (which are also alphabetical) can be matched. If no sequence has been matched, all sequences are checked in order. """ groupdict = match.groupdict() sequence = '' for format in self.enum.formats: if groupdict[format]: # was this the format matched? break # yes; keep `format` else: # shouldn't happen raise ParserError('enumerator format not matched') text = groupdict[format][self.enum.formatinfo[format].start :self.enum.formatinfo[format].end] if text == '#': sequence = '#' elif expected_sequence: try: if self.enum.sequenceregexps[expected_sequence].match(text): sequence = expected_sequence except KeyError: # shouldn't happen raise ParserError('unknown enumerator sequence: %s' % sequence) elif text == 'i': sequence = 'lowerroman' elif text == 'I': sequence = 'upperroman' if not sequence: for sequence in self.enum.sequences: if self.enum.sequenceregexps[sequence].match(text): break else: # shouldn't happen raise ParserError('enumerator sequence not matched') if sequence == '#': ordinal = 1 else: try: ordinal = self.enum.converters[sequence](text) except roman.InvalidRomanNumeralError: ordinal = None return format, sequence, text, ordinal def is_enumerated_list_item(self, ordinal, sequence, format): """ Check validity based on the ordinal value and the second line. Return true if the ordinal is valid and the second line is blank, indented, or starts with the next enumerator or an auto-enumerator. """ if ordinal is None: return None try: next_line = self.state_machine.next_line() except EOFError: # end of input lines self.state_machine.previous_line() return 1 else: self.state_machine.previous_line() if not next_line[:1].strip(): # blank or indented return 1 result = self.make_enumerator(ordinal + 1, sequence, format) if result: next_enumerator, auto_enumerator = result try: if ( next_line.startswith(next_enumerator) or next_line.startswith(auto_enumerator) ): return 1 except TypeError: pass return None def make_enumerator(self, ordinal, sequence, format): """ Construct and return the next enumerated list item marker, and an auto-enumerator ("#" instead of the regular enumerator). Return ``None`` for invalid (out of range) ordinals. """ #" if sequence == '#': enumerator = '#' elif sequence == 'arabic': enumerator = str(ordinal) else: if sequence.endswith('alpha'): if ordinal > 26: return None enumerator = chr(ordinal + ord('a') - 1) elif sequence.endswith('roman'): try: enumerator = roman.toRoman(ordinal) except roman.RomanError: return None else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) if sequence.startswith('lower'): enumerator = enumerator.lower() elif sequence.startswith('upper'): enumerator = enumerator.upper() else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) formatinfo = self.enum.formatinfo[format] next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix + ' ') auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' return next_enumerator, auto_enumerator def field_marker(self, match, context, next_state): """Field list item.""" field_list = nodes.field_list() self.parent += field_list field, blank_finish = self.field(match) field_list += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=field_list, initial_state='FieldList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Field list') return [], next_state, [] def field(self, match): name = self.parse_field_marker(match) src, srcline = self.state_machine.get_source_and_line() lineno = self.state_machine.abs_line_number() indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) field_node = nodes.field() field_node.source = src field_node.line = srcline name_nodes, name_messages = self.inline_text(name, lineno) field_node += nodes.field_name(name, '', *name_nodes) field_body = nodes.field_body('\n'.join(indented), *name_messages) field_node += field_body if indented: self.parse_field_body(indented, line_offset, field_body) return field_node, blank_finish def parse_field_marker(self, match): """Extract & return field name from a field marker match.""" field = match.group()[1:] # strip off leading ':' field = field[:field.rfind(':')] # strip off trailing ':' etc. return field def parse_field_body(self, indented, offset, node): self.nested_parse(indented, input_offset=offset, node=node) def option_marker(self, match, context, next_state): """Option list item.""" optionlist = nodes.option_list() try: listitem, blank_finish = self.option_list_item(match) except MarkupError, error: # This shouldn't happen; pattern won't match. src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.error('Invalid option list marker: %s' % str(error), source=src, line=srcline) self.parent += msg indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) elements = self.block_quote(indented, line_offset) self.parent += elements if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] self.parent += optionlist optionlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=optionlist, initial_state='OptionList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] def option_list_item(self, match): offset = self.state_machine.abs_line_offset() options = self.parse_option_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) if not indented: # not an option list item self.goto_line(offset) raise statemachine.TransitionCorrection('text') option_group = nodes.option_group('', *options) description = nodes.description('\n'.join(indented)) option_list_item = nodes.option_list_item('', option_group, description) if indented: self.nested_parse(indented, input_offset=line_offset, node=description) return option_list_item, blank_finish def parse_option_marker(self, match): """ Return a list of `node.option` and `node.option_argument` objects, parsed from an option marker match. :Exception: `MarkupError` for invalid option markers. """ optlist = [] optionstrings = match.group().rstrip().split(', ') for optionstring in optionstrings: tokens = optionstring.split() delimiter = ' ' firstopt = tokens[0].split('=') if len(firstopt) > 1: # "--opt=value" form tokens[:1] = firstopt delimiter = '=' elif (len(tokens[0]) > 2 and ((tokens[0].startswith('-') and not tokens[0].startswith('--')) or tokens[0].startswith('+'))): # "-ovalue" form tokens[:1] = [tokens[0][:2], tokens[0][2:]] delimiter = '' if len(tokens) > 1 and (tokens[1].startswith('<') and tokens[-1].endswith('>')): # "-o <value1 value2>" form; join all values into one token tokens[1:] = [' '.join(tokens[1:])] if 0 < len(tokens) <= 2: option = nodes.option(optionstring) option += nodes.option_string(tokens[0], tokens[0]) if len(tokens) > 1: option += nodes.option_argument(tokens[1], tokens[1], delimiter=delimiter) optlist.append(option) else: raise MarkupError( 'wrong number of option tokens (=%s), should be 1 or 2: ' '"%s"' % (len(tokens), optionstring)) return optlist def doctest(self, match, context, next_state): data = '\n'.join(self.state_machine.get_text_block()) self.parent += nodes.doctest_block(data, data) return [], next_state, [] def line_block(self, match, context, next_state): """First line of a line block.""" block = nodes.line_block() self.parent += block lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) block += line self.parent += messages if not blank_finish: offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=block, initial_state='LineBlock', blank_finish=0) self.goto_line(new_line_offset) if not blank_finish: src, srcline = self.state_machine.get_source_and_line() self.parent += self.reporter.warning( 'Line block ends without a blank line.', source=src, line=srcline+1) if len(block): if block[0].indent is None: block[0].indent = 0 self.nest_line_block_lines(block) return [], next_state, [] def line_block_line(self, match, lineno): """Return one line element of a line_block.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) text = u'\n'.join(indented) text_nodes, messages = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.string.rstrip() != '|': # not empty line.indent = len(match.group(1)) - 1 return line, messages, blank_finish def nest_line_block_lines(self, block): for index in range(1, len(block)): if block[index].indent is None: block[index].indent = block[index - 1].indent self.nest_line_block_segment(block) def nest_line_block_segment(self, block): indents = [item.indent for item in block] least = min(indents) new_items = [] new_block = nodes.line_block() for item in block: if item.indent > least: new_block.append(item) else: if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) new_block = nodes.line_block() new_items.append(item) if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) block[:] = new_items def grid_table_top(self, match, context, next_state): """Top border of a full table.""" return self.table_top(match, context, next_state, self.isolate_grid_table, tableparser.GridTableParser) def simple_table_top(self, match, context, next_state): """Top border of a simple table.""" return self.table_top(match, context, next_state, self.isolate_simple_table, tableparser.SimpleTableParser) def table_top(self, match, context, next_state, isolate_function, parser_class): """Top border of a generic table.""" nodelist, blank_finish = self.table(isolate_function, parser_class) self.parent += nodelist if not blank_finish: src, srcline = self.state_machine.get_source_and_line() msg = self.reporter.warning( 'Blank line required after table.', source=src, line=srcline+1) self.parent += msg return [], next_state, [] def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, detail: nodelist = self.malformed_table( block, ' '.join(detail.args)) + messages else: nodelist = messages return nodelist, blank_finish def isolate_grid_table(self): messages = [] blank_finish = 1 try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, src, srcline = instance.args messages.append(self.reporter.error('Unexpected indentation.', source=src, line=srcline)) blank_finish = 0 block.disconnect() # for East Asian chars: block.pad_double_width(self.double_width_pad_char) width = len(block[0].strip()) for i in range(len(block)): block[i] = block[i].strip() if block[i][0] not in '+|': # check left edge blank_finish = 0 self.state_machine.previous_line(len(block) - i) del block[i:] break if not self.grid_table_top_pat.match(block[-1]): # find bottom blank_finish = 0 # from second-last to third line of table: for i in range(len(block) - 2, 1, -1): if self.grid_table_top_pat.match(block[i]): self.state_machine.previous_line(len(block) - i + 1) del block[i+1:] break else: messages.extend(self.malformed_table(block)) return [], messages, blank_finish for i in range(len(block)): # check right edge if len(block[i]) != width or block[i][-1] not in '+|': messages.extend(self.malformed_table(block)) return [], messages, blank_finish return block, messages, blank_finish def isolate_simple_table(self): start = self.state_machine.line_offset lines = self.state_machine.input_lines limit = len(lines) - 1 toplen = len(lines[start].strip()) pattern_match = self.simple_table_border_pat.match found = 0 found_at = None i = start + 1 while i <= limit: line = lines[i] match = pattern_match(line) if match: if len(line.strip()) != toplen: self.state_machine.next_line(i - start) messages = self.malformed_table( lines[start:i+1], 'Bottom/header table border does ' 'not match top border.') return [], messages, i == limit or not lines[i+1].strip() found += 1 found_at = i if found == 2 or i == limit or not lines[i+1].strip(): end = i break i += 1 else: # reached end of input_lines if found: extra = ' or no blank line after table bottom' self.state_machine.next_line(found_at - start) block = lines[start:found_at+1] else: extra = '' self.state_machine.next_line(i - start - 1) block = lines[start:] messages = self.malformed_table( block, 'No bottom table border found%s.' % extra) return [], messages, not extra self.state_machine.next_line(end - start) block = lines[start:end+1] # for East Asian chars: block.pad_double_width(self.double_width_pad_char) return block, [], end == limit or not lines[end+1].strip() def malformed_table(self, block, detail=''): block.replace(self.double_width_pad_char, '') data = '\n'.join(block) message = 'Malformed table.' startline = self.state_machine.abs_line_number() - len(block) + 1 src, srcline = self.state_machine.get_source_and_line(startline) if detail: message += '\n' + detail error = self.reporter.error(message, nodes.literal_block(data, data), source=src, line=srcline) return [error] def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table def build_table_row(self, rowdata, tableline): row = nodes.row() for cell in rowdata: if cell is None: continue morerows, morecols, offset, cellblock = cell attributes = {} if morerows: attributes['morerows'] = morerows if morecols: attributes['morecols'] = morecols entry = nodes.entry(**attributes) row += entry if ''.join(cellblock): self.nested_parse(cellblock, input_offset=tableline+offset, node=entry) return row explicit = Struct() """Patterns and constants used for explicit markup recognition.""" explicit.patterns = Struct( target=re.compile(r""" ( _ # anonymous target | # *OR* (?!_) # no underscore at the beginning (?P<quote>`?) # optional open quote (?![ `]) # first char. not space or # backquote (?P<name> # reference name .+? ) %(non_whitespace_escape_before)s (?P=quote) # close quote if open quote used ) (?<!(?<!\x00):) # no unescaped colon at end %(non_whitespace_escape_before)s [ ]? # optional space : # end of reference name ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE), reference=re.compile(r""" ( (?P<simple>%(simplename)s)_ | # *OR* ` # open backquote (?![ ]) # not space (?P<phrase>.+?) # hyperlink phrase %(non_whitespace_escape_before)s `_ # close backquote, # reference mark ) $ # end of string """ % vars(Inliner), re.VERBOSE | re.UNICODE), substitution=re.compile(r""" ( (?![ ]) # first char. not space (?P<name>.+?) # substitution text %(non_whitespace_escape_before)s \| # close delimiter ) ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE),) def footnote(self, match): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) footnote = nodes.footnote('\n'.join(indented)) footnote.source = src footnote.line = srcline if name[0] == '#': # auto-numbered name = name[1:] # autonumber label footnote['auto'] = 1 if name: footnote['names'].append(name) self.document.note_autofootnote(footnote) elif name == '*': # auto-symbol name = '' footnote['auto'] = '*' self.document.note_symbol_footnote(footnote) else: # manually numbered footnote += nodes.label('', label) footnote['names'].append(name) self.document.note_footnote(footnote) if name: self.document.note_explicit_target(footnote, footnote) else: self.document.set_id(footnote, footnote) if indented: self.nested_parse(indented, input_offset=offset, node=footnote) return [footnote], blank_finish def citation(self, match): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) citation = nodes.citation('\n'.join(indented)) citation.source = src citation.line = srcline citation += nodes.label('', label) citation['names'].append(name) self.document.note_citation(citation) self.document.note_explicit_target(citation, citation) if indented: self.nested_parse(indented, input_offset=offset, node=citation) return [citation], blank_finish def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=1, strip_indent=0) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while 1: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.') del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish def make_target(self, block, block_text, lineno, target_name): target_type, data = self.parse_target(block, block_text, lineno) if target_type == 'refname': target = nodes.target(block_text, '', refname=normalize_name(data)) target.indirect_reference_name = data self.add_target(target_name, '', target, lineno) self.document.note_indirect_target(target) return target elif target_type == 'refuri': target = nodes.target(block_text, '') self.add_target(target_name, data, target, lineno) return target else: return data def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference) def is_reference(self, reference): match = self.explicit.patterns.reference.match( whitespace_normalize_name(reference)) if not match: return None return unescape(match.group('simple') or match.group('phrase')) def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri else: raise ApplicationError('problem with URI: %r' % refuri) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri target['anonymous'] = 1 self.document.note_anonymous_target(target) def substitution_def(self, match): pattern = self.explicit.patterns.substitution src, srcline = self.state_machine.get_source_and_line() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), strip_indent=0) blocktext = (match.string[:match.end()] + '\n'.join(block)) block.disconnect() escaped = escape2null(block[0].rstrip()) blockindex = 0 while 1: subdefmatch = pattern.match(escaped) if subdefmatch: break blockindex += 1 try: escaped = escaped + ' ' + escape2null(block[blockindex].strip()) except IndexError: raise MarkupError('malformed substitution definition.') del block[:blockindex] # strip out the substitution marker block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1] if not block[0]: del block[0] offset += 1 while block and not block[-1].strip(): block.pop() subname = subdefmatch.group('name') substitution_node = nodes.substitution_definition(blocktext) substitution_node.source = src substitution_node.line = srcline if not block: msg = self.reporter.warning( 'Substitution definition "%s" missing contents.' % subname, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish block[0] = block[0].strip() substitution_node['names'].append( nodes.whitespace_normalize_name(subname)) new_abs_offset, blank_finish = self.nested_list_parse( block, input_offset=offset, node=substitution_node, initial_state='SubstitutionDef', blank_finish=blank_finish) i = 0 for node in substitution_node[:]: if not (isinstance(node, nodes.Inline) or isinstance(node, nodes.Text)): self.parent += substitution_node[i] del substitution_node[i] else: i += 1 for node in substitution_node.traverse(nodes.Element): if self.disallowed_inside_substitution_definitions(node): pformat = nodes.literal_block('', node.pformat().rstrip()) msg = self.reporter.error( 'Substitution definition contains illegal element:', pformat, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish if len(substitution_node) == 0: msg = self.reporter.warning( 'Substitution definition "%s" empty or invalid.' % subname, nodes.literal_block(blocktext, blocktext), source=src, line=srcline) return [msg], blank_finish self.document.note_substitution_def( substitution_node, subname, self.parent) return [substitution_node], blank_finish def disallowed_inside_substitution_definitions(self, node): if (node['ids'] or isinstance(node, nodes.reference) and node.get('anonymous') or isinstance(node, nodes.footnote_reference) and node.get('auto')): return 1 else: return 0 def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_class, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_class: return self.run_directive( directive_class, match, type_name, option_presets) else: return self.unknown_directive(type_name) def run_directive(self, directive, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive`: The class implementing the directive. Must be a subclass of `rst.Directive`. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ if isinstance(directive, (FunctionType, MethodType)): from docutils.parsers.rst import convert_directive_function directive = convert_directive_function(directive) lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), source=src, line=srcline) return [error], blank_finish directive_instance = directive( type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) try: result = directive_instance.run() except docutils.parsers.rst.DirectiveError, error: msg_node = self.reporter.system_message(error.level, error.msg, source=src, line=srcline) msg_node += nodes.literal_block(block_text, block_text) result = [msg_node] assert isinstance(result, list), \ 'Directive "%s" must return a list of nodes.' % type_name for i in range(len(result)): assert isinstance(result[i], nodes.Node), \ ('Directive "%s" returned non-Node object (index %s): %r' % (type_name, i, result[i])) return (result, blank_finish or self.state_machine.is_next_line_blank()) def parse_directive_block(self, indented, line_offset, directive, option_presets): option_spec = directive.option_spec has_content = directive.has_content if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (directive.required_arguments or directive.optional_arguments or option_spec): for i in range(len(indented)): if not indented[i].strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) if arg_block and not (directive.required_arguments or directive.optional_arguments): raise MarkupError('no arguments permitted; blank line ' 'required before content block') else: options = {} if directive.required_arguments or directive.optional_arguments: arguments = self.parse_directive_arguments( directive, arg_block) else: arguments = [] if content and not has_content: raise MarkupError('no content permitted') return (arguments, options, content, content_offset) def parse_directive_options(self, option_presets, option_spec, arg_block): options = option_presets.copy() for i in range(len(arg_block)): if arg_block[i][:1] == ':': opt_block = arg_block[i:] arg_block = arg_block[:i] break else: opt_block = [] if opt_block: success, data = self.parse_extension_options(option_spec, opt_block) if success: # data is a dict of options options.update(data) else: # data is an error string raise MarkupError(data) return options, arg_block def parse_directive_arguments(self, directive, arg_block): required = directive.required_arguments optional = directive.optional_arguments arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if directive.final_argument_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments def parse_extension_options(self, option_spec, datalines): """ Parse `datalines` for a field list containing extension options matching `option_spec`. :Parameters: - `option_spec`: a mapping of option name to conversion function, which should raise an exception on bad input. - `datalines`: a list of input strings. :Return: - Success value, 1 or 0. - An option dictionary on success, an error string on failure. """ node = nodes.field_list() newline_offset, blank_finish = self.nested_list_parse( datalines, 0, node, initial_state='ExtensionOptions', blank_finish=1) if newline_offset != len(datalines): # incomplete parse of block return 0, 'invalid option block' try: options = utils.extract_extension_options(node, option_spec) except KeyError, detail: return 0, ('unknown option: "%s"' % detail.args[0]) except (ValueError, TypeError), detail: return 0, ('invalid option value: %s' % ' '.join(detail.args)) except utils.ExtensionOptionError, detail: return 0, ('invalid option data: %s' % ' '.join(detail.args)) if blank_finish: return 1, options else: return 0, 'option data incompletely parsed' def unknown_directive(self, type_name): src, srcline = self.state_machine.get_source_and_line() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=0) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), source=src, line=srcline) return [error], blank_finish def comment(self, match): if not match.string[match.end():].strip() \ and self.state_machine.is_next_line_blank(): # an empty comment? return [nodes.comment()], 1 # "A tiny but practical wart." indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) while indented and not indented[-1].strip(): indented.trim_end() text = '\n'.join(indented) return [nodes.comment(text, text)], blank_finish explicit.constructs = [ (footnote, re.compile(r""" \.\.[ ]+ # explicit markup start \[ ( # footnote label: [0-9]+ # manually numbered footnote | # *OR* \# # anonymous auto-numbered footnote | # *OR* \#%s # auto-number ed?) footnote label | # *OR* \* # auto-symbol footnote ) \] ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (citation, re.compile(r""" \.\.[ ]+ # explicit markup start \[(%s)\] # citation label ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (hyperlink_target, re.compile(r""" \.\.[ ]+ # explicit markup start _ # target indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (substitution_def, re.compile(r""" \.\.[ ]+ # explicit markup start \| # substitution indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (directive, re.compile(r""" \.\.[ ]+ # explicit markup start (%s) # directive name [ ]? # optional space :: # directive delimiter ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE))] def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def explicit_construct(self, match): """Determine which explicit construct this is, parse & return it.""" errors = [] for method, pattern in self.explicit.constructs: expmatch = pattern.match(match.string) if expmatch: try: return method(self, expmatch) except MarkupError, error: # never reached? message = ' '.join(error.args) src, srcline = self.state_machine.get_source_and_line() errors.append(self.reporter.warning( message, source=src, line=srcline)) break nodelist, blank_finish = self.comment(match) return nodelist + errors, blank_finish def explicit_list(self, blank_finish): """ Create a nested state machine for a series of explicit markup constructs (including anonymous hyperlink targets). """ offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=self.parent, initial_state='Explicit', blank_finish=blank_finish, match_titles=self.state_machine.match_titles) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Explicit markup') def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def anonymous_target(self, match): lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), until_blank=1) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] target = self.make_target(block, blocktext, lineno, '') return [target], blank_finish def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, [] def text(self, match, context, next_state): """Titles, definition lists, paragraphs.""" return [match.string], 'Text', [] class RFC2822Body(Body): """ RFC2822 headers are only valid as the first constructs in documents. As soon as anything else appears, the `Body` state should take over. """ patterns = Body.patterns.copy() # can't modify the original patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' initial_transitions = [(name, 'Body') for name in Body.initial_transitions] initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text' def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" fieldlist = nodes.field_list(classes=['rfc2822']) self.parent += fieldlist field, blank_finish = self.rfc2822_field(match) fieldlist += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=fieldlist, initial_state='RFC2822List', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning( 'RFC2822-style field list') return [], next_state, [] def rfc2822_field(self, match): name = match.string[:match.string.find(':')] indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) fieldnode = nodes.field() fieldnode += nodes.field_name(name, name) fieldbody = nodes.field_body('\n'.join(indented)) fieldnode += fieldbody if indented: self.nested_parse(indented, input_offset=line_offset, node=fieldbody) return fieldnode, blank_finish class SpecializedBody(Body): """ Superclass for second and subsequent compound element members. Compound elements are lists and list-like constructs. All transition methods are disabled (redefined as `invalid_input`). Override individual methods in subclasses to re-enable. For example, once an initial bullet list item, say, is recognized, the `BulletList` subclass takes over, with a "bullet_list" node as its container. Upon encountering the initial bullet list item, `Body.bullet` calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which starts up a nested parsing session with `BulletList` as the initial state. Only the ``bullet`` transition method is enabled in `BulletList`; as long as only bullet list items are encountered, they are parsed and inserted into the container. The first construct which is *not* a bullet list item triggers the `invalid_input` method, which ends the nested parse and closes the container. `BulletList` needs to recognize input that is invalid in the context of a bullet list, which means everything *other than* bullet list items, so it inherits the transition list created in `Body`. """ def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" self.state_machine.previous_line() # back up so parent SM can reassess raise EOFError indent = invalid_input bullet = invalid_input enumerator = invalid_input field_marker = invalid_input option_marker = invalid_input doctest = invalid_input line_block = invalid_input grid_table_top = invalid_input simple_table_top = invalid_input explicit_markup = invalid_input anonymous = invalid_input line = invalid_input text = invalid_input class BulletList(SpecializedBody): """Second and subsequent bullet_list list_items.""" def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, [] class DefinitionList(SpecializedBody): """Second and subsequent definition_list_items.""" def text(self, match, context, next_state): """Definition lists.""" return [match.string], 'Definition', [] class EnumeratedList(SpecializedBody): """Second and subsequent enumerated_list list_items.""" def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, [] class FieldList(SpecializedBody): """Second and subsequent field_list fields.""" def field_marker(self, match, context, next_state): """Field list field.""" field, blank_finish = self.field(match) self.parent += field self.blank_finish = blank_finish return [], next_state, [] class OptionList(SpecializedBody): """Second and subsequent option_list option_list_items.""" def option_marker(self, match, context, next_state): """Option list item.""" try: option_list_item, blank_finish = self.option_list_item(match) except MarkupError: self.invalid_input() self.parent += option_list_item self.blank_finish = blank_finish return [], next_state, [] class RFC2822List(SpecializedBody, RFC2822Body): """Second and subsequent RFC2822-style field_list fields.""" patterns = RFC2822Body.patterns initial_transitions = RFC2822Body.initial_transitions def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" field, blank_finish = self.rfc2822_field(match) self.parent += field self.blank_finish = blank_finish return [], 'RFC2822List', [] blank = SpecializedBody.invalid_input class ExtensionOptions(FieldList): """ Parse field_list fields for extension options. No nested parsing is done (including inline markup parsing). """ def parse_field_body(self, indented, offset, node): """Override `Body.parse_field_body` for simpler parsing.""" lines = [] for line in list(indented) + ['']: if line.strip(): lines.append(line) elif lines: text = '\n'.join(lines) node += nodes.paragraph(text, text) lines = [] class LineBlock(SpecializedBody): """Second and subsequent lines of a line_block.""" blank = SpecializedBody.invalid_input def line_block(self, match, context, next_state): """New line of line block.""" lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) self.parent += line self.parent.parent += messages self.blank_finish = blank_finish return [], next_state, [] class Explicit(SpecializedBody): """Second and subsequent explicit markup construct.""" def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] blank = SpecializedBody.invalid_input class SubstitutionDef(Body): """ Parser for the contents of a substitution_definition element. """ patterns = { 'embedded_directive': re.compile(r'(%s)::( +|$)' % Inliner.simplename, re.UNICODE), 'text': r''} initial_transitions = ['embedded_directive', 'text'] def embedded_directive(self, match, context, next_state): nodelist, blank_finish = self.directive(match, alt=self.parent['names'][0]) self.parent += nodelist if not self.state_machine.at_eof(): self.blank_finish = blank_finish raise EOFError def text(self, match, context, next_state): if not self.state_machine.at_eof(): self.blank_finish = self.state_machine.is_next_line_blank() raise EOFError class Text(RSTState): """ Classifier of second line of a text block. Could be a paragraph, a definition list item, or a title. """ patterns = {'underline': Body.patterns['line'], 'text': r''} initial_transitions = [('underline', 'Body'), ('text', 'Body')] def blank(self, match, context, next_state): """End of paragraph.""" paragraph, literalnext = self.paragraph( context, self.state_machine.abs_line_number() - 1) self.parent += paragraph if literalnext: self.parent += self.literal_block() return [], 'Body', [] def eof(self, context): if context: self.blank(None, context, None) return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlist = nodes.definition_list() definitionlistitem, blank_finish = self.definition_list_item(context) definitionlist += definitionlistitem self.parent += definitionlist offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=definitionlist, initial_state='DefinitionList', blank_finish=blank_finish, blank_finish_state='Definition') self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Definition list') return [], 'Body', [] def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() src, srcline = self.state_machine.get_source_and_line() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if column_width(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", source=src, line=srcline) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning( 'Title underline too short.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.severe( 'Unexpected section title.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, [] def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, src, srcline = instance.args msg = self.reporter.error('Unexpected indentation.', source=src, line=srcline) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, [] def literal_block(self): """Return a list of nodes.""" indented, indent, offset, blank_finish = \ self.state_machine.get_indented() while indented and not indented[-1].strip(): indented.trim_end() if not indented: return self.quoted_literal_block() data = '\n'.join(indented) literal_block = nodes.literal_block(data, data) literal_block.line = offset + 1 nodelist = [literal_block] if not blank_finish: nodelist.append(self.unindent_warning('Literal block')) return nodelist def quoted_literal_block(self): abs_line_offset = self.state_machine.abs_line_offset() offset = self.state_machine.line_offset parent_node = nodes.Element() new_abs_offset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=abs_line_offset, node=parent_node, match_titles=0, state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), 'initial_state': 'QuotedLiteralBlock'}) self.goto_line(new_abs_offset) return parent_node.children def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() definitionlistitem = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() definitionlistitem.source = src definitionlistitem.line = srcline - 1 termlist, messages = self.term(termline, lineno) definitionlistitem += termlist definition = nodes.definition('', *messages) definitionlistitem += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', source=src, line=srcline) self.nested_parse(indented, input_offset=line_offset, node=definition) return definitionlistitem, blank_finish classifier_delimiter = re.compile(' +: +') def term(self, lines, lineno): """Return a definition_list's term and optional classifiers.""" assert len(lines) == 1 text_nodes, messages = self.inline_text(lines[0], lineno) term_node = nodes.term() node_list = [term_node] for i in range(len(text_nodes)): node = text_nodes[i] if isinstance(node, nodes.Text): parts = self.classifier_delimiter.split(node.rawsource) if len(parts) == 1: node_list[-1] += node else: node_list[-1] += nodes.Text(parts[0].rstrip()) for part in parts[1:]: classifier_node = nodes.classifier('', part) node_list.append(classifier_node) else: node_list[-1] += node return node_list, messages class SpecializedText(Text): """ Superclass for second and subsequent lines of Text-variants. All transition methods are disabled. Override individual methods in subclasses to re-enable. """ def eof(self, context): """Incomplete construct.""" return [] def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" raise EOFError blank = invalid_input indent = invalid_input underline = invalid_input text = invalid_input class Definition(SpecializedText): """Second line of potential definition_list_item.""" def eof(self, context): """Not a definition.""" self.state_machine.previous_line(2) # so parent SM can reassess return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlistitem, blank_finish = self.definition_list_item(context) self.parent += definitionlistitem self.blank_finish = blank_finish return [], 'DefinitionList', [] class Line(SpecializedText): """ Second line of over- & underlined section title or transition marker. """ eofcheck = 1 # @@@ ??? """Set to 0 while parsing sections, so that we don't catch the EOF.""" def eof(self, context): """Transition marker at end of section or document.""" marker = context[0].strip() if self.memo.section_bubble_up_kludge: self.memo.section_bubble_up_kludge = 0 elif len(marker) < 4: self.state_correction(context) if self.eofcheck: # ignore EOFError with sections lineno = self.state_machine.abs_line_number() - 1 transition = nodes.transition(rawsource=context[0]) transition.line = lineno self.parent += transition self.eofcheck = 1 return [] def blank(self, match, context, next_state): """Transition marker.""" src, srcline = self.state_machine.get_source_and_line() marker = context[0].strip() if len(marker) < 4: self.state_correction(context) transition = nodes.transition(rawsource=marker) transition.source = src transition.line = srcline - 1 self.parent += transition return [], 'Body', [] def text(self, match, context, next_state): """Potential over- & underlined title.""" lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() overline = context[0] title = match.string underline = '' try: underline = self.state_machine.next_line() except EOFError: blocktext = overline + '\n' + title if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Incomplete section title.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] source = '%s\n%s\n%s' % (overline, title, underline) overline = overline.rstrip() underline = underline.rstrip() if not self.transitions['underline'][0].match(underline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Missing matching underline for section title overline.', nodes.literal_block(source, source), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] elif overline != underline: blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Title overline & underline mismatch.', nodes.literal_block(source, source), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] title = title.rstrip() messages = [] if column_width(title) > len(overline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.warning( 'Title overline too short.', nodes.literal_block(source, source), source=src, line=srcline-1) messages.append(msg) style = (overline[0], underline[0]) self.eofcheck = 0 # @@@ not sure this is correct self.section(title.lstrip(), source, style, lineno + 1, messages) self.eofcheck = 1 return [], 'Body', [] indent = text # indented title def underline(self, match, context, next_state): overline = context[0] blocktext = overline + '\n' + self.state_machine.line lineno = self.state_machine.abs_line_number() - 1 src, srcline = self.state_machine.get_source_and_line() if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 1) msg = self.reporter.error( 'Invalid section title or transition marker.', nodes.literal_block(blocktext, blocktext), source=src, line=srcline-1) self.parent += msg return [], 'Body', [] def short_overline(self, context, blocktext, lineno, lines=1): src, srcline = self.state_machine.get_source_and_line(lineno) msg = self.reporter.info( 'Possible incomplete section title.\nTreating the overline as ' "ordinary text because it's so short.", source=src, line=srcline) self.parent += msg self.state_correction(context, lines) def state_correction(self, context, lines=1): self.state_machine.previous_line(lines) context[:] = [] raise statemachine.StateCorrection('Body', 'text') class QuotedLiteralBlock(RSTState): """ Nested parse handler for quoted (unindented) literal blocks. Special-purpose. Not for inclusion in `state_classes`. """ patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, 'text': r''} initial_transitions = ('initial_quoted', 'text') def __init__(self, state_machine, debug=0): RSTState.__init__(self, state_machine, debug) self.messages = [] self.initial_lineno = None def blank(self, match, context, next_state): if context: raise EOFError else: return context, next_state, [] def eof(self, context): if context: src, srcline = self.state_machine.get_source_and_line( self.initial_lineno) text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.source = src literal_block.line = srcline self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) # src not available, because statemachine.input_lines is empty self.state_machine.previous_line() self.parent += self.messages return [] def indent(self, match, context, next_state): assert context, ('QuotedLiteralBlock.indent: context should not ' 'be empty!') self.messages.append( self.reporter.error('Unexpected indentation.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError def initial_quoted(self, match, context, next_state): """Match arbitrary quote character on the first line only.""" self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote)) # New transition matches consistent quotes only: self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_number() return [match.string], next_state, [] def quoted(self, match, context, next_state): """Match consistent quotes on subsequent lines.""" context.append(match.string) return context, next_state, [] def text(self, match, context, next_state): if context: src, srcline = self.state_machine.get_source_and_line() self.messages.append( self.reporter.error('Inconsistent literal block quoting.', source=src, line=srcline)) self.state_machine.previous_line() raise EOFError state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, OptionList, LineBlock, ExtensionOptions, Explicit, Text, Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) """Standard set of State classes used to start `RSTStateMachine`."""
pydsigner/wesnoth
refs/heads/master
utils/gdb/register_wesnoth_pretty_printers.py
41
# This file registers pretty printers """ Usage: """ import gdb import re import itertools import wesnoth_type_tools reload(wesnoth_type_tools) from wesnoth_type_tools import strip_all_type class NullPointerPrinter(object): """Print NULL for null pointers""" def __init__(self, val): pass def to_string(self): return "NULL" def display_hint(self): return 'string' def create_wesnoth_lookup_function(pretty_printers_dict): """Closure for lookup function """ def wesnoth_lookup_function(val): "Look-up and return a pretty-printer that can print val." #If it is a null pointer or object return the null pointer printer if (val.type.code == gdb.TYPE_CODE_PTR and long(val) == 0) or (val.address == 0): return NullPointerPrinter(val) # Get the type name. type = strip_all_type(val) # Get the type name. typename = type.tag if typename == None: return None # Iterate over local dictionary of types to determine # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: if function.match(typename): return pretty_printers_dict[function](val) # Cannot find a pretty printer. Return None. return None return wesnoth_lookup_function def register(new_pretty_printers): """register the regex and printers from the dictionary with gdb""" #delete all previous wesnoth printers remove_printers=[] for a in gdb.pretty_printers: if a.__name__ == 'wesnoth_lookup_function': remove_printers.append(a) for a in remove_printers: gdb.pretty_printers.remove(a) #Add the new printers with the new dictionary gdb.pretty_printers.append(create_wesnoth_lookup_function(new_pretty_printers))
alexsanjoseph/duolingo-save-streak
refs/heads/master
werkzeug/contrib/cache.py
84
# -*- coding: utf-8 -*- """ werkzeug.contrib.cache ~~~~~~~~~~~~~~~~~~~~~~ The main problem with dynamic Web sites is, well, they're dynamic. Each time a user requests a page, the webserver executes a lot of code, queries the database, renders templates until the visitor gets the page he sees. This is a lot more expensive than just loading a file from the file system and sending it to the visitor. For most Web applications, this overhead isn't a big deal but once it becomes, you will be glad to have a cache system in place. How Caching Works ================= Caching is pretty simple. Basically you have a cache object lurking around somewhere that is connected to a remote cache or the file system or something else. When the request comes in you check if the current page is already in the cache and if so, you're returning it from the cache. Otherwise you generate the page and put it into the cache. (Or a fragment of the page, you don't have to cache the full thing) Here is a simple example of how to cache a sidebar for 5 minutes:: def get_sidebar(user): identifier = 'sidebar_for/user%d' % user.id value = cache.get(identifier) if value is not None: return value value = generate_sidebar_for(user=user) cache.set(identifier, value, timeout=60 * 5) return value Creating a Cache Object ======================= To create a cache object you just import the cache system of your choice from the cache module and instantiate it. Then you can start working with that object: >>> from werkzeug.contrib.cache import SimpleCache >>> c = SimpleCache() >>> c.set("foo", "value") >>> c.get("foo") 'value' >>> c.get("missing") is None True Please keep in mind that you have to create the cache and put it somewhere you have access to it (either as a module global you can import or you just put it into your WSGI application). :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import re import errno import tempfile import platform from hashlib import md5 from time import time try: import cPickle as pickle except ImportError: # pragma: no cover import pickle from werkzeug._compat import iteritems, string_types, text_type, \ integer_types, to_native from werkzeug.posixemulation import rename def _items(mappingorseq): """Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v """ if hasattr(mappingorseq, 'items'): return iteritems(mappingorseq) return mappingorseq class BaseCache(object): """Baseclass for the cache systems. All the cache systems implement this API or a superset of it. :param default_timeout: the default timeout (in seconds) that is used if no timeout is specified on :meth:`set`. A timeout of 0 indicates that the cache never expires. """ def __init__(self, default_timeout=300): self.default_timeout = default_timeout def _normalize_timeout(self, timeout): if timeout is None: timeout = self.default_timeout return timeout def get(self, key): """Look up key in the cache and return the value for it. :param key: the key to be looked up. :returns: The value if it exists and is readable, else ``None``. """ return None def delete(self, key): """Delete `key` from the cache. :param key: the key to delete. :returns: Whether the key existed and has been deleted. :rtype: boolean """ return True def get_many(self, *keys): """Returns a list of values for the given keys. For each key a item in the list is created:: foo, bar = cache.get_many("foo", "bar") Has the same error handling as :meth:`get`. :param keys: The function accepts multiple keys as positional arguments. """ return map(self.get, keys) def get_dict(self, *keys): """Like :meth:`get_many` but return a dict:: d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"] :param keys: The function accepts multiple keys as positional arguments. """ return dict(zip(keys, self.get_many(*keys))) def set(self, key, value, timeout=None): """Add a new key/value to the cache (overwrites value, if key already exists in the cache). :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key in seconds (if not specified, it uses the default timeout). A timeout of 0 idicates that the cache never expires. :returns: ``True`` if key has been updated, ``False`` for backend errors. Pickling errors, however, will raise a subclass of ``pickle.PickleError``. :rtype: boolean """ return True def add(self, key, value, timeout=None): """Works like :meth:`set` but does not overwrite the values of already existing keys. :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key in seconds (if not specified, it uses the default timeout). A timeout of 0 idicates that the cache never expires. :returns: Same as :meth:`set`, but also ``False`` for already existing keys. :rtype: boolean """ return True def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key in seconds (if not specified, it uses the default timeout). A timeout of 0 idicates that the cache never expires. :returns: Whether all given keys have been set. :rtype: boolean """ rv = True for key, value in _items(mapping): if not self.set(key, value, timeout): rv = False return rv def delete_many(self, *keys): """Deletes multiple keys at once. :param keys: The function accepts multiple keys as positional arguments. :returns: Whether all given keys have been deleted. :rtype: boolean """ return all(self.delete(key) for key in keys) def has(self, key): """Checks if a key exists in the cache without returning it. This is a cheap operation that bypasses loading the actual data on the backend. This method is optional and may not be implemented on all caches. :param key: the key to check """ raise NotImplementedError( '%s doesn\'t have an efficient implementation of `has`. That ' 'means it is impossible to check whether a key exists without ' 'fully loading the key\'s data. Consider using `self.get` ' 'explicitly if you don\'t care about performance.' ) def clear(self): """Clears the cache. Keep in mind that not all caches support completely clearing the cache. :returns: Whether the cache has been cleared. :rtype: boolean """ return True def inc(self, key, delta=1): """Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add. :returns: The new value or ``None`` for backend errors. """ value = (self.get(key) or 0) + delta return value if self.set(key, value) else None def dec(self, key, delta=1): """Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract. :returns: The new value or `None` for backend errors. """ value = (self.get(key) or 0) - delta return value if self.set(key, value) else None class NullCache(BaseCache): """A cache that doesn't cache. This can be useful for unit testing. :param default_timeout: a dummy parameter that is ignored but exists for API compatibility with other caches. """ class SimpleCache(BaseCache): """Simple memory cache for single process environments. This class exists mainly for the development server and is not 100% thread safe. It tries to use as many atomic operations as possible and no locks for simplicity but it could happen under heavy load that keys are added multiple times. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates that the cache never expires. """ def __init__(self, threshold=500, default_timeout=300): BaseCache.__init__(self, default_timeout) self._cache = {} self.clear = self._cache.clear self._threshold = threshold def _prune(self): if len(self._cache) > self._threshold: now = time() toremove = [] for idx, (key, (expires, _)) in enumerate(self._cache.items()): if (expires != 0 and expires <= now) or idx % 3 == 0: toremove.append(key) for key in toremove: self._cache.pop(key, None) def _normalize_timeout(self, timeout): timeout = BaseCache._normalize_timeout(self, timeout) if timeout > 0: timeout = time() + timeout return timeout def get(self, key): try: expires, value = self._cache[key] if expires == 0 or expires > time(): return pickle.loads(value) except (KeyError, pickle.PickleError): return None def set(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() self._cache[key] = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) return True def add(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) if key in self._cache: return False self._cache.setdefault(key, item) return True def delete(self, key): return self._cache.pop(key, None) is not None def has(self, key): try: expires, value = self._cache[key] return expires == 0 or expires > time() except KeyError: return False _test_memcached_key = re.compile(r'[^\x00-\x21\xff]{1,250}$').match class MemcachedCache(BaseCache): """A cache that uses memcached as backend. The first argument can either be an object that resembles the API of a :class:`memcache.Client` or a tuple/list of server addresses. In the event that a tuple/list is passed, Werkzeug tries to import the best available memcache library. This cache looks into the following packages/modules to find bindings for memcached: - ``pylibmc`` - ``google.appengine.api.memcached`` - ``memcached`` Implementation notes: This cache backend works around some limitations in memcached to simplify the interface. For example unicode keys are encoded to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return the keys in the same format as passed. Furthermore all get methods silently ignore key errors to not cause problems when untrusted user data is passed to the get methods which is often the case in web applications. :param servers: a list or tuple of server addresses or alternatively a :class:`memcache.Client` or a compatible client. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates taht the cache never expires. :param key_prefix: a prefix that is added before all keys. This makes it possible to use the same memcached server for different applications. Keep in mind that :meth:`~BaseCache.clear` will also clear keys with a different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if servers is None or isinstance(servers, (list, tuple)): if servers is None: servers = ['127.0.0.1:11211'] self._client = self.import_preferred_memcache_lib(servers) if self._client is None: raise RuntimeError('no memcache module found') else: # NOTE: servers is actually an already initialized memcache # client. self._client = servers self.key_prefix = to_native(key_prefix) def _normalize_key(self, key): key = to_native(key, 'utf-8') if self.key_prefix: key = self.key_prefix + key return key def _normalize_timeout(self, timeout): timeout = BaseCache._normalize_timeout(self, timeout) if timeout > 0: timeout = int(time()) + timeout return timeout def get(self, key): key = self._normalize_key(key) # memcached doesn't support keys longer than that. Because often # checks for so long keys can occur because it's tested from user # submitted data etc we fail silently for getting. if _test_memcached_key(key): return self._client.get(key) def get_dict(self, *keys): key_mapping = {} have_encoded_keys = False for key in keys: encoded_key = self._normalize_key(key) if not isinstance(key, str): have_encoded_keys = True if _test_memcached_key(key): key_mapping[encoded_key] = key d = rv = self._client.get_multi(key_mapping.keys()) if have_encoded_keys or self.key_prefix: rv = {} for key, value in iteritems(d): rv[key_mapping[key]] = value if len(rv) < len(keys): for key in keys: if key not in rv: rv[key] = None return rv def add(self, key, value, timeout=None): key = self._normalize_key(key) timeout = self._normalize_timeout(timeout) return self._client.add(key, value, timeout) def set(self, key, value, timeout=None): key = self._normalize_key(key) timeout = self._normalize_timeout(timeout) return self._client.set(key, value, timeout) def get_many(self, *keys): d = self.get_dict(*keys) return [d[key] for key in keys] def set_many(self, mapping, timeout=None): new_mapping = {} for key, value in _items(mapping): key = self._normalize_key(key) new_mapping[key] = value timeout = self._normalize_timeout(timeout) failed_keys = self._client.set_multi(new_mapping, timeout) return not failed_keys def delete(self, key): key = self._normalize_key(key) if _test_memcached_key(key): return self._client.delete(key) def delete_many(self, *keys): new_keys = [] for key in keys: key = self._normalize_key(key) if _test_memcached_key(key): new_keys.append(key) return self._client.delete_multi(new_keys) def has(self, key): key = self._normalize_key(key) if _test_memcached_key(key): return self._client.append(key, '') return False def clear(self): return self._client.flush_all() def inc(self, key, delta=1): key = self._normalize_key(key) return self._client.incr(key, delta) def dec(self, key, delta=1): key = self._normalize_key(key) return self._client.decr(key, delta) def import_preferred_memcache_lib(self, servers): """Returns an initialized memcache client. Used by the constructor.""" try: import pylibmc except ImportError: pass else: return pylibmc.Client(servers) try: from google.appengine.api import memcache except ImportError: pass else: return memcache.Client() try: import memcache except ImportError: pass else: return memcache.Client(servers) # backwards compatibility GAEMemcachedCache = MemcachedCache class RedisCache(BaseCache): """Uses the Redis key-value store as a cache backend. The first argument can be either a string denoting address of the Redis server or an object resembling an instance of a redis.Redis class. Note: Python Redis API already takes care of encoding unicode strings on the fly. .. versionadded:: 0.7 .. versionadded:: 0.8 `key_prefix` was added. .. versionchanged:: 0.8 This cache backend now properly serializes objects. .. versionchanged:: 0.8.3 This cache backend now supports password authentication. .. versionchanged:: 0.10 ``**kwargs`` is now passed to the redis object. :param host: address of the Redis server or an object which API is compatible with the official Python Redis client (redis-py). :param port: port number on which Redis server listens for connections. :param password: password authentication for the Redis server. :param db: db (zero-based numeric index) on Redis Server to connect. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates that the cache never expires. :param key_prefix: A prefix that should be added to all keys. Any additional keyword arguments will be passed to ``redis.Redis``. """ def __init__(self, host='localhost', port=6379, password=None, db=0, default_timeout=300, key_prefix=None, **kwargs): BaseCache.__init__(self, default_timeout) if isinstance(host, string_types): try: import redis except ImportError: raise RuntimeError('no redis module found') if kwargs.get('decode_responses', None): raise ValueError('decode_responses is not supported by ' 'RedisCache.') self._client = redis.Redis(host=host, port=port, password=password, db=db, **kwargs) else: self._client = host self.key_prefix = key_prefix or '' def _normalize_timeout(self, timeout): timeout = BaseCache._normalize_timeout(self, timeout) if timeout == 0: timeout = -1 return timeout def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t in integer_types: return str(value).encode('ascii') return b'!' + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with None. """ if value is None: return None if value.startswith(b'!'): try: return pickle.loads(value[1:]) except pickle.PickleError: return None try: return int(value) except ValueError: # before 0.8 we did not have serialization. Still support that. return value def get(self, key): return self.load_object(self._client.get(self.key_prefix + key)) def get_many(self, *keys): if self.key_prefix: keys = [self.key_prefix + key for key in keys] return [self.load_object(x) for x in self._client.mget(keys)] def set(self, key, value, timeout=None): timeout = self._normalize_timeout(timeout) dump = self.dump_object(value) if timeout == -1: result = self._client.set(name=self.key_prefix + key, value=dump) else: result = self._client.setex(name=self.key_prefix + key, value=dump, time=timeout) return result def add(self, key, value, timeout=None): timeout = self._normalize_timeout(timeout) dump = self.dump_object(value) return ( self._client.setnx(name=self.key_prefix + key, value=dump) and self._client.expire(name=self.key_prefix + key, time=timeout) ) def set_many(self, mapping, timeout=None): timeout = self._normalize_timeout(timeout) # Use transaction=False to batch without calling redis MULTI # which is not supported by twemproxy pipe = self._client.pipeline(transaction=False) for key, value in _items(mapping): dump = self.dump_object(value) if timeout == -1: pipe.set(name=self.key_prefix + key, value=dump) else: pipe.setex(name=self.key_prefix + key, value=dump, time=timeout) return pipe.execute() def delete(self, key): return self._client.delete(self.key_prefix + key) def delete_many(self, *keys): if not keys: return if self.key_prefix: keys = [self.key_prefix + key for key in keys] return self._client.delete(*keys) def has(self, key): return self._client.exists(self.key_prefix + key) def clear(self): status = False if self.key_prefix: keys = self._client.keys(self.key_prefix + '*') if keys: status = self._client.delete(*keys) else: status = self._client.flushdb() return status def inc(self, key, delta=1): return self._client.incr(name=self.key_prefix + key, amount=delta) def dec(self, key, delta=1): return self._client.decr(name=self.key_prefix + key, amount=delta) class FileSystemCache(BaseCache): """A cache that stores the items on the file system. This cache depends on being the only user of the `cache_dir`. Make absolutely sure that nobody but this cache stores files there or otherwise the cache will randomly delete files therein. :param cache_dir: the directory where cache files are stored. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates that the cache never expires. :param mode: the file mode wanted for the cache files, default 0600 """ #: used for temporary files by the FileSystemCache _fs_transaction_suffix = '.__wz_cache' def __init__(self, cache_dir, threshold=500, default_timeout=300, mode=0o600): BaseCache.__init__(self, default_timeout) self._path = cache_dir self._threshold = threshold self._mode = mode try: os.makedirs(self._path) except OSError as ex: if ex.errno != errno.EEXIST: raise def _normalize_timeout(self, timeout): timeout = BaseCache._normalize_timeout(self, timeout) if timeout != 0: timeout = time() + timeout return int(timeout) def _list_dir(self): """return a list of (fully qualified) cache filenames """ return [os.path.join(self._path, fn) for fn in os.listdir(self._path) if not fn.endswith(self._fs_transaction_suffix)] def _prune(self): entries = self._list_dir() if len(entries) > self._threshold: now = time() for idx, fname in enumerate(entries): try: remove = False with open(fname, 'rb') as f: expires = pickle.load(f) remove = (expires != 0 and expires <= now) or idx % 3 == 0 if remove: os.remove(fname) except (IOError, OSError): pass def clear(self): for fname in self._list_dir(): try: os.remove(fname) except (IOError, OSError): return False return True def _get_filename(self, key): if isinstance(key, text_type): key = key.encode('utf-8') # XXX unicode review hash = md5(key).hexdigest() return os.path.join(self._path, hash) def get(self, key): filename = self._get_filename(key) try: with open(filename, 'rb') as f: pickle_time = pickle.load(f) if pickle_time == 0 or pickle_time >= time(): return pickle.load(f) else: os.remove(filename) return None except (IOError, OSError, pickle.PickleError): return None def add(self, key, value, timeout=None): filename = self._get_filename(key) if not os.path.exists(filename): return self.set(key, value, timeout) return False def set(self, key, value, timeout=None): timeout = self._normalize_timeout(timeout) filename = self._get_filename(key) self._prune() try: fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix, dir=self._path) with os.fdopen(fd, 'wb') as f: pickle.dump(timeout, f, 1) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) rename(tmp, filename) os.chmod(filename, self._mode) except (IOError, OSError): return False else: return True def delete(self, key): try: os.remove(self._get_filename(key)) except (IOError, OSError): return False else: return True def has(self, key): filename = self._get_filename(key) try: with open(filename, 'rb') as f: pickle_time = pickle.load(f) if pickle_time == 0 or pickle_time >= time(): return True else: os.remove(filename) return False except (IOError, OSError, pickle.PickleError): return False class UWSGICache(BaseCache): """ Implements the cache using uWSGI's caching framework. .. note:: This class cannot be used when running under PyPy, because the uWSGI API implementation for PyPy is lacking the needed functionality. :param default_timeout: The default timeout in seconds. :param cache: The name of the caching instance to connect to, for example: mycache@localhost:3031, defaults to an empty string, which means uWSGI will cache in the local instance. If the cache is in the same instance as the werkzeug app, you only have to provide the name of the cache. """ def __init__(self, default_timeout=300, cache=''): BaseCache.__init__(self, default_timeout) if platform.python_implementation() == 'PyPy': raise RuntimeError("uWSGI caching does not work under PyPy, see " "the docs for more details.") try: import uwsgi self._uwsgi = uwsgi except ImportError: raise RuntimeError("uWSGI could not be imported, are you " "running under uWSGI?") self.cache = cache def get(self, key): rv = self._uwsgi.cache_get(key, self.cache) if rv is None: return return pickle.loads(rv) def delete(self, key): return self._uwsgi.cache_del(key, self.cache) def set(self, key, value, timeout=None): return self._uwsgi.cache_update(key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache) def add(self, key, value, timeout=None): return self._uwsgi.cache_set(key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache) def clear(self): return self._uwsgi.cache_clear(self.cache) def has(self, key): return self._uwsgi.cache_exists(key, self.cache) is not None
jessrosenfield/pants
refs/heads/master
tests/python/pants_test/tasks/test_jvm_bundle_integration.py
14
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants_test.pants_run_integration_test import PantsRunIntegrationTest class BundleIntegrationTest(PantsRunIntegrationTest): def test_bundle_of_nonascii_classes(self): """JVM classes can have non-ASCII names. Make sure we don't assume ASCII.""" stdout = self.bundle_and_run('testprojects/src/java/org/pantsbuild/testproject/unicode/main', 'unicode-testproject') self.assertIn("Have a nice day!", stdout) self.assertIn("shapeless success", stdout) def test_bundle_colliding_resources(self): """Tests that the proper resource is bundled with each of these bundled targets when each project has a different resource with the same path. """ for name in ['a', 'b', 'c']: target = ('testprojects/maven_layout/resource_collision/example_{name}/' 'src/main/java/org/pantsbuild/duplicateres/example{name}/' .format(name=name)) bundle_name = 'example{proj}'.format(proj=name) stdout = self.bundle_and_run(target, bundle_name) self.assertEquals(stdout, 'Hello world!: resource from example {name}\n'.format(name=name))
pradyu1993/scikit-learn
refs/heads/master
sklearn/manifold/__init__.py
4
""" The :mod:`sklearn.manifold` module implements data embedding techniques. """ from .locally_linear import locally_linear_embedding, LocallyLinearEmbedding from .isomap import Isomap from .mds import MDS
facebookexperimental/eden
refs/heads/master
eden/scm/tests/test-fb-hgext-treemanifest-sparse-t.py
2
# Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import from testutil.dott import feature, sh, testtmp # noqa: F401 # test interaction between sparse and treemanifest (sparse file listing) ( sh % "cat" << r""" [extensions] sparse= treemanifest= [treemanifest] treeonly = True [remotefilelog] reponame = master cachepath = $PWD/hgcache """ >> "$HGRCPATH" ) # Setup the repository sh % "hg init myrepo" sh % "cd myrepo" sh % "touch show" sh % "touch hide" sh % "mkdir -p subdir/foo/spam subdir/bar/ham hiddensub/foo hiddensub/bar" sh % "touch subdir/foo/spam/show" sh % "touch subdir/bar/ham/hide" sh % "touch hiddensub/foo/spam" sh % "touch hiddensub/bar/ham" sh % "hg add ." == r""" adding hiddensub/bar/ham adding hiddensub/foo/spam adding hide adding show adding subdir/bar/ham/hide adding subdir/foo/spam/show""" sh % "hg commit -m Init" sh % "hg sparse include show" sh % "hg sparse exclude hide" sh % "hg sparse include subdir" sh % "hg sparse exclude subdir/foo" # Test cwd sh % "hg sparse cwd" == r""" - hiddensub - hide show subdir""" sh % "cd subdir" sh % "hg sparse cwd" == r""" bar - foo""" sh % "hg sparse include foo" sh % "hg sparse cwd" == r""" bar foo"""
hiptools/hiptools
refs/heads/master
russ_simp.py
1
#! /usr/bin/python2 # -*- coding: utf-8 -*- import codecs import re import os import sys import chardet import numb_conv n_conv = numb_conv.NumParser() class Mn: def __init__(self, stress=None, color=None, junk=None): '''This module tries to convert hip-encoded text into plain Russian''' # if args are True - all wiped out # diacritics self.stress_sw = stress # angle brackets self.color_sw = color # comments and stuff self.junk_sw = junk self.rg_er = re.compile(r"(.*)ъ(|\.|,|;|:|\?|!)?$", re.U) self.diacr = [["`", "\'"], ["^", "\'"]] self.color = ["%<", "%>"] self.junk = ["{", "}", "@", "!"] self.lett = [["jа", "я"], ["JА", "Я"], ["_я", "я"], ["_Я", "Я"], ["jь", "е"], ["Jь", "Е"], ["_е", "е"], ["_Е", "Е"], ["_о", "о"], ["_О", "О"], ["_w", "о"], ["_W", "О"], ["w", "о"], ["W", "О"], ["о_у", "у"], ["О_у", "У"], ["о<у>", "у"], ["О<у>", "У"], ["s", "з"], ["S", "З"], ["i", "и"], ["I", "И"], ["v\"", "и"], ["V\"", "И"], ["v\'", "и\'"], ["V\'", "И\'"], ["v=", "и"], ["V=", "И"], ["v", "в"], ["V", "В"], ["f", "ф"], ["F", "Ф"], ["_кс", "кс"], ["_Кс", "Кс"], ["_пс", "пс"], ["_Пс", "Пс"], ["\\", ""], ["=", ""]] # fill up the titlo-filter list from file # fil_name = '/usr/local/bin/titlo_filter' # fil_name = 'titlo_filter_sm' fil_name = os.path.join(os.path.expanduser('~'), '.config', 'hiptools', 'titlo_filter') try: fp = codecs.open(fil_name, "rb", "utf8") text_l = fp.readlines() fp.close() self.filter = [] for line in text_l: line = line.encode('utf8').strip() a, b = line.split(' ') # print a, b a = re.compile(a, re.U) self.filter.append((a, b)) # print self.filter except IOError: print 'no such file found:', fil_name # sys.exit(1) def opener(self, f_name): try: fp = open(f_name) text_l = fp.readlines() fp.close() slice = ''.join(text_l[:3]) enc = chardet.detect(slice)['encoding'] if not enc: enc = 'utf8' for line in text_l: line = line.decode(enc) out = self.conv_str(line) print out except IOError: print 'no such file found:', f_name def conv_str(self, line): # To put text through this function helps debugging line = line.strip().split(' ') line_l = [] # print line for wrd in line: wrd = wrd.strip() wrd = wrd.encode('utf8') wrd = self.conv_ru(wrd) line_l.append(wrd) res = ' '.join(line_l) return res def conv_ru(self, wrd): '''russify the word''' # open up titlo if '~' in wrd or '\\' in wrd: for key, val in self.filter: # if key in wrd: if key.search(wrd): # wrd = wrd.replace(key, val) wrd = key.sub(val, wrd) break # numbers if '~' in wrd: wrd = wrd.decode('utf8') res = n_conv.slav2rus(wrd) if res[0]: wrd = str(res[0]) + res[1] wrd = wrd.encode('utf8') # print 'word:', wrd # DEBUG titlo_filter and numb_conv!!! ^^^ # convert slavic letters for a, b in self.lett: wrd = wrd.replace(a, b) for a, b in self.diacr: wrd = wrd.replace(a, b) if self.stress_sw: # print 'stress' wrd = wrd.replace("\'", "") # print i # print wrd if self.color_sw: for y in self.color: wrd = wrd.replace(y, "") # print y # print wrd if self.junk_sw: for j in self.junk: wrd = wrd.replace(j, "") if "ъ" in wrd: wrd = self.rg_er.sub("\\1\\2", wrd) return wrd ###################main########################### if __name__ == '__main__': from optparse import OptionParser usage = "usage: russ_simp.py [options] file" parser = OptionParser(usage=usage) parser.add_option("-d", "--debug", dest="debug", action='store_true', default=False, help="Work in the debuging mode") parser.add_option("-s", "--stress", dest="stress", action='store_true', default=False, help="Remove stress from text") parser.add_option("-c", "--color", dest="color", action='store_true', default=False, help="Remove color tags from text") parser.add_option("-j", "--junk", dest="junk", action='store_true', default=False, help="Remove service symbols from text") (options, args) = parser.parse_args() rep = Mn(options.stress, options.color, options.junk) if args: f_path = args[0] rep.opener(f_path) elif options.debug: # rep.conv_str(u'пр\сн') rep.conv_str(u'<%п>%е\'снь') else: print "No file name given, exiting" sys.exit(1) #TODO: titlo_filter_sm use it when small filter needed. # fix titilo_filter so, that it would output captial letters in words like Христос # make option for including|excluding comments in hip # fix parser from russify to work with tags like %< @{ etc. Otherwise "%<Гласъ а~%> doesn't work # знак вопроса пофикси!
mbr0wn/gnuradio
refs/heads/master
gr-blocks/python/blocks/__init__.py
3
# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # ''' Processing blocks common to many flowgraphs. ''' import os try: from .blocks_python import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "bindings")) from .blocks_python import * from .stream_to_vector_decimator import * from .msg_meta_to_pair import meta_to_pair from .msg_pair_to_var import msg_pair_to_var from .var_to_msg import var_to_msg_pair #alias old add_vXX and multiply_vXX add_vcc = add_cc add_vff = add_ff add_vii = add_ii add_vss = add_ss multiply_vcc = multiply_cc multiply_vff = multiply_ff multiply_vii = multiply_ii multiply_vss = multiply_ss
wmvanvliet/mne-python
refs/heads/master
mne/coreg.py
1
# -*- coding: utf-8 -*- """Coregistration between different coordinate frames.""" # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) import configparser import fnmatch from glob import glob, iglob import os import os.path as op import stat import sys import re import shutil from functools import reduce import numpy as np from .io import read_fiducials, write_fiducials, read_info from .io.constants import FIFF from .label import read_label, Label from .source_space import (add_source_space_distances, read_source_spaces, write_source_spaces, read_talxfm, _read_mri_info) from .surface import read_surface, write_surface, _normalize_vectors from .bem import read_bem_surfaces, write_bem_surfaces from .transforms import (rotation, rotation3d, scaling, translation, Transform, _read_fs_xfm, _write_fs_xfm, invert_transform, combine_transforms, apply_trans, _quat_to_euler, _fit_matched_points) from .utils import (get_config, get_subjects_dir, logger, pformat, verbose, warn, has_nibabel) from .viz._3d import _fiducial_coords # some path templates trans_fname = os.path.join('{raw_dir}', '{subject}-trans.fif') subject_dirname = os.path.join('{subjects_dir}', '{subject}') bem_dirname = os.path.join(subject_dirname, 'bem') mri_dirname = os.path.join(subject_dirname, 'mri') mri_transforms_dirname = os.path.join(subject_dirname, 'mri', 'transforms') surf_dirname = os.path.join(subject_dirname, 'surf') bem_fname = os.path.join(bem_dirname, "{subject}-{name}.fif") head_bem_fname = pformat(bem_fname, name='head') fid_fname = pformat(bem_fname, name='fiducials') fid_fname_general = os.path.join(bem_dirname, "{head}-fiducials.fif") src_fname = os.path.join(bem_dirname, '{subject}-{spacing}-src.fif') _head_fnames = (os.path.join(bem_dirname, 'outer_skin.surf'), head_bem_fname) _high_res_head_fnames = (os.path.join(bem_dirname, '{subject}-head-dense.fif'), os.path.join(surf_dirname, 'lh.seghead'), os.path.join(surf_dirname, 'lh.smseghead')) def _make_writable(fname): """Make a file writable.""" os.chmod(fname, stat.S_IMODE(os.lstat(fname)[stat.ST_MODE]) | 128) # write def _make_writable_recursive(path): """Recursively set writable.""" if sys.platform.startswith('win'): return # can't safely set perms for root, dirs, files in os.walk(path, topdown=False): for f in dirs + files: _make_writable(os.path.join(root, f)) def _find_head_bem(subject, subjects_dir, high_res=False): """Find a high resolution head.""" # XXX this should be refactored with mne.surface.get_head_surf ... fnames = _high_res_head_fnames if high_res else _head_fnames for fname in fnames: path = fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): return path def coregister_fiducials(info, fiducials, tol=0.01): """Create a head-MRI transform by aligning 3 fiducial points. Parameters ---------- info : Info Measurement info object with fiducials in head coordinate space. fiducials : str | list of dict Fiducials in MRI coordinate space (either path to a ``*-fiducials.fif`` file or list of fiducials as returned by :func:`read_fiducials`. Returns ------- trans : Transform The device-MRI transform. """ if isinstance(info, str): info = read_info(info) if isinstance(fiducials, str): fiducials, coord_frame_to = read_fiducials(fiducials) else: coord_frame_to = FIFF.FIFFV_COORD_MRI frames_from = {d['coord_frame'] for d in info['dig']} if len(frames_from) > 1: raise ValueError("info contains fiducials from different coordinate " "frames") else: coord_frame_from = frames_from.pop() coords_from = _fiducial_coords(info['dig']) coords_to = _fiducial_coords(fiducials, coord_frame_to) trans = fit_matched_points(coords_from, coords_to, tol=tol) return Transform(coord_frame_from, coord_frame_to, trans) @verbose def create_default_subject(fs_home=None, update=False, subjects_dir=None, verbose=None): """Create an average brain subject for subjects without structural MRI. Create a copy of fsaverage from the Freesurfer directory in subjects_dir and add auxiliary files from the mne package. Parameters ---------- fs_home : None | str The freesurfer home directory (only needed if FREESURFER_HOME is not specified as environment variable). update : bool In cases where a copy of the fsaverage brain already exists in the subjects_dir, this option allows to only copy files that don't already exist in the fsaverage directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (os.environ['SUBJECTS_DIR']) as destination for the new subject. %(verbose)s Notes ----- When no structural MRI is available for a subject, an average brain can be substituted. Freesurfer comes with such an average brain model, and MNE comes with some auxiliary files which make coregistration easier. :py:func:`create_default_subject` copies the relevant files from Freesurfer into the current subjects_dir, and also adds the auxiliary files provided by MNE. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if fs_home is None: fs_home = get_config('FREESURFER_HOME', fs_home) if fs_home is None: raise ValueError( "FREESURFER_HOME environment variable not found. Please " "specify the fs_home parameter in your call to " "create_default_subject().") # make sure freesurfer files exist fs_src = os.path.join(fs_home, 'subjects', 'fsaverage') if not os.path.exists(fs_src): raise IOError('fsaverage not found at %r. Is fs_home specified ' 'correctly?' % fs_src) for name in ('label', 'mri', 'surf'): dirname = os.path.join(fs_src, name) if not os.path.isdir(dirname): raise IOError("Freesurfer fsaverage seems to be incomplete: No " "directory named %s found in %s" % (name, fs_src)) # make sure destination does not already exist dest = os.path.join(subjects_dir, 'fsaverage') if dest == fs_src: raise IOError( "Your subjects_dir points to the freesurfer subjects_dir (%r). " "The default subject can not be created in the freesurfer " "installation directory; please specify a different " "subjects_dir." % subjects_dir) elif (not update) and os.path.exists(dest): raise IOError( "Can not create fsaverage because %r already exists in " "subjects_dir %r. Delete or rename the existing fsaverage " "subject folder." % ('fsaverage', subjects_dir)) # copy fsaverage from freesurfer logger.info("Copying fsaverage subject from freesurfer directory...") if (not update) or not os.path.exists(dest): shutil.copytree(fs_src, dest) _make_writable_recursive(dest) # copy files from mne source_fname = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage', 'fsaverage-%s.fif') dest_bem = os.path.join(dest, 'bem') if not os.path.exists(dest_bem): os.mkdir(dest_bem) logger.info("Copying auxiliary fsaverage files from mne...") dest_fname = os.path.join(dest_bem, 'fsaverage-%s.fif') _make_writable_recursive(dest_bem) for name in ('fiducials', 'head', 'inner_skull-bem', 'trans'): if not os.path.exists(dest_fname % name): shutil.copy(source_fname % name, dest_bem) def _decimate_points(pts, res=10): """Decimate the number of points using a voxel grid. Create a voxel grid with a specified resolution and retain at most one point per voxel. For each voxel, the point closest to its center is retained. Parameters ---------- pts : array, shape (n_points, 3) The points making up the head shape. res : scalar The resolution of the voxel space (side length of each voxel). Returns ------- pts : array, shape = (n_points, 3) The decimated points. """ from scipy.spatial.distance import cdist pts = np.asarray(pts) # find the bin edges for the voxel space xmin, ymin, zmin = pts.min(0) - res / 2. xmax, ymax, zmax = pts.max(0) + res xax = np.arange(xmin, xmax, res) yax = np.arange(ymin, ymax, res) zax = np.arange(zmin, zmax, res) # find voxels containing one or more point H, _ = np.histogramdd(pts, bins=(xax, yax, zax), normed=False) # for each voxel, select one point X, Y, Z = pts.T out = np.empty((np.sum(H > 0), 3)) for i, (xbin, ybin, zbin) in enumerate(zip(*np.nonzero(H))): x = xax[xbin] y = yax[ybin] z = zax[zbin] xi = np.logical_and(X >= x, X < x + res) yi = np.logical_and(Y >= y, Y < y + res) zi = np.logical_and(Z >= z, Z < z + res) idx = np.logical_and(zi, np.logical_and(yi, xi)) ipts = pts[idx] mid = np.array([x, y, z]) + res / 2. dist = cdist(ipts, [mid]) i_min = np.argmin(dist) ipt = ipts[i_min] out[i] = ipt return out def _trans_from_params(param_info, params): """Convert transformation parameters into a transformation matrix. Parameters ---------- param_info : tuple, len = 3 Tuple describing the parameters in x (do_translate, do_rotate, do_scale). params : tuple The transformation parameters. Returns ------- trans : array, shape = (4, 4) Transformation matrix. """ do_rotate, do_translate, do_scale = param_info i = 0 trans = [] if do_rotate: x, y, z = params[:3] trans.append(rotation(x, y, z)) i += 3 if do_translate: x, y, z = params[i:i + 3] trans.insert(0, translation(x, y, z)) i += 3 if do_scale == 1: s = params[i] trans.append(scaling(s, s, s)) elif do_scale == 3: x, y, z = params[i:i + 3] trans.append(scaling(x, y, z)) trans = reduce(np.dot, trans) return trans _ALLOW_ANALITICAL = True # XXX this function should be moved out of coreg as used elsewhere def fit_matched_points(src_pts, tgt_pts, rotate=True, translate=True, scale=False, tol=None, x0=None, out='trans', weights=None): """Find a transform between matched sets of points. This minimizes the squared distance between two matching sets of points. Uses :func:`scipy.optimize.leastsq` to find a transformation involving a combination of rotation, translation, and scaling (in that order). Parameters ---------- src_pts : array, shape = (n, 3) Points to which the transform should be applied. tgt_pts : array, shape = (n, 3) Points to which src_pts should be fitted. Each point in tgt_pts should correspond to the point in src_pts with the same index. rotate : bool Allow rotation of the ``src_pts``. translate : bool Allow translation of the ``src_pts``. scale : bool Number of scaling parameters. With False, points are not scaled. With True, points are scaled by the same factor along all axes. tol : scalar | None The error tolerance. If the distance between any of the matched points exceeds this value in the solution, a RuntimeError is raised. With None, no error check is performed. x0 : None | tuple Initial values for the fit parameters. out : 'params' | 'trans' In what format to return the estimate: 'params' returns a tuple with the fit parameters; 'trans' returns a transformation matrix of shape (4, 4). Returns ------- trans : array, shape (4, 4) Transformation that, if applied to src_pts, minimizes the squared distance to tgt_pts. Only returned if out=='trans'. params : array, shape (n_params, ) A single tuple containing the rotation, translation, and scaling parameters in that order (as applicable). """ src_pts = np.atleast_2d(src_pts) tgt_pts = np.atleast_2d(tgt_pts) if src_pts.shape != tgt_pts.shape: raise ValueError("src_pts and tgt_pts must have same shape (got " "{}, {})".format(src_pts.shape, tgt_pts.shape)) if weights is not None: weights = np.asarray(weights, src_pts.dtype) if weights.ndim != 1 or weights.size not in (src_pts.shape[0], 1): raise ValueError("weights (shape=%s) must be None or have shape " "(%s,)" % (weights.shape, src_pts.shape[0],)) weights = weights[:, np.newaxis] param_info = (bool(rotate), bool(translate), int(scale)) del rotate, translate, scale # very common use case, rigid transformation (maybe with one scale factor, # with or without weighted errors) if param_info in ((True, True, 0), (True, True, 1)) and _ALLOW_ANALITICAL: src_pts = np.asarray(src_pts, float) tgt_pts = np.asarray(tgt_pts, float) x, s = _fit_matched_points( src_pts, tgt_pts, weights, bool(param_info[2])) x[:3] = _quat_to_euler(x[:3]) x = np.concatenate((x, [s])) if param_info[2] else x else: x = _generic_fit(src_pts, tgt_pts, param_info, weights, x0) # re-create the final transformation matrix if (tol is not None) or (out == 'trans'): trans = _trans_from_params(param_info, x) # assess the error of the solution if tol is not None: src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) est_pts = np.dot(src_pts, trans.T)[:, :3] err = np.sqrt(np.sum((est_pts - tgt_pts) ** 2, axis=1)) if np.any(err > tol): raise RuntimeError("Error exceeds tolerance. Error = %r" % err) if out == 'params': return x elif out == 'trans': return trans else: raise ValueError("Invalid out parameter: %r. Needs to be 'params' or " "'trans'." % out) def _generic_fit(src_pts, tgt_pts, param_info, weights, x0): from scipy.optimize import leastsq if param_info[1]: # translate src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) if param_info == (True, False, 0): def error(x): rx, ry, rz = x trans = rotation3d(rx, ry, rz) est = np.dot(src_pts, trans.T) d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0) elif param_info == (True, True, 0): def error(x): rx, ry, rz, tx, ty, tz = x trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz)) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0) elif param_info == (True, True, 1): def error(x): rx, ry, rz, tx, ty, tz, s = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(s, s, s))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1) elif param_info == (True, True, 3): def error(x): rx, ry, rz, tx, ty, tz, sx, sy, sz = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(sx, sy, sz))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1, 1, 1) else: raise NotImplementedError( "The specified parameter combination is not implemented: " "rotate=%r, translate=%r, scale=%r" % param_info) x, _, _, _, _ = leastsq(error, x0, full_output=True) return x def _find_label_paths(subject='fsaverage', pattern=None, subjects_dir=None): """Find paths to label files in a subject's label directory. Parameters ---------- subject : str Name of the mri subject. pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "aparc/*.label" will find all labels in the "subject/label/aparc" directory). With None, find all labels. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : list List of paths relative to the subject's label directory """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_dir = os.path.join(subjects_dir, subject) lbl_dir = os.path.join(subject_dir, 'label') if pattern is None: paths = [] for dirpath, _, filenames in os.walk(lbl_dir): rel_dir = os.path.relpath(dirpath, lbl_dir) for filename in fnmatch.filter(filenames, '*.label'): path = os.path.join(rel_dir, filename) paths.append(path) else: paths = [os.path.relpath(path, lbl_dir) for path in iglob(pattern)] return paths def _find_mri_paths(subject, skip_fiducials, subjects_dir): """Find all files of an mri relevant for source transformation. Parameters ---------- subject : str Name of the mri subject. skip_fiducials : bool Do not scale the MRI fiducials. If False, an IOError will be raised if no fiducials file can be found. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : dict Dictionary whose keys are relevant file type names (str), and whose values are lists of paths. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = {} # directories to create paths['dirs'] = [bem_dirname, surf_dirname] # surf/ files paths['surf'] = [] surf_fname = os.path.join(surf_dirname, '{name}') surf_names = ('inflated', 'white', 'orig', 'orig_avg', 'inflated_avg', 'inflated_pre', 'pial', 'pial_avg', 'smoothwm', 'white_avg', 'seghead', 'smseghead') if os.getenv('_MNE_FEW_SURFACES', '') == 'true': # for testing surf_names = surf_names[:4] for surf_name in surf_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=name)) surf_fname = os.path.join(bem_dirname, '{name}') surf_names = ('inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf') for surf_name in surf_names: path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=surf_name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=surf_name)) del surf_names, surf_name, path, hemi # BEM files paths['bem'] = bem = [] path = head_bem_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): bem.append('head') bem_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='*-bem') re_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='(.+)').replace('\\', '\\\\') for path in iglob(bem_pattern): match = re.match(re_pattern, path) name = match.group(1) bem.append(name) del bem, path, bem_pattern, re_pattern # fiducials if skip_fiducials: paths['fid'] = [] else: paths['fid'] = _find_fiducials_files(subject, subjects_dir) # check that we found at least one if len(paths['fid']) == 0: raise IOError("No fiducials file found for %s. The fiducials " "file should be named " "{subject}/bem/{subject}-fiducials.fif. In " "order to scale an MRI without fiducials set " "skip_fiducials=True." % subject) # duplicate files (curvature and some surfaces) paths['duplicate'] = [] path = os.path.join(surf_dirname, '{name}') surf_fname = os.path.join(surf_dirname, '{name}') surf_dup_names = ('curv', 'sphere', 'sphere.reg', 'sphere.reg.avg') for surf_dup_name in surf_dup_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_dup_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['duplicate'].append(pformat(surf_fname, name=name)) del surf_dup_name, name, path, hemi # transform files (talairach) paths['transforms'] = [] transform_fname = os.path.join(mri_transforms_dirname, 'talairach.xfm') path = transform_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): paths['transforms'].append(transform_fname) del transform_fname, path # find source space files paths['src'] = src = [] bem_dir = bem_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(bem_dir), '*-src.fif') prefix = subject + '-' for fname in fnames: if fname.startswith(prefix): fname = "{subject}-%s" % fname[len(prefix):] path = os.path.join(bem_dirname, fname) src.append(path) # find MRIs mri_dir = mri_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(mri_dir), '*.mgz') paths['mri'] = [os.path.join(mri_dir, f) for f in fnames] return paths def _find_fiducials_files(subject, subjects_dir): """Find fiducial files.""" fid = [] # standard fiducials if os.path.exists(fid_fname.format(subjects_dir=subjects_dir, subject=subject)): fid.append(fid_fname) # fiducials with subject name pattern = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='*') regex = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='(.+)').replace('\\', '\\\\') for path in iglob(pattern): match = re.match(regex, path) head = match.group(1).replace(subject, '{subject}') fid.append(pformat(fid_fname_general, head=head)) return fid def _is_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is an mri subject directory. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_mri_subject : bool Whether ``subject`` is an mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) return bool(_find_head_bem(subject, subjects_dir) or _find_head_bem(subject, subjects_dir, high_res=True)) def _is_scaled_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is a scaled mri subject. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_scaled_mri_subject : bool Whether ``subject`` is a scaled mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if not _is_mri_subject(subject, subjects_dir): return False fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') return os.path.exists(fname) def _mri_subject_has_bem(subject, subjects_dir=None): """Check whether an mri subject has a file matching the bem pattern. Parameters ---------- subject : str Name of the subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- has_bem_file : bool Whether ``subject`` has a bem file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) pattern = bem_fname.format(subjects_dir=subjects_dir, subject=subject, name='*-bem') fnames = glob(pattern) return bool(len(fnames)) def read_mri_cfg(subject, subjects_dir=None): """Read information from the cfg file of a scaled MRI brain. Parameters ---------- subject : str Name of the scaled MRI subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- cfg : dict Dictionary with entries from the MRI's cfg file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') if not os.path.exists(fname): raise IOError("%r does not seem to be a scaled mri subject: %r does " "not exist." % (subject, fname)) logger.info("Reading MRI cfg file %s" % fname) config = configparser.RawConfigParser() config.read(fname) n_params = config.getint("MRI Scaling", 'n_params') if n_params == 1: scale = config.getfloat("MRI Scaling", 'scale') elif n_params == 3: scale_str = config.get("MRI Scaling", 'scale') scale = np.array([float(s) for s in scale_str.split()]) else: raise ValueError("Invalid n_params value in MRI cfg: %i" % n_params) out = {'subject_from': config.get("MRI Scaling", 'subject_from'), 'n_params': n_params, 'scale': scale} return out def _write_mri_config(fname, subject_from, subject_to, scale): """Write the cfg file describing a scaled MRI subject. Parameters ---------- fname : str Target file. subject_from : str Name of the source MRI subject. subject_to : str Name of the scaled MRI subject. scale : float | array_like, shape = (3,) The scaling parameter. """ scale = np.asarray(scale) if np.isscalar(scale) or scale.shape == (): n_params = 1 else: n_params = 3 config = configparser.RawConfigParser() config.add_section("MRI Scaling") config.set("MRI Scaling", 'subject_from', subject_from) config.set("MRI Scaling", 'subject_to', subject_to) config.set("MRI Scaling", 'n_params', str(n_params)) if n_params == 1: config.set("MRI Scaling", 'scale', str(scale)) else: config.set("MRI Scaling", 'scale', ' '.join([str(s) for s in scale])) config.set("MRI Scaling", 'version', '1') with open(fname, 'w') as fid: config.write(fid) def _scale_params(subject_to, subject_from, scale, subjects_dir): """Assemble parameters for scaling. Returns ------- subjects_dir : str Subjects directory. subject_from : str Name of the source subject. scale : array Scaling factor, either shape=() for uniform scaling or shape=(3,) for non-uniform scaling. uniform : bool Whether scaling is uniform. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if (subject_from is None) != (scale is None): raise TypeError("Need to provide either both subject_from and scale " "parameters, or neither.") if subject_from is None: cfg = read_mri_cfg(subject_to, subjects_dir) subject_from = cfg['subject_from'] n_params = cfg['n_params'] assert n_params in (1, 3) scale = cfg['scale'] scale = np.atleast_1d(scale) if scale.ndim != 1 or scale.shape[0] not in (1, 3): raise ValueError("Invalid shape for scale parameer. Need scalar " "or array of length 3. Got shape %s." % (scale.shape,)) n_params = len(scale) return subjects_dir, subject_from, scale, n_params == 1 @verbose def scale_bem(subject_to, bem_name, subject_from=None, scale=None, subjects_dir=None, verbose=None): """Scale a bem file. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). bem_name : str Name of the bem file. For example, to scale ``fsaverage-inner_skull-bem.fif``, the bem_name would be "inner_skull-bem". subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. %(verbose)s """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) src = bem_fname.format(subjects_dir=subjects_dir, subject=subject_from, name=bem_name) dst = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name=bem_name) if os.path.exists(dst): raise IOError("File already exists: %s" % dst) surfs = read_bem_surfaces(src) for surf in surfs: surf['rr'] *= scale if not uniform: assert len(surf['nn']) > 0 surf['nn'] /= scale _normalize_vectors(surf['nn']) write_bem_surfaces(dst, surfs) def scale_labels(subject_to, pattern=None, overwrite=False, subject_from=None, scale=None, subjects_dir=None): r"""Scale labels to match a brain that was previously created by scaling. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination brain). pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "lh.BA3a.label" will scale "fsaverage/label/lh.BA3a.label"; "aparc/\*.label" will find all labels in the "fsaverage/label/aparc" directory). With None, scale all labels. overwrite : bool Overwrite any label file that already exists for subject_to (otherwise existing labels are skipped). subject_from : None | str Name of the original MRI subject (the brain that was scaled to create subject_to). If None, the value is read from subject_to's cfg file. scale : None | float | array_like, shape = (3,) Scaling parameter. If None, the value is read from subject_to's cfg file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. """ subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # find labels paths = _find_label_paths(subject_from, pattern, subjects_dir) if not paths: return subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) src_root = os.path.join(subjects_dir, subject_from, 'label') dst_root = os.path.join(subjects_dir, subject_to, 'label') # scale labels for fname in paths: dst = os.path.join(dst_root, fname) if not overwrite and os.path.exists(dst): continue dirname = os.path.dirname(dst) if not os.path.exists(dirname): os.makedirs(dirname) src = os.path.join(src_root, fname) l_old = read_label(src) pos = l_old.pos * scale l_new = Label(l_old.vertices, pos, l_old.values, l_old.hemi, l_old.comment, subject=subject_to) l_new.save(dst) @verbose def scale_mri(subject_from, subject_to, scale, overwrite=False, subjects_dir=None, skip_fiducials=False, labels=True, annot=False, verbose=None): """Create a scaled copy of an MRI subject. Parameters ---------- subject_from : str Name of the subject providing the MRI. subject_to : str New subject name for which to save the scaled MRI. scale : float | array_like, shape = (3,) The scaling factor (one or 3 parameters). overwrite : bool If an MRI already exists for subject_to, overwrite it. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. skip_fiducials : bool Do not scale the MRI fiducials. If False (default), an IOError will be raised if no fiducials file can be found. labels : bool Also scale all labels (default True). annot : bool Copy ``*.annot`` files to the new location (default False). %(verbose)s See Also -------- scale_labels : Add labels to a scaled MRI. scale_source_space : Add a source space to a scaled MRI. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = _find_mri_paths(subject_from, skip_fiducials, subjects_dir) scale = np.atleast_1d(scale) if scale.shape == (3,): if np.isclose(scale[1], scale[0]) and np.isclose(scale[2], scale[0]): scale = scale[0] # speed up scaling conditionals using a singleton elif scale.shape != (1,): raise ValueError('scale must have shape (3,) or (1,), got %s' % (scale.shape,)) # make sure we have an empty target directory dest = subject_dirname.format(subject=subject_to, subjects_dir=subjects_dir) if os.path.exists(dest): if not overwrite: raise IOError("Subject directory for %s already exists: %r" % (subject_to, dest)) shutil.rmtree(dest) logger.debug('create empty directory structure') for dirname in paths['dirs']: dir_ = dirname.format(subject=subject_to, subjects_dir=subjects_dir) os.makedirs(dir_) logger.debug('save MRI scaling parameters') fname = os.path.join(dest, 'MRI scaling parameters.cfg') _write_mri_config(fname, subject_from, subject_to, scale) logger.debug('surf files [in mm]') for fname in paths['surf']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) pts, tri = read_surface(src) write_surface(dest, pts * scale, tri) logger.debug('BEM files [in m]') for bem_name in paths['bem']: scale_bem(subject_to, bem_name, subject_from, scale, subjects_dir, verbose=False) logger.debug('fiducials [in m]') for fname in paths['fid']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) pts, cframe = read_fiducials(src, verbose=False) for pt in pts: pt['r'] = pt['r'] * scale dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) write_fiducials(dest, pts, cframe, verbose=False) logger.debug('MRIs [nibabel]') os.mkdir(mri_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['mri']: mri_name = os.path.basename(fname) _scale_mri(subject_to, mri_name, subject_from, scale, subjects_dir) logger.debug('Transforms') for mri_name in paths['mri']: if mri_name.endswith('T1.mgz'): os.mkdir(mri_transforms_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['transforms']: xfm_name = os.path.basename(fname) _scale_xfm(subject_to, xfm_name, mri_name, subject_from, scale, subjects_dir) break logger.debug('duplicate files') for fname in paths['duplicate']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) shutil.copyfile(src, dest) logger.debug('source spaces') for fname in paths['src']: src_name = os.path.basename(fname) scale_source_space(subject_to, src_name, subject_from, scale, subjects_dir, verbose=False) logger.debug('labels [in m]') os.mkdir(os.path.join(subjects_dir, subject_to, 'label')) if labels: scale_labels(subject_to, subject_from=subject_from, scale=scale, subjects_dir=subjects_dir) logger.debug('copy *.annot files') # they don't contain scale-dependent information if annot: src_pattern = os.path.join(subjects_dir, subject_from, 'label', '*.annot') dst_dir = os.path.join(subjects_dir, subject_to, 'label') for src_file in iglob(src_pattern): shutil.copy(src_file, dst_dir) @verbose def scale_source_space(subject_to, src_name, subject_from=None, scale=None, subjects_dir=None, n_jobs=1, verbose=None): """Scale a source space for an mri created with scale_mri(). Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). src_name : str Source space name. Can be a spacing parameter (e.g., ``'7'``, ``'ico4'``, ``'oct6'``) or a file name of a source space file relative to the bem directory; if the file name contains the subject name, it should be indicated as "{subject}" in ``src_name`` (e.g., ``"{subject}-my_source_space-src.fif"``). subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. n_jobs : int Number of jobs to run in parallel if recomputing distances (only applies if scale is an array of length 3, and will not use more cores than there are source spaces). %(verbose)s Notes ----- When scaling volume source spaces, the source (vertex) locations are scaled, but the reference to the MRI volume is left unchanged. Transforms are updated so that source estimates can be plotted on the original MRI volume. """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) # if n_params==1 scale is a scalar; if n_params==3 scale is a (3,) array # find the source space file names if src_name.isdigit(): spacing = src_name # spacing in mm src_pattern = src_fname else: match = re.match(r"(oct|ico|vol)-?(\d+)$", src_name) if match: spacing = '-'.join(match.groups()) src_pattern = src_fname else: spacing = None src_pattern = os.path.join(bem_dirname, src_name) src = src_pattern.format(subjects_dir=subjects_dir, subject=subject_from, spacing=spacing) dst = src_pattern.format(subjects_dir=subjects_dir, subject=subject_to, spacing=spacing) # read and scale the source space [in m] sss = read_source_spaces(src) logger.info("scaling source space %s: %s -> %s", spacing, subject_from, subject_to) logger.info("Scale factor: %s", scale) add_dist = False for ss in sss: ss['subject_his_id'] = subject_to ss['rr'] *= scale # additional tags for volume source spaces for key in ('vox_mri_t', 'src_mri_t'): # maintain transform to original MRI volume ss['mri_volume_name'] if key in ss: ss[key]['trans'][:3] *= scale[:, np.newaxis] # distances and patch info if uniform: if ss['dist'] is not None: ss['dist'] *= scale[0] # Sometimes this is read-only due to how it's read ss['nearest_dist'] = ss['nearest_dist'] * scale ss['dist_limit'] = ss['dist_limit'] * scale else: # non-uniform scaling ss['nn'] /= scale _normalize_vectors(ss['nn']) if ss['dist'] is not None: add_dist = True dist_limit = float(np.abs(sss[0]['dist_limit'])) elif ss['nearest'] is not None: add_dist = True dist_limit = 0 if add_dist: logger.info("Recomputing distances, this might take a while") add_source_space_distances(sss, dist_limit, n_jobs) write_source_spaces(dst, sss) def _scale_mri(subject_to, mri_fname, subject_from, scale, subjects_dir): """Scale an MRI by setting its affine.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) if not has_nibabel(): warn('Skipping MRI scaling for %s, please install nibabel') return import nibabel fname_from = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_from), mri_fname) fname_to = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), mri_fname) img = nibabel.load(fname_from) zooms = np.array(img.header.get_zooms()) zooms[[0, 2, 1]] *= scale img.header.set_zooms(zooms) # Hack to fix nibabel problems, see # https://github.com/nipy/nibabel/issues/619 img._affine = img.header.get_affine() # or could use None nibabel.save(img, fname_to) def _scale_xfm(subject_to, xfm_fname, mri_name, subject_from, scale, subjects_dir): """Scale a transform.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # The nibabel warning should already be there in MRI step, if applicable, # as we only get here if T1.mgz is present (and thus a scaling was # attempted) so we can silently return here. if not has_nibabel(): return fname_from = os.path.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_from), xfm_fname) fname_to = op.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_to), xfm_fname) assert op.isfile(fname_from), fname_from assert op.isdir(op.dirname(fname_to)), op.dirname(fname_to) # The "talairach.xfm" file stores the ras_mni transform. # # For "from" subj F, "to" subj T, F->T scaling S, some equivalent vertex # positions F_x and T_x in MRI (Freesurfer RAS) coords, knowing that # we have T_x = S @ F_x, we want to have the same MNI coords computed # for these vertices: # # T_mri_mni @ T_x = F_mri_mni @ F_x # # We need to find the correct T_ras_mni (talaraich.xfm file) that yields # this. So we derive (where † indicates inversion): # # T_mri_mni @ S @ F_x = F_mri_mni @ F_x # T_mri_mni @ S = F_mri_mni # T_ras_mni @ T_mri_ras @ S = F_ras_mni @ F_mri_ras # T_ras_mni @ T_mri_ras = F_ras_mni @ F_mri_ras @ S⁻¹ # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # prepare the scale (S) transform scale = np.atleast_1d(scale) scale = np.tile(scale, 3) if len(scale) == 1 else scale S = Transform('mri', 'mri', scaling(*scale)) # F_mri->T_mri # # Get the necessary transforms of the "from" subject # xfm, kind = _read_fs_xfm(fname_from) assert kind == 'MNI Transform File', kind _, _, F_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') F_ras_mni = Transform('ras', 'mni_tal', xfm) del xfm # # Get the necessary transforms of the "to" subject # mri_name = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), op.basename(mri_name)) _, _, T_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') T_ras_mri = invert_transform(T_mri_ras) del mri_name, T_mri_ras # Finally we construct as above: # # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # By moving right to left through the equation. T_ras_mni = \ combine_transforms( combine_transforms( combine_transforms( T_ras_mri, invert_transform(S), 'ras', 'mri'), F_mri_ras, 'ras', 'ras'), F_ras_mni, 'ras', 'mni_tal') _write_fs_xfm(fname_to, T_ras_mni['trans'], kind) @verbose def get_mni_fiducials(subject, subjects_dir=None, verbose=None): """Estimate fiducials for a subject. Parameters ---------- %(subject)s %(subjects_dir)s %(verbose)s Returns ------- fids_mri : list List of estimated fiducials (each point in a dict), in the order LPA, nasion, RPA. Notes ----- This takes the ``fsaverage-fiducials.fif`` file included with MNE—which contain the LPA, nasion, and RPA for the ``fsaverage`` subject—and transforms them to the given FreeSurfer subject's MRI space. The MRI of ``fsaverage`` is already in MNI Talairach space, so applying the inverse of the given subject's MNI Talairach affine transformation (``$SUBJECTS_DIR/$SUBJECT/mri/transforms/talairach.xfm``) is used to estimate the subject's fiducial locations. For more details about the coordinate systems and transformations involved, see https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems and :ref:`plot_source_alignment`. """ # Eventually we might want to allow using the MNI Talairach with-skull # transformation rather than the standard brain-based MNI Talaranch # transformation, and/or project the points onto the head surface # (if available). fname_fids_fs = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage', 'fsaverage-fiducials.fif') # Read fsaverage fiducials file and subject Talairach. fids, coord_frame = read_fiducials(fname_fids_fs) assert coord_frame == FIFF.FIFFV_COORD_MRI if subject == 'fsaverage': return fids # special short-circuit for fsaverage mni_mri_t = invert_transform(read_talxfm(subject, subjects_dir)) for f in fids: f['r'] = apply_trans(mni_mri_t, f['r']) return fids
salv-orlando/MyRepo
refs/heads/bp/xenapi-security-groups
nova/api/openstack/contrib/security_groups.py
1
# Copyright 2011 OpenStack LLC. # 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. """The security groups extension.""" import netaddr import urllib from webob import exc import webob from nova import compute from nova import db from nova import exception from nova import flags from nova import log as logging from nova import rpc from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.compute import power_state from xml.dom import minidom LOG = logging.getLogger("nova.api.contrib.security_groups") FLAGS = flags.FLAGS class SecurityGroupController(object): """The Security group API controller for the OpenStack API.""" def __init__(self): self.compute_api = compute.API() super(SecurityGroupController, self).__init__() def _format_security_group_rule(self, context, rule): sg_rule = {} sg_rule['id'] = rule.id sg_rule['parent_group_id'] = rule.parent_group_id sg_rule['ip_protocol'] = rule.protocol sg_rule['from_port'] = rule.from_port sg_rule['to_port'] = rule.to_port sg_rule['group'] = {} sg_rule['ip_range'] = {} if rule.group_id: source_group = db.security_group_get(context, rule.group_id) sg_rule['group'] = {'name': source_group.name, 'tenant_id': source_group.project_id} else: sg_rule['ip_range'] = {'cidr': rule.cidr} return sg_rule def _format_security_group(self, context, group): security_group = {} security_group['id'] = group.id security_group['description'] = group.description security_group['name'] = group.name security_group['tenant_id'] = group.project_id security_group['rules'] = [] for rule in group.rules: security_group['rules'] += [self._format_security_group_rule( context, rule)] return security_group def _get_security_group(self, context, id): try: id = int(id) security_group = db.security_group_get(context, id) except ValueError: msg = _("Security group id should be integer") raise exc.HTTPBadRequest(explanation=msg) except exception.NotFound as exp: raise exc.HTTPNotFound(explanation=unicode(exp)) return security_group def show(self, req, id): """Return data about the given security group.""" context = req.environ['nova.context'] security_group = self._get_security_group(context, id) return {'security_group': self._format_security_group(context, security_group)} def delete(self, req, id): """Delete a security group.""" context = req.environ['nova.context'] security_group = self._get_security_group(context, id) LOG.audit(_("Delete security group %s"), id, context=context) db.security_group_destroy(context, security_group.id) return webob.Response(status_int=202) def index(self, req): """Returns a list of security groups""" context = req.environ['nova.context'] self.compute_api.ensure_default_security_group(context) groups = db.security_group_get_by_project(context, context.project_id) limited_list = common.limited(groups, req) result = [self._format_security_group(context, group) for group in limited_list] return {'security_groups': list(sorted(result, key=lambda k: (k['tenant_id'], k['name'])))} def create(self, req, body): """Creates a new security group.""" context = req.environ['nova.context'] if not body: raise exc.HTTPUnprocessableEntity() security_group = body.get('security_group', None) if security_group is None: raise exc.HTTPUnprocessableEntity() group_name = security_group.get('name', None) group_description = security_group.get('description', None) self._validate_security_group_property(group_name, "name") self._validate_security_group_property(group_description, "description") group_name = group_name.strip() group_description = group_description.strip() LOG.audit(_("Create Security Group %s"), group_name, context=context) self.compute_api.ensure_default_security_group(context) if db.security_group_exists(context, context.project_id, group_name): msg = _('Security group %s already exists') % group_name raise exc.HTTPBadRequest(explanation=msg) group = {'user_id': context.user_id, 'project_id': context.project_id, 'name': group_name, 'description': group_description} group_ref = db.security_group_create(context, group) return {'security_group': self._format_security_group(context, group_ref)} def _validate_security_group_property(self, value, typ): """ typ will be either 'name' or 'description', depending on the caller """ try: val = value.strip() except AttributeError: msg = _("Security group %s is not a string or unicode") % typ raise exc.HTTPBadRequest(explanation=msg) if not val: msg = _("Security group %s cannot be empty.") % typ raise exc.HTTPBadRequest(explanation=msg) if len(val) > 255: msg = _("Security group %s should not be greater " "than 255 characters.") % typ raise exc.HTTPBadRequest(explanation=msg) class SecurityGroupRulesController(SecurityGroupController): def create(self, req, body): context = req.environ['nova.context'] if not body: raise exc.HTTPUnprocessableEntity() if not 'security_group_rule' in body: raise exc.HTTPUnprocessableEntity() self.compute_api.ensure_default_security_group(context) sg_rule = body['security_group_rule'] parent_group_id = sg_rule.get('parent_group_id', None) try: parent_group_id = int(parent_group_id) security_group = db.security_group_get(context, parent_group_id) except ValueError: msg = _("Parent group id is not integer") raise exc.HTTPBadRequest(explanation=msg) except exception.NotFound as exp: msg = _("Security group (%s) not found") % parent_group_id raise exc.HTTPNotFound(explanation=msg) msg = _("Authorize security group ingress %s") LOG.audit(msg, security_group['name'], context=context) try: values = self._rule_args_to_dict(context, to_port=sg_rule.get('to_port'), from_port=sg_rule.get('from_port'), parent_group_id=sg_rule.get('parent_group_id'), ip_protocol=sg_rule.get('ip_protocol'), cidr=sg_rule.get('cidr'), group_id=sg_rule.get('group_id')) except Exception as exp: raise exc.HTTPBadRequest(explanation=unicode(exp)) if values is None: msg = _("Not enough parameters to build a " "valid rule.") raise exc.HTTPBadRequest(explanation=msg) values['parent_group_id'] = security_group.id if self._security_group_rule_exists(security_group, values): msg = _('This rule already exists in group %s') % parent_group_id raise exc.HTTPBadRequest(explanation=msg) security_group_rule = db.security_group_rule_create(context, values) self.compute_api.trigger_security_group_rules_refresh(context, security_group_id=security_group['id']) return {"security_group_rule": self._format_security_group_rule( context, security_group_rule)} def _security_group_rule_exists(self, security_group, values): """Indicates whether the specified rule values are already defined in the given security group. """ for rule in security_group.rules: if 'group_id' in values: if rule['group_id'] == values['group_id']: return True else: is_duplicate = True for key in ('cidr', 'from_port', 'to_port', 'protocol'): if rule[key] != values[key]: is_duplicate = False break if is_duplicate: return True return False def _rule_args_to_dict(self, context, to_port=None, from_port=None, parent_group_id=None, ip_protocol=None, cidr=None, group_id=None): values = {} if group_id is not None: try: parent_group_id = int(parent_group_id) group_id = int(group_id) except ValueError: msg = _("Parent or group id is not integer") raise exception.InvalidInput(reason=msg) if parent_group_id == group_id: msg = _("Parent group id and group id cannot be same") raise exception.InvalidInput(reason=msg) values['group_id'] = group_id #check if groupId exists db.security_group_get(context, group_id) elif cidr: # If this fails, it throws an exception. This is what we want. try: cidr = urllib.unquote(cidr).decode() netaddr.IPNetwork(cidr) except Exception: raise exception.InvalidCidr(cidr=cidr) values['cidr'] = cidr else: values['cidr'] = '0.0.0.0/0' if ip_protocol and from_port and to_port: try: from_port = int(from_port) to_port = int(to_port) except ValueError: raise exception.InvalidPortRange(from_port=from_port, to_port=to_port) ip_protocol = str(ip_protocol) if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']: raise exception.InvalidIpProtocol(protocol=ip_protocol) if ((min(from_port, to_port) < -1) or (max(from_port, to_port) > 65535)): raise exception.InvalidPortRange(from_port=from_port, to_port=to_port) values['protocol'] = ip_protocol values['from_port'] = from_port values['to_port'] = to_port else: # If cidr based filtering, protocol and ports are mandatory if 'cidr' in values: return None return values def delete(self, req, id): context = req.environ['nova.context'] self.compute_api.ensure_default_security_group(context) try: id = int(id) rule = db.security_group_rule_get(context, id) except ValueError: msg = _("Rule id is not integer") raise exc.HTTPBadRequest(explanation=msg) except exception.NotFound as exp: msg = _("Rule (%s) not found") % id raise exc.HTTPNotFound(explanation=msg) group_id = rule.parent_group_id self.compute_api.ensure_default_security_group(context) security_group = db.security_group_get(context, group_id) msg = _("Revoke security group ingress %s") LOG.audit(msg, security_group['name'], context=context) db.security_group_rule_destroy(context, rule['id']) self.compute_api.trigger_security_group_rules_refresh(context, security_group_id=security_group['id']) return webob.Response(status_int=202) class Security_groups(extensions.ExtensionDescriptor): """Security group support""" name = "SecurityGroups" alias = "security_groups" namespace = "http://docs.openstack.org/ext/securitygroups/api/v1.1" updated = "2011-07-21T00:00:00+00:00" def __init__(self, ext_mgr): self.compute_api = compute.API() super(Security_groups, self).__init__(ext_mgr) def _addSecurityGroup(self, input_dict, req, instance_id): context = req.environ['nova.context'] try: body = input_dict['addSecurityGroup'] group_name = body['name'] except TypeError: msg = _("Missing parameter dict") raise webob.exc.HTTPBadRequest(explanation=msg) except KeyError: msg = _("Security group not specified") raise webob.exc.HTTPBadRequest(explanation=msg) if not group_name or group_name.strip() == '': msg = _("Security group name cannot be empty") raise webob.exc.HTTPBadRequest(explanation=msg) try: self.compute_api.add_security_group(context, instance_id, group_name) except exception.SecurityGroupNotFound as exp: raise exc.HTTPNotFound(explanation=unicode(exp)) except exception.InstanceNotFound as exp: raise exc.HTTPNotFound(explanation=unicode(exp)) except exception.Invalid as exp: raise exc.HTTPBadRequest(explanation=unicode(exp)) return webob.Response(status_int=202) def _removeSecurityGroup(self, input_dict, req, instance_id): context = req.environ['nova.context'] try: body = input_dict['removeSecurityGroup'] group_name = body['name'] except TypeError: msg = _("Missing parameter dict") raise webob.exc.HTTPBadRequest(explanation=msg) except KeyError: msg = _("Security group not specified") raise webob.exc.HTTPBadRequest(explanation=msg) if not group_name or group_name.strip() == '': msg = _("Security group name cannot be empty") raise webob.exc.HTTPBadRequest(explanation=msg) try: self.compute_api.remove_security_group(context, instance_id, group_name) except exception.SecurityGroupNotFound as exp: raise exc.HTTPNotFound(explanation=unicode(exp)) except exception.InstanceNotFound as exp: raise exc.HTTPNotFound(explanation=unicode(exp)) except exception.Invalid as exp: raise exc.HTTPBadRequest(explanation=unicode(exp)) return webob.Response(status_int=202) def get_actions(self): """Return the actions the extensions adds""" actions = [ extensions.ActionExtension("servers", "addSecurityGroup", self._addSecurityGroup), extensions.ActionExtension("servers", "removeSecurityGroup", self._removeSecurityGroup) ] return actions def get_resources(self): resources = [] metadata = _get_metadata() body_serializers = { 'application/xml': wsgi.XMLDictSerializer(metadata=metadata, xmlns=wsgi.XMLNS_V11), } serializer = wsgi.ResponseSerializer(body_serializers, None) body_deserializers = { 'application/xml': SecurityGroupXMLDeserializer(), } deserializer = wsgi.RequestDeserializer(body_deserializers) res = extensions.ResourceExtension('os-security-groups', controller=SecurityGroupController(), deserializer=deserializer, serializer=serializer) resources.append(res) body_deserializers = { 'application/xml': SecurityGroupRulesXMLDeserializer(), } deserializer = wsgi.RequestDeserializer(body_deserializers) res = extensions.ResourceExtension('os-security-group-rules', controller=SecurityGroupRulesController(), deserializer=deserializer, serializer=serializer) resources.append(res) return resources class SecurityGroupXMLDeserializer(wsgi.MetadataXMLDeserializer): """ Deserializer to handle xml-formatted security group requests. """ def create(self, string): """Deserialize an xml-formatted security group create request""" dom = minidom.parseString(string) security_group = {} sg_node = self.find_first_child_named(dom, 'security_group') if sg_node is not None: if sg_node.hasAttribute('name'): security_group['name'] = sg_node.getAttribute('name') desc_node = self.find_first_child_named(sg_node, "description") if desc_node: security_group['description'] = self.extract_text(desc_node) return {'body': {'security_group': security_group}} class SecurityGroupRulesXMLDeserializer(wsgi.MetadataXMLDeserializer): """ Deserializer to handle xml-formatted security group requests. """ def create(self, string): """Deserialize an xml-formatted security group create request""" dom = minidom.parseString(string) security_group_rule = self._extract_security_group_rule(dom) return {'body': {'security_group_rule': security_group_rule}} def _extract_security_group_rule(self, node): """Marshal the security group rule attribute of a parsed request""" sg_rule = {} sg_rule_node = self.find_first_child_named(node, 'security_group_rule') if sg_rule_node is not None: ip_protocol_node = self.find_first_child_named(sg_rule_node, "ip_protocol") if ip_protocol_node is not None: sg_rule['ip_protocol'] = self.extract_text(ip_protocol_node) from_port_node = self.find_first_child_named(sg_rule_node, "from_port") if from_port_node is not None: sg_rule['from_port'] = self.extract_text(from_port_node) to_port_node = self.find_first_child_named(sg_rule_node, "to_port") if to_port_node is not None: sg_rule['to_port'] = self.extract_text(to_port_node) parent_group_id_node = self.find_first_child_named(sg_rule_node, "parent_group_id") if parent_group_id_node is not None: sg_rule['parent_group_id'] = self.extract_text( parent_group_id_node) group_id_node = self.find_first_child_named(sg_rule_node, "group_id") if group_id_node is not None: sg_rule['group_id'] = self.extract_text(group_id_node) cidr_node = self.find_first_child_named(sg_rule_node, "cidr") if cidr_node is not None: sg_rule['cidr'] = self.extract_text(cidr_node) return sg_rule def _get_metadata(): metadata = { "attributes": { "security_group": ["id", "tenant_id", "name"], "rule": ["id", "parent_group_id"], "security_group_rule": ["id", "parent_group_id"], } } return metadata
YajunQiu/three.js
refs/heads/master
utils/exporters/blender/addons/io_three/exporter/material.py
70
from .. import constants, logger from . import base_classes, utilities, api class Material(base_classes.BaseNode): """Class that wraps material nodes""" def __init__(self, node, parent): logger.debug("Material().__init__(%s)", node) base_classes.BaseNode.__init__(self, node, parent, constants.MATERIAL) self._common_attributes() if self[constants.TYPE] == constants.THREE_PHONG: self._phong_attributes() textures = self.parent.options.get(constants.MAPS) if textures: self._update_maps() def _common_attributes(self): """Parse the common material attributes""" logger.debug('Material()._common_attributes()') dispatch = { constants.PHONG: constants.THREE_PHONG, constants.LAMBERT: constants.THREE_LAMBERT, constants.BASIC: constants.THREE_BASIC } shader_type = api.material.type(self.node) self[constants.TYPE] = dispatch[shader_type] diffuse = api.material.diffuse_color(self.node) self[constants.COLOR] = utilities.rgb2int(diffuse) if self[constants.TYPE] != constants.THREE_BASIC: ambient = api.material.ambient_color(self.node) self[constants.AMBIENT] = utilities.rgb2int(ambient) emissive = api.material.emissive_color(self.node) self[constants.EMISSIVE] = utilities.rgb2int(emissive) vertex_color = api.material.use_vertex_colors(self.node) self[constants.VERTEX_COLORS] = vertex_color self[constants.BLENDING] = api.material.blending(self.node) if api.material.transparent(self.node): self[constants.TRANSPARENT] = True if api.material.double_sided(self.node): self[constants.SIDE] = constants.SIDE_DOUBLE self[constants.DEPTH_TEST] = api.material.depth_test(self.node) self[constants.DEPTH_WRITE] = api.material.depth_write(self.node) def _phong_attributes(self): """Parse phong specific attributes""" logger.debug("Material()._phong_attributes()") specular = api.material.specular_color(self.node) self[constants.SPECULAR] = utilities.rgb2int(specular) self[constants.SHININESS] = api.material.specular_coef(self.node) def _update_maps(self): """Parses maps/textures and updates the textures array with any new nodes found. """ logger.debug("Material()._update_maps()") mapping = ( (api.material.diffuse_map, constants.MAP), (api.material.specular_map, constants.SPECULAR_MAP), (api.material.light_map, constants.LIGHT_MAP) ) for func, key in mapping: map_node = func(self.node) if map_node: logger.info('Found map node %s for %s', map_node, key) tex_inst = self.scene.texture(map_node.name) self[key] = tex_inst[constants.UUID] if self[constants.TYPE] == constants.THREE_PHONG: mapping = ( (api.material.bump_map, constants.BUMP_MAP, constants.BUMP_SCALE, api.material.bump_scale), (api.material.normal_map, constants.NORMAL_MAP, constants.NORMAL_SCALE, api.material.normal_scale) ) for func, map_key, scale_key, scale_func in mapping: map_node = func(self.node) if not map_node: continue logger.info("Found map node %s for %s", map_node, map_key) tex_inst = self.scene.texture(map_node.name) self[map_key] = tex_inst[constants.UUID] self[scale_key] = scale_func(self.node)
bbcf/bsPlugins
refs/heads/master
bsPlugins/MergeTracks.py
1
from bsPlugins import * from bbcflib.gfminer.stream import merge_scores from bbcflib.gfminer.numeric import correlation from bbcflib.track import track, FeatureStream from bbcflib import genrep output_opts = ['sql','bed','bedGraph','wig','bigWig','sga'] method_opts = ['mean','min','max','geometric','median','sum'] meta = {'version': "1.0.0", 'author': "BBCF", 'contact': "webmaster-bbcf@epfl.ch"} in_parameters = [{'id': 'forward', 'type': 'track', 'required': True, 'label': 'Forward: ', 'help_text': 'Select forward density file' }, {'id': 'reverse', 'type': 'track', 'required': True, 'label': 'Reverse: ', 'help_text': 'Select reverse density file' }, {'id': 'assembly', 'type': 'assembly', 'label': 'Assembly: ', 'help_text': 'Reference genome', 'options': genrep.GenRep().assemblies_available()}, {'id': 'shift', 'type': 'int', 'required': True, 'label': 'Shift: ', 'help_text': 'Enter positive downstream shift ([fragment_size-read_length]/2), \nor a negative value to estimate shift by cross-correlation', 'value': 0}, {'id': 'format', 'type': 'listing', 'label': 'Output format: ', 'help_text': 'Format of the output file', 'options': output_opts, 'prompt_text': None}, {'id': 'method', 'type': 'radio', 'label': 'Method: ', 'help_text': 'Select the score combination method', 'options': method_opts, 'value': 'mean'}] out_parameters = [{'id': 'density_merged', 'type': 'track'}] class MergeTracksForm(BaseForm): forward = twb.BsFileField(label='Forward: ', help_text='Select forward density file', validator=twb.BsFileFieldValidator(required=True)) reverse = twb.BsFileField(label='Reverse: ', help_text='Select reverse density file', validator=twb.BsFileFieldValidator(required=True)) assembly = twf.SingleSelectField(label='Assembly: ', options=genrep.GenRep().assemblies_available(), help_text='Reference genome') shift = twf.TextField(label='Shift: ', validator=twc.IntValidator(required=True), value=0, help_text='Enter positive downstream shift ([fragment_size-read_length]/2), \ or a negative value to estimate shift by cross-correlation') format = twf.SingleSelectField(label='Output format: ', options=output_opts, prompt_text=None, help_text='Format of the output file', ) method = twf.RadioButtonList(label='Method: ', options=method_opts, value='mean', help_text='Select the score combination method') submit = twf.SubmitButton(id="submit", value='Merge tracks') class MergeTracksPlugin(BasePlugin): """Shift and average scores from forward and reverse strand densities. Typically built to merge ChIP-seq signals from both DNA strands, it can also be used to add (average) several numeric genomic tracks, replicates for instance. The output is the average of all the input signals, position by position. """ info = { 'title': 'Merge strands', 'description': __doc__, 'path': ['Signal', 'Merge strands'], # 'output': MergeTracksForm, 'in': in_parameters, 'out': out_parameters, 'meta': meta, } def __call__(self, **kw): def _shift(stream, shift): istart = stream.fields.index('start') iend = stream.fields.index('end') i1 = min(istart, iend) i2 = max(istart, iend) def _apply_shift(x): return x[:i1] + (x[i1] + shift,) + x[i1 + 1:i2] + (x[i2] + shift,) + x[i2 + 1:] return FeatureStream((_apply_shift(x) for x in stream), fields=stream.fields) assembly = kw.get('assembly') or 'guess' tfwd = track(kw.get('forward'), chrmeta=assembly) trev = track(kw.get('reverse'), chrmeta=assembly) chrmeta = tfwd.chrmeta shiftval = int(kw.get('shift', 0)) if shiftval < 0: # Determine shift automatically shiftval = None xcor_lim = 300 for chrom, v in chrmeta.iteritems(): chrsize = v['length'] xcor_lim = min(xcor_lim, 0.01 * chrsize) xcor = correlation([tfwd.read(chrom), trev.read(chrom)], regions=(1, chrsize), limits=(-xcor_lim, xcor_lim)) max_xcor_idx = xcor.argmax() if xcor[max_xcor_idx] > 0.2: shiftval = (max_xcor_idx - xcor_lim - 1)/2 break if not shiftval: raise ValueError("Unable to detect shift automatically. Must specify a shift value.") output = self.temporary_path(fname=tfwd.name+'-'+trev.name+'_merged', ext=kw.get('format',tfwd.format)) outfields = [f for f in tfwd.fields if f in trev.fields] tout = track(output, chrmeta=chrmeta, fields=outfields, info={'datatype': 'quantitative', 'shift': shiftval}) mode = 'write' method = kw.get("method","mean") for chrom in chrmeta.keys(): tout.write(merge_scores([_shift(tfwd.read(selection=chrom), shiftval), _shift(trev.read(selection=chrom), -shiftval)], method=method), chrom=chrom, mode=mode, clip=True) mode = 'append' tout.close() trev.close() tfwd.close() self.new_file(output, 'density_merged') return self.display_time() # nosetests --logging-filter=-tw2 test_MergeTracks.py
apelliciari/django-registration-from-bitbucket
refs/heads/master
registration/tests/urls.py
138
""" URLs used in the unit tests for django-registration. You should not attempt to use these URLs in any sort of real or development environment; instead, use ``registration/backends/default/urls.py``. This URLconf includes those URLs, and also adds several additional URLs which serve no purpose other than to test that optional keyword arguments are properly handled. """ from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from registration.views import activate from registration.views import register urlpatterns = patterns('', # Test the 'activate' view with custom template # name. url(r'^activate-with-template-name/(?P<activation_key>\w+)/$', activate, {'template_name': 'registration/test_template_name.html', 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_activate_template_name'), # Test the 'activate' view with # extra_context_argument. url(r'^activate-extra-context/(?P<activation_key>\w+)/$', activate, {'extra_context': {'foo': 'bar', 'callable': lambda: 'called'}, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_activate_extra_context'), # Test the 'activate' view with success_url argument. url(r'^activate-with-success-url/(?P<activation_key>\w+)/$', activate, {'success_url': 'registration_test_custom_success_url', 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_activate_success_url'), # Test the 'register' view with custom template # name. url(r'^register-with-template-name/$', register, {'template_name': 'registration/test_template_name.html', 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_register_template_name'), # Test the'register' view with extra_context # argument. url(r'^register-extra-context/$', register, {'extra_context': {'foo': 'bar', 'callable': lambda: 'called'}, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_register_extra_context'), # Test the 'register' view with custom URL for # closed registration. url(r'^register-with-disallowed-url/$', register, {'disallowed_url': 'registration_test_custom_disallowed', 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_register_disallowed_url'), # Set up a pattern which will correspond to the # custom 'disallowed_url' above. url(r'^custom-disallowed/$', direct_to_template, {'template': 'registration/registration_closed.html'}, name='registration_test_custom_disallowed'), # Test the 'register' view with custom redirect # on successful registration. url(r'^register-with-success_url/$', register, {'success_url': 'registration_test_custom_success_url', 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_test_register_success_url' ), # Pattern for custom redirect set above. url(r'^custom-success/$', direct_to_template, {'template': 'registration/test_template_name.html'}, name='registration_test_custom_success_url'), (r'', include('registration.backends.default.urls')), )
facundoq/toys
refs/heads/master
cic-fly/src/cic/Processing.py
1
''' Created on 14/05/2013 @author: facuq ''' from numpy import * import os; import matplotlib.pyplot as plt from PeakDetector import peakdetect from ImageReader import imsave, ImageReader import itertools from matplotlib.pyplot import figure from Smoothing import savitzky_golay class Peak(object): (Maximum,Minimum) = (0,1) def __init__(self,x,y, type): self.x=x self.y=y self.type= type class Peaks(object): def __init__(self,x,y,minimum_dy): _max,_min = peakdetect(y, x, 10, minimum_dy) self.min=_min self.max=_max def x_min(self): return [p[0] for p in self.min] def y_min(self): return [p[1] for p in self.min] def x_max(self): return [p[0] for p in self.max] def y_max(self): return [p[1] for p in self.max] def detect(self,y,x): pass def all_in_one(self): minimum= map(lambda p: Peak(p[0],p[1], Peak.Minimum),self.min) maximum= map(lambda p: Peak(p[0],p[1], Peak.Maximum),self.max) return sorted(minimum+maximum,key= lambda p: p.x) class ProcessingResult(object): def __init__(self,options,image_count, using_white,combined_image,f,smooth_f, peaks,t_half,f_mean,f0): self.f=f self.f0=f0 self.smooth_f= smooth_f self.combined_image=combined_image self.options=options self.peaks=peaks self.t_half=t_half self.f_mean=f_mean self.using_white= using_white self.image_count= image_count def output_name(self): return "output-duration-%d.txt" % (self.options.duration) class ProcessingArea(object): def __init__(self,start,end,background_start,background_end): self.start=start self.end=end self.background_start=background_start self.background_end=background_end class ProcessingOptions(object): def __init__(self,duration,area,minimum_dy, window_size, order): self.duration=duration self.area=area self.minimum_dy=minimum_dy self.window_size= window_size self.order= order class Processor(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' def process(self,options,combined_images, images, white): result=self.extract_information(combined_images,len(images), white!= None, options) return result def preprocess(self, folder_path): images,white= ImageReader().read_all(folder_path) if white!= None: images=self.remove_white(images,white) return (self.combine_images(images), images, white) def remove_white(self, images, white): for i in images: i=i-white return images def combine_images(self, images): return concatenate(images,axis=1) def smooth(self,y,window_size, order): if (window_size<=1 or order>= window_size): return y if window_size %2==0: window_size+=1 return savitzky_golay(y, window_size=window_size, order=order) def extract_information(self, combined_images,image_count, using_white, options): data_points,f0= self.extract_data_points(combined_images,options) time=linspace(0,options.duration,len(data_points)) smooth_data_points= self.smooth(data_points, options.window_size, options.order) f= array([time,data_points]) smooth_f=array([time,smooth_data_points]) peaks=Peaks(time,smooth_data_points, options.minimum_dy) mean_f=mean(peaks.y_max()) t_half=self.calculate_t_half(peaks) return ProcessingResult(options,image_count, using_white,combined_images,f,smooth_f,peaks,t_half,mean_f,f0) def extract_data_points(self,combined_images,options): f0=average(combined_images[:options.area.background_start,:,:]) f0+= average(combined_images[options.area.background_end:,:,:]) data = combined_images[options.area.start:options.area.end,:,:] avg_data=average(data, (2)) avg_data=average(avg_data, (0)) avg_data-=f0 return (avg_data,f0) def save_output(self,result, folder_path): folder_path+= "/result" if not os.path.exists(folder_path): os.mkdir(folder_path) #path=os.path.join(folder_path,result.output_name()) path= folder_path+ "/"+result.output_name() savetxt(path, transpose(result.f), "%10.3f", ",",'\n') path= folder_path+ "/"+'total.png' #path=os.path.join(folder_path,'total.png') imsave(path,result.combined_image) def calculate_t_half (self,peaks): all= peaks.all_in_one() all=list(itertools.dropwhile(lambda p: p.type== Peak.Minimum,all)) result=[] i=0 while i<len(all): maximum=None minimum=None while i<len(all) and all[i].type== Peak.Maximum: if maximum==None or all[i].y> maximum.y: maximum=all[i] i+=1 while i<len(all) and all[i].type== Peak.Minimum : if minimum==None or all[i].y< minimum.y: minimum=all[i] i+=1 if maximum!= None and minimum!= None: result+= [minimum.x- maximum.x] return mean(result) def plot_image(image): figure() plt.imshow(image) plt.show() def plot_peaks(result): figure() x,y=(result.f[0,:],result.f[1,:]) plt.plot(x,y) peaks= result.peaks xm = peaks.x_max() ym = peaks.y_max() xn = peaks.x_min() yn = peaks.y_min() plt.plot(xm, ym, 'r+') plt.plot(xn, yn, 'g+') plt.show() def main(): folder_path='C:\\Users\\facuq\\Desktop\\img\\test' p=Processor() combined_images, images, white= p.preprocess(folder_path) plot_image(combined_images) options= ProcessingOptions(len (images)*5.2,ProcessingArea(280, 290),10,0.3) result=p.process(options,combined_images, images, white) p.save_output(result, folder_path) plot_peaks(result) print "f %f - T12 %f" % (result.f_mean, result.t_half) if __name__ == '__main__': main()
infectedmushi/kernel-sony-copyleft
refs/heads/39.2.A.0.xxx
tools/perf/scripts/python/netdev-times.py
1544
# Display a process of packets and processed time. # It helps us to investigate networking or network device. # # options # tx: show only tx chart # rx: show only rx chart # dev=: show only thing related to specified device # debug: work with debug mode. It shows buffer status. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * all_event_list = []; # insert all tracepoint event related with this script irq_dic = {}; # key is cpu and value is a list which stacks irqs # which raise NET_RX softirq net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry # and a list which stacks receive receive_hunk_list = []; # a list which include a sequence of receive events rx_skb_list = []; # received packet list for matching # skb_copy_datagram_iovec buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and # tx_xmit_list of_count_rx_skb_list = 0; # overflow count tx_queue_list = []; # list of packets which pass through dev_queue_xmit of_count_tx_queue_list = 0; # overflow count tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit of_count_tx_xmit_list = 0; # overflow count tx_free_list = []; # list of packets which is freed # options show_tx = 0; show_rx = 0; dev = 0; # store a name of device specified by option "dev=" debug = 0; # indices of event_info tuple EINFO_IDX_NAME= 0 EINFO_IDX_CONTEXT=1 EINFO_IDX_CPU= 2 EINFO_IDX_TIME= 3 EINFO_IDX_PID= 4 EINFO_IDX_COMM= 5 # Calculate a time interval(msec) from src(nsec) to dst(nsec) def diff_msec(src, dst): return (dst - src) / 1000000.0 # Display a process of transmitting a packet def print_transmit(hunk): if dev != 0 and hunk['dev'].find(dev) < 0: return print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \ (hunk['dev'], hunk['len'], nsecs_secs(hunk['queue_t']), nsecs_nsecs(hunk['queue_t'])/1000, diff_msec(hunk['queue_t'], hunk['xmit_t']), diff_msec(hunk['xmit_t'], hunk['free_t'])) # Format for displaying rx packet processing PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)" PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)" PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)" PF_JOINT= " |" PF_WJOINT= " | |" PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)" PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)" PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)" PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)" PF_CONS_SKB= " | consume_skb(+%.3fmsec)" # Display a process of received packets and interrputs associated with # a NET_RX softirq def print_receive(hunk): show_hunk = 0 irq_list = hunk['irq_list'] cpu = irq_list[0]['cpu'] base_t = irq_list[0]['irq_ent_t'] # check if this hunk should be showed if dev != 0: for i in range(len(irq_list)): if irq_list[i]['name'].find(dev) >= 0: show_hunk = 1 break else: show_hunk = 1 if show_hunk == 0: return print "%d.%06dsec cpu=%d" % \ (nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu) for i in range(len(irq_list)): print PF_IRQ_ENTRY % \ (diff_msec(base_t, irq_list[i]['irq_ent_t']), irq_list[i]['irq'], irq_list[i]['name']) print PF_JOINT irq_event_list = irq_list[i]['event_list'] for j in range(len(irq_event_list)): irq_event = irq_event_list[j] if irq_event['event'] == 'netif_rx': print PF_NET_RX % \ (diff_msec(base_t, irq_event['time']), irq_event['skbaddr']) print PF_JOINT print PF_SOFT_ENTRY % \ diff_msec(base_t, hunk['sirq_ent_t']) print PF_JOINT event_list = hunk['event_list'] for i in range(len(event_list)): event = event_list[i] if event['event_name'] == 'napi_poll': print PF_NAPI_POLL % \ (diff_msec(base_t, event['event_t']), event['dev']) if i == len(event_list) - 1: print "" else: print PF_JOINT else: print PF_NET_RECV % \ (diff_msec(base_t, event['event_t']), event['skbaddr'], event['len']) if 'comm' in event.keys(): print PF_WJOINT print PF_CPY_DGRAM % \ (diff_msec(base_t, event['comm_t']), event['pid'], event['comm']) elif 'handle' in event.keys(): print PF_WJOINT if event['handle'] == "kfree_skb": print PF_KFREE_SKB % \ (diff_msec(base_t, event['comm_t']), event['location']) elif event['handle'] == "consume_skb": print PF_CONS_SKB % \ diff_msec(base_t, event['comm_t']) print PF_JOINT def trace_begin(): global show_tx global show_rx global dev global debug for i in range(len(sys.argv)): if i == 0: continue arg = sys.argv[i] if arg == 'tx': show_tx = 1 elif arg =='rx': show_rx = 1 elif arg.find('dev=',0, 4) >= 0: dev = arg[4:] elif arg == 'debug': debug = 1 if show_tx == 0 and show_rx == 0: show_tx = 1 show_rx = 1 def trace_end(): # order all events in time all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME], b[EINFO_IDX_TIME])) # process all events for i in range(len(all_event_list)): event_info = all_event_list[i] name = event_info[EINFO_IDX_NAME] if name == 'irq__softirq_exit': handle_irq_softirq_exit(event_info) elif name == 'irq__softirq_entry': handle_irq_softirq_entry(event_info) elif name == 'irq__softirq_raise': handle_irq_softirq_raise(event_info) elif name == 'irq__irq_handler_entry': handle_irq_handler_entry(event_info) elif name == 'irq__irq_handler_exit': handle_irq_handler_exit(event_info) elif name == 'napi__napi_poll': handle_napi_poll(event_info) elif name == 'net__netif_receive_skb': handle_netif_receive_skb(event_info) elif name == 'net__netif_rx': handle_netif_rx(event_info) elif name == 'skb__skb_copy_datagram_iovec': handle_skb_copy_datagram_iovec(event_info) elif name == 'net__net_dev_queue': handle_net_dev_queue(event_info) elif name == 'net__net_dev_xmit': handle_net_dev_xmit(event_info) elif name == 'skb__kfree_skb': handle_kfree_skb(event_info) elif name == 'skb__consume_skb': handle_consume_skb(event_info) # display receive hunks if show_rx: for i in range(len(receive_hunk_list)): print_receive(receive_hunk_list[i]) # display transmit hunks if show_tx: print " dev len Qdisc " \ " netdevice free" for i in range(len(tx_free_list)): print_transmit(tx_free_list[i]) if debug: print "debug buffer status" print "----------------------------" print "xmit Qdisc:remain:%d overflow:%d" % \ (len(tx_queue_list), of_count_tx_queue_list) print "xmit netdevice:remain:%d overflow:%d" % \ (len(tx_xmit_list), of_count_tx_xmit_list) print "receive:remain:%d overflow:%d" % \ (len(rx_skb_list), of_count_rx_skb_list) # called from perf, when it finds a correspoinding event def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, callchain, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, callchain, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, callchain, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm, callchain, irq, irq_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, irq_name) all_event_list.append(event_info) def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, callchain, irq, ret): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret) all_event_list.append(event_info) def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, callchain, napi, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, napi, dev_name) all_event_list.append(event_info) def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, skblen, rc, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, rc ,dev_name) all_event_list.append(event_info) def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, protocol, location): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, protocol, location) all_event_list.append(event_info) def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr) all_event_list.append(event_info) def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm, callchain, skbaddr, skblen): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen) all_event_list.append(event_info) def handle_irq_handler_entry(event_info): (name, context, cpu, time, pid, comm, irq, irq_name) = event_info if cpu not in irq_dic.keys(): irq_dic[cpu] = [] irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time} irq_dic[cpu].append(irq_record) def handle_irq_handler_exit(event_info): (name, context, cpu, time, pid, comm, irq, ret) = event_info if cpu not in irq_dic.keys(): return irq_record = irq_dic[cpu].pop() if irq != irq_record['irq']: return irq_record.update({'irq_ext_t':time}) # if an irq doesn't include NET_RX softirq, drop. if 'event_list' in irq_record.keys(): irq_dic[cpu].append(irq_record) def handle_irq_softirq_raise(event_info): (name, context, cpu, time, pid, comm, vec) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'sirq_raise'}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_irq_softirq_entry(event_info): (name, context, cpu, time, pid, comm, vec) = event_info net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]} def handle_irq_softirq_exit(event_info): (name, context, cpu, time, pid, comm, vec) = event_info irq_list = [] event_list = 0 if cpu in irq_dic.keys(): irq_list = irq_dic[cpu] del irq_dic[cpu] if cpu in net_rx_dic.keys(): sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t'] event_list = net_rx_dic[cpu]['event_list'] del net_rx_dic[cpu] if irq_list == [] or event_list == 0: return rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time, 'irq_list':irq_list, 'event_list':event_list} # merge information realted to a NET_RX softirq receive_hunk_list.append(rec_data) def handle_napi_poll(event_info): (name, context, cpu, time, pid, comm, napi, dev_name) = event_info if cpu in net_rx_dic.keys(): event_list = net_rx_dic[cpu]['event_list'] rec_data = {'event_name':'napi_poll', 'dev':dev_name, 'event_t':time} event_list.append(rec_data) def handle_netif_rx(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'netif_rx', 'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_netif_receive_skb(event_info): global of_count_rx_skb_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu in net_rx_dic.keys(): rec_data = {'event_name':'netif_receive_skb', 'event_t':time, 'skbaddr':skbaddr, 'len':skblen} event_list = net_rx_dic[cpu]['event_list'] event_list.append(rec_data) rx_skb_list.insert(0, rec_data) if len(rx_skb_list) > buffer_budget: rx_skb_list.pop() of_count_rx_skb_list += 1 def handle_net_dev_queue(event_info): global of_count_tx_queue_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time} tx_queue_list.insert(0, skb) if len(tx_queue_list) > buffer_budget: tx_queue_list.pop() of_count_tx_queue_list += 1 def handle_net_dev_xmit(event_info): global of_count_tx_xmit_list (name, context, cpu, time, pid, comm, skbaddr, skblen, rc, dev_name) = event_info if rc == 0: # NETDEV_TX_OK for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: skb['xmit_t'] = time tx_xmit_list.insert(0, skb) del tx_queue_list[i] if len(tx_xmit_list) > buffer_budget: tx_xmit_list.pop() of_count_tx_xmit_list += 1 return def handle_kfree_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr, protocol, location) = event_info for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: del tx_queue_list[i] return for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if rec_data['skbaddr'] == skbaddr: rec_data.update({'handle':"kfree_skb", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return def handle_consume_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr) = event_info for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return def handle_skb_copy_datagram_iovec(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if skbaddr == rec_data['skbaddr']: rec_data.update({'handle':"skb_copy_datagram_iovec", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return
dfalt974/SickRage
refs/heads/master
lib/future/backports/socket.py
68
# Wrapper module for _socket, providing some additional facilities # implemented in Python. """\ This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. Functions: socket() -- create a new socket object socketpair() -- create a pair of new socket objects [*] fromfd() -- create a socket object from an open file descriptor [*] fromshare() -- create a socket object from data received from socket.share() [*] gethostname() -- return the current hostname gethostbyname() -- map a hostname to its IP number gethostbyaddr() -- map an IP number or hostname to DNS info getservbyname() -- map a service name and a protocol name to a port number getprotobyname() -- map a protocol name (e.g. 'tcp') to a number ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order htons(), htonl() -- convert 16, 32 bit int from host to network byte order inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) socket.getdefaulttimeout() -- get the default timeout value socket.setdefaulttimeout() -- set the default timeout value create_connection() -- connects to an address, with an optional timeout and optional source address. [*] not available on all platforms! Special objects: SocketType -- type object for socket objects error -- exception raised for I/O errors has_ipv6 -- boolean value indicating if IPv6 is supported Integer constants: AF_INET, AF_UNIX -- socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods. """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future.builtins import super import _socket from _socket import * import os, sys, io try: import errno except ImportError: errno = None EBADF = getattr(errno, 'EBADF', 9) EAGAIN = getattr(errno, 'EAGAIN', 11) EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) __all__ = ["getfqdn", "create_connection"] __all__.extend(os._get_exports_list(_socket)) _realsocket = socket # WSA error codes if sys.platform.lower().startswith("win"): errorTab = {} errorTab[10004] = "The operation was interrupted." errorTab[10009] = "A bad file handle was passed." errorTab[10013] = "Permission denied." errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT errorTab[10022] = "An invalid operation was attempted." errorTab[10035] = "The socket operation would block" errorTab[10036] = "A blocking operation is already in progress." errorTab[10048] = "The network address is in use." errorTab[10054] = "The connection has been reset." errorTab[10058] = "The network has been shut down." errorTab[10060] = "The operation timed out." errorTab[10061] = "Connection refused." errorTab[10063] = "The name is too long." errorTab[10064] = "The host is down." errorTab[10065] = "The host is unreachable." __all__.append("errorTab") class socket(_socket.socket): """A subclass of _socket.socket adding the makefile() method.""" __slots__ = ["__weakref__", "_io_refs", "_closed"] def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): if fileno is None: _socket.socket.__init__(self, family, type, proto) else: _socket.socket.__init__(self, family, type, proto, fileno) self._io_refs = 0 self._closed = False def __enter__(self): return self def __exit__(self, *args): if not self._closed: self.close() def __repr__(self): """Wrap __repr__() to reveal the real class name.""" s = _socket.socket.__repr__(self) if s.startswith("<socket object"): s = "<%s.%s%s%s" % (self.__class__.__module__, self.__class__.__name__, getattr(self, '_closed', False) and " [closed] " or "", s[7:]) return s def __getstate__(self): raise TypeError("Cannot serialize socket object") def dup(self): """dup() -> socket object Return a new socket object connected to the same system resource. """ fd = dup(self.fileno()) sock = self.__class__(self.family, self.type, self.proto, fileno=fd) sock.settimeout(self.gettimeout()) return sock def accept(self): """accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). """ fd, addr = self._accept() sock = socket(self.family, self.type, self.proto, fileno=fd) # Issue #7995: if no default timeout is set and the listening # socket had a (non-zero) timeout, force the new socket in blocking # mode to override platform-specific socket flags inheritance. if getdefaulttimeout() is None and self.gettimeout(): sock.setblocking(True) return sock, addr def makefile(self, mode="r", buffering=None, **_3to2kwargs): """makefile(...) -> an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only mode characters supported are 'r', 'w' and 'b'. The semantics are similar too. (XXX refactor to share code?) """ if 'newline' in _3to2kwargs: newline = _3to2kwargs['newline']; del _3to2kwargs['newline'] else: newline = None if 'errors' in _3to2kwargs: errors = _3to2kwargs['errors']; del _3to2kwargs['errors'] else: errors = None if 'encoding' in _3to2kwargs: encoding = _3to2kwargs['encoding']; del _3to2kwargs['encoding'] else: encoding = None for c in mode: if c not in ("r", "w", "b"): raise ValueError("invalid mode %r (only r, w, b allowed)") writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._io_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text def _decref_socketios(self): if self._io_refs > 0: self._io_refs -= 1 if self._closed: self.close() def _real_close(self, _ss=_socket.socket): # This function should not reference any globals. See issue #808164. _ss.close(self) def close(self): # This function should not reference any globals. See issue #808164. self._closed = True if self._io_refs <= 0: self._real_close() def detach(self): """detach() -> file descriptor Close the socket object without closing the underlying file descriptor. The object cannot be used after this call, but the file descriptor can be reused for other purposes. The file descriptor is returned. """ self._closed = True return super().detach() def fromfd(fd, family, type, proto=0): """ fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). """ nfd = dup(fd) return socket(family, type, proto, nfd) if hasattr(_socket.socket, "share"): def fromshare(info): """ fromshare(info) -> socket object Create a socket object from a the bytes object returned by socket.share(pid). """ return socket(0, 0, 0, info) if hasattr(_socket, "socketpair"): def socketpair(family=None, type=SOCK_STREAM, proto=0): """socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. """ if family is None: try: family = AF_UNIX except NameError: family = AF_INET a, b = _socket.socketpair(family, type, proto) a = socket(family, type, proto, a.detach()) b = socket(family, type, proto, b.detach()) return a, b _blocking_errnos = set([EAGAIN, EWOULDBLOCK]) class SocketIO(io.RawIOBase): """Raw I/O implementation for stream sockets. This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object. """ # One might wonder why not let FileIO do the job instead. There are two # main reasons why FileIO is not adapted: # - it wouldn't work under Windows (where you can't used read() and # write() on a socket handle) # - it wouldn't work with socket timeouts (FileIO would ignore the # timeout and consider the socket non-blocking) # XXX More docs def __init__(self, sock, mode): if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): raise ValueError("invalid mode: %r" % mode) io.RawIOBase.__init__(self) self._sock = sock if "b" not in mode: mode += "b" self._mode = mode self._reading = "r" in mode self._writing = "w" in mode self._timeout_occurred = False def readinto(self, b): """Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at the other end. """ self._checkClosed() self._checkReadable() if self._timeout_occurred: raise IOError("cannot read from timed out object") while True: try: return self._sock.recv_into(b) except timeout: self._timeout_occurred = True raise # except InterruptedError: # continue except error as e: if e.args[0] in _blocking_errnos: return None raise def write(self, b): """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. """ self._checkClosed() self._checkWritable() try: return self._sock.send(b) except error as e: # XXX what about EINTR? if e.args[0] in _blocking_errnos: return None raise def readable(self): """True if the SocketIO is open for reading. """ if self.closed: raise ValueError("I/O operation on closed socket.") return self._reading def writable(self): """True if the SocketIO is open for writing. """ if self.closed: raise ValueError("I/O operation on closed socket.") return self._writing def seekable(self): """True if the SocketIO is open for seeking. """ if self.closed: raise ValueError("I/O operation on closed socket.") return super().seekable() def fileno(self): """Return the file descriptor of the underlying socket. """ self._checkClosed() return self._sock.fileno() @property def name(self): if not self.closed: return self.fileno() else: return -1 @property def mode(self): return self._mode def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: return io.RawIOBase.close(self) self._sock._decref_socketios() self._sock = None def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name # Re-use the same sentinel as in the Python stdlib socket module: from socket import _GLOBAL_DEFAULT_TIMEOUT # Was: _GLOBAL_DEFAULT_TIMEOUT = object() def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address err = None for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket(af, socktype, proto) if timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except error as _: err = _ if sock is not None: sock.close() if err is not None: raise err else: raise error("getaddrinfo returns an empty list")
ShiYw/Sigil
refs/heads/master
3rdparty/python/Lib/test/test_telnetlib.py
84
import socket import selectors import telnetlib import time import contextlib from unittest import TestCase from test import support threading = support.import_module('threading') HOST = support.HOST def server(evt, serv): serv.listen(5) evt.set() try: conn, addr = serv.accept() conn.close() except socket.timeout: pass finally: serv.close() class GeneralTests(TestCase): def setUp(self): self.evt = threading.Event() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(60) # Safety net. Look issue 11812 self.port = support.bind_port(self.sock) self.thread = threading.Thread(target=server, args=(self.evt,self.sock)) self.thread.setDaemon(True) self.thread.start() self.evt.wait() def tearDown(self): self.thread.join() del self.thread # Clear out any dangling Thread objects. def testBasic(self): # connects telnet = telnetlib.Telnet(HOST, self.port) telnet.sock.close() def testTimeoutDefault(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: telnet = telnetlib.Telnet(HOST, self.port) finally: socket.setdefaulttimeout(None) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() def testTimeoutNone(self): # None, having other default self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: telnet = telnetlib.Telnet(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(None) self.assertTrue(telnet.sock.gettimeout() is None) telnet.sock.close() def testTimeoutValue(self): telnet = telnetlib.Telnet(HOST, self.port, timeout=30) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() def testTimeoutOpen(self): telnet = telnetlib.Telnet() telnet.open(HOST, self.port, timeout=30) self.assertEqual(telnet.sock.gettimeout(), 30) telnet.sock.close() def testGetters(self): # Test telnet getter methods telnet = telnetlib.Telnet(HOST, self.port, timeout=30) t_sock = telnet.sock self.assertEqual(telnet.get_socket(), t_sock) self.assertEqual(telnet.fileno(), t_sock.fileno()) telnet.sock.close() class SocketStub(object): ''' a socket proxy that re-defines sendall() ''' def __init__(self, reads=()): self.reads = list(reads) # Intentionally make a copy. self.writes = [] self.block = False def sendall(self, data): self.writes.append(data) def recv(self, size): out = b'' while self.reads and len(out) < size: out += self.reads.pop(0) if len(out) > size: self.reads.insert(0, out[size:]) out = out[:size] return out class TelnetAlike(telnetlib.Telnet): def fileno(self): raise NotImplementedError() def close(self): pass def sock_avail(self): return (not self.sock.block) def msg(self, msg, *args): with support.captured_stdout() as out: telnetlib.Telnet.msg(self, msg, *args) self._messages += out.getvalue() return class MockSelector(selectors.BaseSelector): def __init__(self): self.keys = {} @property def resolution(self): return 1e-3 def register(self, fileobj, events, data=None): key = selectors.SelectorKey(fileobj, 0, events, data) self.keys[fileobj] = key return key def unregister(self, fileobj): return self.keys.pop(fileobj) def select(self, timeout=None): block = False for fileobj in self.keys: if isinstance(fileobj, TelnetAlike): block = fileobj.sock.block break if block: return [] else: return [(key, key.events) for key in self.keys.values()] def get_map(self): return self.keys @contextlib.contextmanager def test_socket(reads): def new_conn(*ignored): return SocketStub(reads) try: old_conn = socket.create_connection socket.create_connection = new_conn yield None finally: socket.create_connection = old_conn return def test_telnet(reads=(), cls=TelnetAlike): ''' return a telnetlib.Telnet object that uses a SocketStub with reads queued up to be read ''' for x in reads: assert type(x) is bytes, x with test_socket(reads): telnet = cls('dummy', 0) telnet._messages = '' # debuglevel output return telnet class ExpectAndReadTestCase(TestCase): def setUp(self): self.old_selector = telnetlib._TelnetSelector telnetlib._TelnetSelector = MockSelector def tearDown(self): telnetlib._TelnetSelector = self.old_selector class ReadTests(ExpectAndReadTestCase): def test_read_until(self): """ read_until(expected, timeout=None) test the blocking version of read_util """ want = [b'xxxmatchyyy'] telnet = test_telnet(want) data = telnet.read_until(b'match') self.assertEqual(data, b'xxxmatch', msg=(telnet.cookedq, telnet.rawq, telnet.sock.reads)) reads = [b'x' * 50, b'match', b'y' * 50] expect = b''.join(reads[:-1]) telnet = test_telnet(reads) data = telnet.read_until(b'match') self.assertEqual(data, expect) def test_read_all(self): """ read_all() Read all data until EOF; may block. """ reads = [b'x' * 500, b'y' * 500, b'z' * 500] expect = b''.join(reads) telnet = test_telnet(reads) data = telnet.read_all() self.assertEqual(data, expect) return def test_read_some(self): """ read_some() Read at least one byte or EOF; may block. """ # test 'at least one byte' telnet = test_telnet([b'x' * 500]) data = telnet.read_some() self.assertTrue(len(data) >= 1) # test EOF telnet = test_telnet() data = telnet.read_some() self.assertEqual(b'', data) def _read_eager(self, func_name): """ read_*_eager() Read all data available already queued or on the socket, without blocking. """ want = b'x' * 100 telnet = test_telnet([want]) func = getattr(telnet, func_name) telnet.sock.block = True self.assertEqual(b'', func()) telnet.sock.block = False data = b'' while True: try: data += func() except EOFError: break self.assertEqual(data, want) def test_read_eager(self): # read_eager and read_very_eager make the same gaurantees # (they behave differently but we only test the gaurantees) self._read_eager('read_eager') self._read_eager('read_very_eager') # NB -- we need to test the IAC block which is mentioned in the # docstring but not in the module docs def read_very_lazy(self): want = b'x' * 100 telnet = test_telnet([want]) self.assertEqual(b'', telnet.read_very_lazy()) while telnet.sock.reads: telnet.fill_rawq() data = telnet.read_very_lazy() self.assertEqual(want, data) self.assertRaises(EOFError, telnet.read_very_lazy) def test_read_lazy(self): want = b'x' * 100 telnet = test_telnet([want]) self.assertEqual(b'', telnet.read_lazy()) data = b'' while True: try: read_data = telnet.read_lazy() data += read_data if not read_data: telnet.fill_rawq() except EOFError: break self.assertTrue(want.startswith(data)) self.assertEqual(data, want) class nego_collector(object): def __init__(self, sb_getter=None): self.seen = b'' self.sb_getter = sb_getter self.sb_seen = b'' def do_nego(self, sock, cmd, opt): self.seen += cmd + opt if cmd == tl.SE and self.sb_getter: sb_data = self.sb_getter() self.sb_seen += sb_data tl = telnetlib class WriteTests(TestCase): '''The only thing that write does is replace each tl.IAC for tl.IAC+tl.IAC''' def test_write(self): data_sample = [b'data sample without IAC', b'data sample with' + tl.IAC + b' one IAC', b'a few' + tl.IAC + tl.IAC + b' iacs' + tl.IAC, tl.IAC, b''] for data in data_sample: telnet = test_telnet() telnet.write(data) written = b''.join(telnet.sock.writes) self.assertEqual(data.replace(tl.IAC,tl.IAC+tl.IAC), written) class OptionTests(TestCase): # RFC 854 commands cmds = [tl.AO, tl.AYT, tl.BRK, tl.EC, tl.EL, tl.GA, tl.IP, tl.NOP] def _test_command(self, data): """ helper for testing IAC + cmd """ telnet = test_telnet(data) data_len = len(b''.join(data)) nego = nego_collector() telnet.set_option_negotiation_callback(nego.do_nego) txt = telnet.read_all() cmd = nego.seen self.assertTrue(len(cmd) > 0) # we expect at least one command self.assertIn(cmd[:1], self.cmds) self.assertEqual(cmd[1:2], tl.NOOPT) self.assertEqual(data_len, len(txt + cmd)) nego.sb_getter = None # break the nego => telnet cycle def test_IAC_commands(self): for cmd in self.cmds: self._test_command([tl.IAC, cmd]) self._test_command([b'x' * 100, tl.IAC, cmd, b'y'*100]) self._test_command([b'x' * 10, tl.IAC, cmd, b'y'*10]) # all at once self._test_command([tl.IAC + cmd for (cmd) in self.cmds]) def test_SB_commands(self): # RFC 855, subnegotiations portion send = [tl.IAC + tl.SB + tl.IAC + tl.SE, tl.IAC + tl.SB + tl.IAC + tl.IAC + tl.IAC + tl.SE, tl.IAC + tl.SB + tl.IAC + tl.IAC + b'aa' + tl.IAC + tl.SE, tl.IAC + tl.SB + b'bb' + tl.IAC + tl.IAC + tl.IAC + tl.SE, tl.IAC + tl.SB + b'cc' + tl.IAC + tl.IAC + b'dd' + tl.IAC + tl.SE, ] telnet = test_telnet(send) nego = nego_collector(telnet.read_sb_data) telnet.set_option_negotiation_callback(nego.do_nego) txt = telnet.read_all() self.assertEqual(txt, b'') want_sb_data = tl.IAC + tl.IAC + b'aabb' + tl.IAC + b'cc' + tl.IAC + b'dd' self.assertEqual(nego.sb_seen, want_sb_data) self.assertEqual(b'', telnet.read_sb_data()) nego.sb_getter = None # break the nego => telnet cycle def test_debuglevel_reads(self): # test all the various places that self.msg(...) is called given_a_expect_b = [ # Telnet.fill_rawq (b'a', ": recv b''\n"), # Telnet.process_rawq (tl.IAC + bytes([88]), ": IAC 88 not recognized\n"), (tl.IAC + tl.DO + bytes([1]), ": IAC DO 1\n"), (tl.IAC + tl.DONT + bytes([1]), ": IAC DONT 1\n"), (tl.IAC + tl.WILL + bytes([1]), ": IAC WILL 1\n"), (tl.IAC + tl.WONT + bytes([1]), ": IAC WONT 1\n"), ] for a, b in given_a_expect_b: telnet = test_telnet([a]) telnet.set_debuglevel(1) txt = telnet.read_all() self.assertIn(b, telnet._messages) return def test_debuglevel_write(self): telnet = test_telnet() telnet.set_debuglevel(1) telnet.write(b'xxx') expected = "send b'xxx'\n" self.assertIn(expected, telnet._messages) def test_debug_accepts_str_port(self): # Issue 10695 with test_socket([]): telnet = TelnetAlike('dummy', '0') telnet._messages = '' telnet.set_debuglevel(1) telnet.msg('test') self.assertRegex(telnet._messages, r'0.*test') class ExpectTests(ExpectAndReadTestCase): def test_expect(self): """ expect(expected, [timeout]) Read until the expected string has been seen, or a timeout is hit (default is no timeout); may block. """ want = [b'x' * 10, b'match', b'y' * 10] telnet = test_telnet(want) (_,_,data) = telnet.expect([b'match']) self.assertEqual(data, b''.join(want[:-1])) def test_main(verbose=None): support.run_unittest(GeneralTests, ReadTests, WriteTests, OptionTests, ExpectTests) if __name__ == '__main__': test_main()
gcd0318/django
refs/heads/master
tests/template_tests/filter_tests/test_linebreaksbr.py
331
from django.template.defaultfilters import linebreaksbr from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LinebreaksbrTests(SimpleTestCase): """ The contents in "linebreaksbr" are escaped according to the current autoescape setting. """ @setup({'linebreaksbr01': '{{ a|linebreaksbr }} {{ b|linebreaksbr }}'}) def test_linebreaksbr01(self): output = self.engine.render_to_string('linebreaksbr01', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "x&amp;<br />y x&<br />y") @setup({'linebreaksbr02': '{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}'}) def test_linebreaksbr02(self): output = self.engine.render_to_string('linebreaksbr02', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "x&<br />y x&<br />y") class FunctionTests(SimpleTestCase): def test_newline(self): self.assertEqual(linebreaksbr('line 1\nline 2'), 'line 1<br />line 2') def test_carriage(self): self.assertEqual(linebreaksbr('line 1\rline 2'), 'line 1<br />line 2') def test_carriage_newline(self): self.assertEqual(linebreaksbr('line 1\r\nline 2'), 'line 1<br />line 2') def test_non_string_input(self): self.assertEqual(linebreaksbr(123), '123') def test_autoescape(self): self.assertEqual( linebreaksbr('foo\n<a>bar</a>\nbuz'), 'foo<br />&lt;a&gt;bar&lt;/a&gt;<br />buz', ) def test_autoescape_off(self): self.assertEqual( linebreaksbr('foo\n<a>bar</a>\nbuz', autoescape=False), 'foo<br /><a>bar</a><br />buz', )
eromoe/flask-website
refs/heads/master
flask_website/search.py
6
# -*- coding: utf-8 -*- import os from whoosh import highlight, analysis, qparser from whoosh.support.charset import accent_map from flask import Markup from flask_website import app from werkzeug import import_string def open_index(): from whoosh import index, fields as f if os.path.isdir(app.config['WHOOSH_INDEX']): return index.open_dir(app.config['WHOOSH_INDEX']) os.mkdir(app.config['WHOOSH_INDEX']) analyzer = analysis.StemmingAnalyzer() | analysis.CharsetFilter(accent_map) schema = f.Schema( url=f.ID(stored=True, unique=True), id=f.ID(stored=True), title=f.TEXT(stored=True, field_boost=2.0, analyzer=analyzer), type=f.ID(stored=True), keywords=f.KEYWORD(commas=True), content=f.TEXT(analyzer=analyzer) ) return index.create_in(app.config['WHOOSH_INDEX'], schema) index = open_index() class Indexable(object): search_document_kind = None def add_to_search_index(self, writer): writer.add_document(url=unicode(self.url), type=self.search_document_type, **self.get_search_document()) @classmethod def describe_search_result(cls, result): return None @property def search_document_type(self): cls = type(self) return cls.__module__ + u'.' + cls.__name__ def get_search_document(self): raise NotImplementedError() def remove_from_search_index(self, writer): writer.delete_by_term('url', unicode(self.url)) def highlight_all(result, field): text = result[field] return Markup(highlight.Highlighter( fragmenter=highlight.WholeFragmenter(), formatter=result.results.highlighter.formatter) .highlight_hit(result, field, text=text)) or text class SearchResult(object): def __init__(self, result): self.url = result['url'] self.title_text = result['title'] self.title = highlight_all(result, 'title') cls = import_string(result['type']) self.kind = cls.search_document_kind self.description = cls.describe_search_result(result) class SearchResultPage(object): def __init__(self, results, page): self.page = page if results is None: self.results = [] self.pages = 1 self.total = 0 else: self.results = [SearchResult(r) for r in results] self.pages = results.pagecount self.total = results.total def __iter__(self): return iter(self.results) def search(query, page=1, per_page=20): with index.searcher() as s: qp = qparser.MultifieldParser(['title', 'content'], index.schema) q = qp.parse(unicode(query)) try: result_page = s.search_page(q, page, pagelen=per_page) except ValueError: if page == 1: return SearchResultPage(None, page) return None results = result_page.results results.highlighter.fragmenter.maxchars = 512 results.highlighter.fragmenter.surround = 40 results.highlighter.formatter = highlight.HtmlFormatter('em', classname='search-match', termclass='search-term', between=u'<span class=ellipsis> … </span>') return SearchResultPage(result_page, page) def update_model_based_indexes(session, flush_context): """Called by a session event, updates the model based documents.""" to_delete = [] to_add = [] for model in session.new: if isinstance(model, Indexable): to_add.append(model) for model in session.dirty: if isinstance(model, Indexable): to_delete.append(model) to_add.append(model) for model in session.dirty: if isinstance(model, Indexable): to_delete.append(model) if not (to_delete or to_add): return writer = index.writer() for model in to_delete: model.remove_from_search_index(writer) for model in to_add: model.add_to_search_index(writer) writer.commit() def update_documentation_index(): from flask_website.docs import DocumentationPage writer = index.writer() for page in DocumentationPage.iter_pages(): page.remove_from_search_index(writer) page.add_to_search_index(writer) writer.commit() def reindex_snippets(): from flask_website.database import Snippet writer = index.writer() for snippet in Snippet.query.all(): snippet.remove_from_search_index(writer) snippet.add_to_search_index(writer) writer.commit()
michaelyin/im2markup-prep
refs/heads/master
net/wyun/mer/ink/scg.py
1
import json from net.wyun.mer.ink.sample import Sample from net.wyun.mer.ink.stroke import Stroke from net.wyun.mer.ink import scginkparser import numpy as np from net.wyun.mer.ink.stroke import get_bounding_box from scipy import misc class Scg(object): def __init__(self, scg_id, scg_content, truth, request_at, response_at): self.id = scg_id self.content = scg_content self.response = truth self.request_at = request_at self.response_at = response_at self.truth_obj = Payload(truth) self.dummySample = Sample('data/inkml/65_alfonso.inkml') self.w_h_ratio = 1.0 # initialize here, updated in replace_traces() self.replace_traces() self.dummySample.re_calculate_IMG_MINMAX() def get_latex(self): return self.truth_obj.latex def replace_traces(self): ''' replace the traces in dummySample with the one generated from scg_content :return: ''' strokes = scginkparser.parse_scg_ink_file(self.content, self.id) #for st in strokes: #print st traces = {} trace_id_int = 0 for st in strokes: coords = np.zeros((2, len(st))) idx = 0 for x_y in st: coords[:, idx] = [float(x_y[0]), float(x_y[1])] idx += 1 traces[trace_id_int] = Stroke(trace_id_int, coords) trace_id_int += 1 # //Compute bounding box of the input expression x_min, y_min, x_max, y_max = get_bounding_box(traces) # bounding box for the whole math expression # Just in case there is only one point or a sequence of points perfectly aligned with the x or y axis if x_max == x_min: x_max = x_min + 1; if y_max == y_min: y_max = y_min + 1; self.w_h_ratio = float(x_max - x_min) / (y_max - y_min) # Renormalize to height [0,10000] keeping the aspect ratio H = 10000.0 W = H * (x_max - x_min) / (y_max - y_min) for trace_key, trace_v in traces.iteritems(): trace_v.calc_coords_h10000(H, W, x_min, y_min, x_max, y_max) self.dummySample.traces = traces def save_image(self, path): img, W, H = self.dummySample.render() print 'save image to: ', path misc.imsave(path, img) class Payload(object): def __init__(self, j): self.__dict__ = json.loads(j)
vipins/ccccms
refs/heads/master
env/Lib/encodings/cp1255.py
593
""" Python Character Mapping Codec cp1255 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1255.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1255', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u20ac' # 0x80 -> EURO SIGN u'\ufffe' # 0x81 -> UNDEFINED u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK u'\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS u'\u2020' # 0x86 -> DAGGER u'\u2021' # 0x87 -> DOUBLE DAGGER u'\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT u'\u2030' # 0x89 -> PER MILLE SIGN u'\ufffe' # 0x8A -> UNDEFINED u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\ufffe' # 0x8C -> UNDEFINED u'\ufffe' # 0x8D -> UNDEFINED u'\ufffe' # 0x8E -> UNDEFINED u'\ufffe' # 0x8F -> UNDEFINED u'\ufffe' # 0x90 -> UNDEFINED u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK u'\u2022' # 0x95 -> BULLET u'\u2013' # 0x96 -> EN DASH u'\u2014' # 0x97 -> EM DASH u'\u02dc' # 0x98 -> SMALL TILDE u'\u2122' # 0x99 -> TRADE MARK SIGN u'\ufffe' # 0x9A -> UNDEFINED u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\ufffe' # 0x9C -> UNDEFINED u'\ufffe' # 0x9D -> UNDEFINED u'\ufffe' # 0x9E -> UNDEFINED u'\ufffe' # 0x9F -> UNDEFINED u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK u'\xa2' # 0xA2 -> CENT SIGN u'\xa3' # 0xA3 -> POUND SIGN u'\u20aa' # 0xA4 -> NEW SHEQEL SIGN u'\xa5' # 0xA5 -> YEN SIGN u'\xa6' # 0xA6 -> BROKEN BAR u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\xd7' # 0xAA -> MULTIPLICATION SIGN u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xac' # 0xAC -> NOT SIGN u'\xad' # 0xAD -> SOFT HYPHEN u'\xae' # 0xAE -> REGISTERED SIGN u'\xaf' # 0xAF -> MACRON u'\xb0' # 0xB0 -> DEGREE SIGN u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\xb2' # 0xB2 -> SUPERSCRIPT TWO u'\xb3' # 0xB3 -> SUPERSCRIPT THREE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\xb9' # 0xB9 -> SUPERSCRIPT ONE u'\xf7' # 0xBA -> DIVISION SIGN u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF u'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS u'\xbf' # 0xBF -> INVERTED QUESTION MARK u'\u05b0' # 0xC0 -> HEBREW POINT SHEVA u'\u05b1' # 0xC1 -> HEBREW POINT HATAF SEGOL u'\u05b2' # 0xC2 -> HEBREW POINT HATAF PATAH u'\u05b3' # 0xC3 -> HEBREW POINT HATAF QAMATS u'\u05b4' # 0xC4 -> HEBREW POINT HIRIQ u'\u05b5' # 0xC5 -> HEBREW POINT TSERE u'\u05b6' # 0xC6 -> HEBREW POINT SEGOL u'\u05b7' # 0xC7 -> HEBREW POINT PATAH u'\u05b8' # 0xC8 -> HEBREW POINT QAMATS u'\u05b9' # 0xC9 -> HEBREW POINT HOLAM u'\ufffe' # 0xCA -> UNDEFINED u'\u05bb' # 0xCB -> HEBREW POINT QUBUTS u'\u05bc' # 0xCC -> HEBREW POINT DAGESH OR MAPIQ u'\u05bd' # 0xCD -> HEBREW POINT METEG u'\u05be' # 0xCE -> HEBREW PUNCTUATION MAQAF u'\u05bf' # 0xCF -> HEBREW POINT RAFE u'\u05c0' # 0xD0 -> HEBREW PUNCTUATION PASEQ u'\u05c1' # 0xD1 -> HEBREW POINT SHIN DOT u'\u05c2' # 0xD2 -> HEBREW POINT SIN DOT u'\u05c3' # 0xD3 -> HEBREW PUNCTUATION SOF PASUQ u'\u05f0' # 0xD4 -> HEBREW LIGATURE YIDDISH DOUBLE VAV u'\u05f1' # 0xD5 -> HEBREW LIGATURE YIDDISH VAV YOD u'\u05f2' # 0xD6 -> HEBREW LIGATURE YIDDISH DOUBLE YOD u'\u05f3' # 0xD7 -> HEBREW PUNCTUATION GERESH u'\u05f4' # 0xD8 -> HEBREW PUNCTUATION GERSHAYIM u'\ufffe' # 0xD9 -> UNDEFINED u'\ufffe' # 0xDA -> UNDEFINED u'\ufffe' # 0xDB -> UNDEFINED u'\ufffe' # 0xDC -> UNDEFINED u'\ufffe' # 0xDD -> UNDEFINED u'\ufffe' # 0xDE -> UNDEFINED u'\ufffe' # 0xDF -> UNDEFINED u'\u05d0' # 0xE0 -> HEBREW LETTER ALEF u'\u05d1' # 0xE1 -> HEBREW LETTER BET u'\u05d2' # 0xE2 -> HEBREW LETTER GIMEL u'\u05d3' # 0xE3 -> HEBREW LETTER DALET u'\u05d4' # 0xE4 -> HEBREW LETTER HE u'\u05d5' # 0xE5 -> HEBREW LETTER VAV u'\u05d6' # 0xE6 -> HEBREW LETTER ZAYIN u'\u05d7' # 0xE7 -> HEBREW LETTER HET u'\u05d8' # 0xE8 -> HEBREW LETTER TET u'\u05d9' # 0xE9 -> HEBREW LETTER YOD u'\u05da' # 0xEA -> HEBREW LETTER FINAL KAF u'\u05db' # 0xEB -> HEBREW LETTER KAF u'\u05dc' # 0xEC -> HEBREW LETTER LAMED u'\u05dd' # 0xED -> HEBREW LETTER FINAL MEM u'\u05de' # 0xEE -> HEBREW LETTER MEM u'\u05df' # 0xEF -> HEBREW LETTER FINAL NUN u'\u05e0' # 0xF0 -> HEBREW LETTER NUN u'\u05e1' # 0xF1 -> HEBREW LETTER SAMEKH u'\u05e2' # 0xF2 -> HEBREW LETTER AYIN u'\u05e3' # 0xF3 -> HEBREW LETTER FINAL PE u'\u05e4' # 0xF4 -> HEBREW LETTER PE u'\u05e5' # 0xF5 -> HEBREW LETTER FINAL TSADI u'\u05e6' # 0xF6 -> HEBREW LETTER TSADI u'\u05e7' # 0xF7 -> HEBREW LETTER QOF u'\u05e8' # 0xF8 -> HEBREW LETTER RESH u'\u05e9' # 0xF9 -> HEBREW LETTER SHIN u'\u05ea' # 0xFA -> HEBREW LETTER TAV u'\ufffe' # 0xFB -> UNDEFINED u'\ufffe' # 0xFC -> UNDEFINED u'\u200e' # 0xFD -> LEFT-TO-RIGHT MARK u'\u200f' # 0xFE -> RIGHT-TO-LEFT MARK u'\ufffe' # 0xFF -> UNDEFINED ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
BhupeshGupta/erpnext
refs/heads/develop
erpnext/accounts/page/accounts_browser/accounts_browser.py
34
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import frappe.defaults from frappe.utils import flt from erpnext.accounts.utils import get_balance_on @frappe.whitelist() def get_companies(): """get a list of companies based on permission""" return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")] @frappe.whitelist() def get_children(): args = frappe.local.form_dict ctype, company = args['ctype'], args['comp'] # root if args['parent'] in ("Accounts", "Cost Centers"): acc = frappe.db.sql(""" select name as value, if(group_or_ledger='Group', 1, 0) as expandable from `tab%s` where ifnull(parent_%s,'') = '' and `company` = %s and docstatus<2 order by name""" % (ctype, ctype.lower().replace(' ','_'), '%s'), company, as_dict=1) else: # other acc = frappe.db.sql("""select name as value, if(group_or_ledger='Group', 1, 0) as expandable from `tab%s` where ifnull(parent_%s,'') = %s and docstatus<2 order by name""" % (ctype, ctype.lower().replace(' ','_'), '%s'), args['parent'], as_dict=1) if ctype == 'Account': currency = frappe.db.sql("select default_currency from `tabCompany` where name = %s", company)[0][0] for each in acc: bal = get_balance_on(each.get("value")) each["currency"] = currency each["balance"] = flt(bal) return acc
alphagov/notify-api
refs/heads/master
app/job/sms_jobs.py
1
import os from datetime import datetime from flask import json from app.connectors.access_queue import get_messages_from_queue from app.models import Notification from app import db, sms_wrapper, create_app from sqlalchemy import asc from app.connectors.sms.clients import ClientException def __update_notification_to_sent(id, message_id, sender): notification = Notification.query.filter_by(id=id).first() notification.status = 'sent' notification.sent_at = datetime.utcnow() notification.sender_id = message_id notification.sender = sender db.session.add(notification) db.session.commit() def __update_notification_in_error(e, id, sender): notification = Notification.query.filter_by(id=id).first() notification.status = 'error' notification.sender = e.sender db.session.add(notification) db.session.commit() def send_sms(): application = create_app(os.getenv('NOTIFY_API_ENVIRONMENT') or 'development') with application.app_context(): notifications = get_messages_from_queue('sms') for notification in notifications: if notification.message_attributes.get('type').get('StringValue') == 'sms': print("Processing SMS messages") try: notification_body = json.loads(notification.body) print("Processing {}".format(notification_body['id'])) print("notification: {}".format(notification.body)) (message_id, sender) = sms_wrapper.send(notification_body['to'], notification_body['message'], notification_body['id']) notification.delete() __update_notification_to_sent(notification_body['id'], message_id, sender) except ClientException as e: print(e) __update_notification_in_error(e, notification_body['id'], e.sender) def fetch_sms_status(): application = create_app(os.getenv('NOTIFY_API_ENVIRONMENT') or 'development') with application.app_context(): notifications = Notification.query \ .filter(Notification.status == 'sent') \ .order_by(asc(Notification.sent_at)).all() for notification in notifications: print("Processing SMS status") try: response_status = sms_wrapper.status(notification.sender_id, notification.sender) if response_status: notification.status = response_status if response_status == 'delivered': notification.delivered_at = datetime.utcnow() db.session.add(notification) db.session.commit() except ClientException as e: print(e)
hozn/stravalib
refs/heads/master
examples/strava-oauth/server.py
1
#!flask/bin/python import logging from flask import Flask, render_template, redirect, url_for, request, jsonify from stravalib import Client app = Flask(__name__) app.config.from_envvar('APP_SETTINGS') @app.route("/") def login(): c = Client() url = c.authorization_url(client_id=app.config['STRAVA_CLIENT_ID'], redirect_uri=url_for('.logged_in', _external=True), approval_prompt='auto') return render_template('login.html', authorize_url=url) @app.route("/strava-oauth") def logged_in(): """ Method called by Strava (redirect) that includes parameters. - state - code - error """ error = request.args.get('error') state = request.args.get('state') if error: return render_template('login_error.html', error=error) else: code = request.args.get('code') client = Client() access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'], client_secret=app.config['STRAVA_CLIENT_SECRET'], code=code) # Probably here you'd want to store this somewhere -- e.g. in a database. strava_athlete = client.get_athlete() return render_template('login_results.html', athlete=strava_athlete, access_token=access_token) if __name__ == '__main__': app.run(debug=True)
swieder227/three.js
refs/heads/master
utils/converters/msgpack/msgpack/fallback.py
641
"""Fallback pure Python implementation of msgpack""" import sys import array import struct if sys.version_info[0] == 3: PY3 = True int_types = int Unicode = str xrange = range def dict_iteritems(d): return d.items() else: PY3 = False int_types = (int, long) Unicode = unicode def dict_iteritems(d): return d.iteritems() if hasattr(sys, 'pypy_version_info'): # cStringIO is slow on PyPy, StringIO is faster. However: PyPy's own # StringBuilder is fastest. from __pypy__ import newlist_hint from __pypy__.builders import StringBuilder USING_STRINGBUILDER = True class StringIO(object): def __init__(self, s=b''): if s: self.builder = StringBuilder(len(s)) self.builder.append(s) else: self.builder = StringBuilder() def write(self, s): self.builder.append(s) def getvalue(self): return self.builder.build() else: USING_STRINGBUILDER = False from io import BytesIO as StringIO newlist_hint = lambda size: [] from msgpack.exceptions import ( BufferFull, OutOfData, UnpackValueError, PackValueError, ExtraData) from msgpack import ExtType EX_SKIP = 0 EX_CONSTRUCT = 1 EX_READ_ARRAY_HEADER = 2 EX_READ_MAP_HEADER = 3 TYPE_IMMEDIATE = 0 TYPE_ARRAY = 1 TYPE_MAP = 2 TYPE_RAW = 3 TYPE_BIN = 4 TYPE_EXT = 5 DEFAULT_RECURSE_LIMIT = 511 def unpack(stream, **kwargs): """ Unpack an object from `stream`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options. """ unpacker = Unpacker(stream, **kwargs) ret = unpacker._fb_unpack() if unpacker._fb_got_extradata(): raise ExtraData(ret, unpacker._fb_get_extradata()) return ret def unpackb(packed, **kwargs): """ Unpack an object from `packed`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options. """ unpacker = Unpacker(None, **kwargs) unpacker.feed(packed) try: ret = unpacker._fb_unpack() except OutOfData: raise UnpackValueError("Data is not enough.") if unpacker._fb_got_extradata(): raise ExtraData(ret, unpacker._fb_get_extradata()) return ret class Unpacker(object): """ Streaming unpacker. `file_like` is a file-like object having a `.read(n)` method. When `Unpacker` is initialized with a `file_like`, `.feed()` is not usable. `read_size` is used for `file_like.read(read_size)`. If `use_list` is True (default), msgpack lists are deserialized to Python lists. Otherwise they are deserialized to tuples. `object_hook` is the same as in simplejson. If it is not None, it should be callable and Unpacker calls it with a dict argument after deserializing a map. `object_pairs_hook` is the same as in simplejson. If it is not None, it should be callable and Unpacker calls it with a list of key-value pairs after deserializing a map. `ext_hook` is callback for ext (User defined) type. It called with two arguments: (code, bytes). default: `msgpack.ExtType` `encoding` is the encoding used for decoding msgpack bytes. If it is None (default), msgpack bytes are deserialized to Python bytes. `unicode_errors` is used for decoding bytes. `max_buffer_size` limits the buffer size. 0 means INT_MAX (default). Raises `BufferFull` exception when it is unsufficient. You should set this parameter when unpacking data from an untrustred source. example of streaming deserialization from file-like object:: unpacker = Unpacker(file_like) for o in unpacker: do_something(o) example of streaming deserialization from socket:: unpacker = Unpacker() while 1: buf = sock.recv(1024*2) if not buf: break unpacker.feed(buf) for o in unpacker: do_something(o) """ def __init__(self, file_like=None, read_size=0, use_list=True, object_hook=None, object_pairs_hook=None, list_hook=None, encoding=None, unicode_errors='strict', max_buffer_size=0, ext_hook=ExtType): if file_like is None: self._fb_feeding = True else: if not callable(file_like.read): raise TypeError("`file_like.read` must be callable") self.file_like = file_like self._fb_feeding = False self._fb_buffers = [] self._fb_buf_o = 0 self._fb_buf_i = 0 self._fb_buf_n = 0 self._max_buffer_size = max_buffer_size or 2**31-1 if read_size > self._max_buffer_size: raise ValueError("read_size must be smaller than max_buffer_size") self._read_size = read_size or min(self._max_buffer_size, 2048) self._encoding = encoding self._unicode_errors = unicode_errors self._use_list = use_list self._list_hook = list_hook self._object_hook = object_hook self._object_pairs_hook = object_pairs_hook self._ext_hook = ext_hook if list_hook is not None and not callable(list_hook): raise TypeError('`list_hook` is not callable') if object_hook is not None and not callable(object_hook): raise TypeError('`object_hook` is not callable') if object_pairs_hook is not None and not callable(object_pairs_hook): raise TypeError('`object_pairs_hook` is not callable') if object_hook is not None and object_pairs_hook is not None: raise TypeError("object_pairs_hook and object_hook are mutually " "exclusive") if not callable(ext_hook): raise TypeError("`ext_hook` is not callable") def feed(self, next_bytes): if isinstance(next_bytes, array.array): next_bytes = next_bytes.tostring() elif isinstance(next_bytes, bytearray): next_bytes = bytes(next_bytes) assert self._fb_feeding if self._fb_buf_n + len(next_bytes) > self._max_buffer_size: raise BufferFull self._fb_buf_n += len(next_bytes) self._fb_buffers.append(next_bytes) def _fb_consume(self): self._fb_buffers = self._fb_buffers[self._fb_buf_i:] if self._fb_buffers: self._fb_buffers[0] = self._fb_buffers[0][self._fb_buf_o:] self._fb_buf_o = 0 self._fb_buf_i = 0 self._fb_buf_n = sum(map(len, self._fb_buffers)) def _fb_got_extradata(self): if self._fb_buf_i != len(self._fb_buffers): return True if self._fb_feeding: return False if not self.file_like: return False if self.file_like.read(1): return True return False def __iter__(self): return self def read_bytes(self, n): return self._fb_read(n) def _fb_rollback(self): self._fb_buf_i = 0 self._fb_buf_o = 0 def _fb_get_extradata(self): bufs = self._fb_buffers[self._fb_buf_i:] if bufs: bufs[0] = bufs[0][self._fb_buf_o:] return b''.join(bufs) def _fb_read(self, n, write_bytes=None): buffs = self._fb_buffers if (write_bytes is None and self._fb_buf_i < len(buffs) and self._fb_buf_o + n < len(buffs[self._fb_buf_i])): self._fb_buf_o += n return buffs[self._fb_buf_i][self._fb_buf_o - n:self._fb_buf_o] ret = b'' while len(ret) != n: if self._fb_buf_i == len(buffs): if self._fb_feeding: break tmp = self.file_like.read(self._read_size) if not tmp: break buffs.append(tmp) continue sliced = n - len(ret) ret += buffs[self._fb_buf_i][self._fb_buf_o:self._fb_buf_o + sliced] self._fb_buf_o += sliced if self._fb_buf_o >= len(buffs[self._fb_buf_i]): self._fb_buf_o = 0 self._fb_buf_i += 1 if len(ret) != n: self._fb_rollback() raise OutOfData if write_bytes is not None: write_bytes(ret) return ret def _read_header(self, execute=EX_CONSTRUCT, write_bytes=None): typ = TYPE_IMMEDIATE n = 0 obj = None c = self._fb_read(1, write_bytes) b = ord(c) if b & 0b10000000 == 0: obj = b elif b & 0b11100000 == 0b11100000: obj = struct.unpack("b", c)[0] elif b & 0b11100000 == 0b10100000: n = b & 0b00011111 obj = self._fb_read(n, write_bytes) typ = TYPE_RAW elif b & 0b11110000 == 0b10010000: n = b & 0b00001111 typ = TYPE_ARRAY elif b & 0b11110000 == 0b10000000: n = b & 0b00001111 typ = TYPE_MAP elif b == 0xc0: obj = None elif b == 0xc2: obj = False elif b == 0xc3: obj = True elif b == 0xc4: typ = TYPE_BIN n = struct.unpack("B", self._fb_read(1, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xc5: typ = TYPE_BIN n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xc6: typ = TYPE_BIN n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xc7: # ext 8 typ = TYPE_EXT L, n = struct.unpack('Bb', self._fb_read(2, write_bytes)) obj = self._fb_read(L, write_bytes) elif b == 0xc8: # ext 16 typ = TYPE_EXT L, n = struct.unpack('>Hb', self._fb_read(3, write_bytes)) obj = self._fb_read(L, write_bytes) elif b == 0xc9: # ext 32 typ = TYPE_EXT L, n = struct.unpack('>Ib', self._fb_read(5, write_bytes)) obj = self._fb_read(L, write_bytes) elif b == 0xca: obj = struct.unpack(">f", self._fb_read(4, write_bytes))[0] elif b == 0xcb: obj = struct.unpack(">d", self._fb_read(8, write_bytes))[0] elif b == 0xcc: obj = struct.unpack("B", self._fb_read(1, write_bytes))[0] elif b == 0xcd: obj = struct.unpack(">H", self._fb_read(2, write_bytes))[0] elif b == 0xce: obj = struct.unpack(">I", self._fb_read(4, write_bytes))[0] elif b == 0xcf: obj = struct.unpack(">Q", self._fb_read(8, write_bytes))[0] elif b == 0xd0: obj = struct.unpack("b", self._fb_read(1, write_bytes))[0] elif b == 0xd1: obj = struct.unpack(">h", self._fb_read(2, write_bytes))[0] elif b == 0xd2: obj = struct.unpack(">i", self._fb_read(4, write_bytes))[0] elif b == 0xd3: obj = struct.unpack(">q", self._fb_read(8, write_bytes))[0] elif b == 0xd4: # fixext 1 typ = TYPE_EXT n, obj = struct.unpack('b1s', self._fb_read(2, write_bytes)) elif b == 0xd5: # fixext 2 typ = TYPE_EXT n, obj = struct.unpack('b2s', self._fb_read(3, write_bytes)) elif b == 0xd6: # fixext 4 typ = TYPE_EXT n, obj = struct.unpack('b4s', self._fb_read(5, write_bytes)) elif b == 0xd7: # fixext 8 typ = TYPE_EXT n, obj = struct.unpack('b8s', self._fb_read(9, write_bytes)) elif b == 0xd8: # fixext 16 typ = TYPE_EXT n, obj = struct.unpack('b16s', self._fb_read(17, write_bytes)) elif b == 0xd9: typ = TYPE_RAW n = struct.unpack("B", self._fb_read(1, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xda: typ = TYPE_RAW n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xdb: typ = TYPE_RAW n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] obj = self._fb_read(n, write_bytes) elif b == 0xdc: n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] typ = TYPE_ARRAY elif b == 0xdd: n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] typ = TYPE_ARRAY elif b == 0xde: n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] typ = TYPE_MAP elif b == 0xdf: n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] typ = TYPE_MAP else: raise UnpackValueError("Unknown header: 0x%x" % b) return typ, n, obj def _fb_unpack(self, execute=EX_CONSTRUCT, write_bytes=None): typ, n, obj = self._read_header(execute, write_bytes) if execute == EX_READ_ARRAY_HEADER: if typ != TYPE_ARRAY: raise UnpackValueError("Expected array") return n if execute == EX_READ_MAP_HEADER: if typ != TYPE_MAP: raise UnpackValueError("Expected map") return n # TODO should we eliminate the recursion? if typ == TYPE_ARRAY: if execute == EX_SKIP: for i in xrange(n): # TODO check whether we need to call `list_hook` self._fb_unpack(EX_SKIP, write_bytes) return ret = newlist_hint(n) for i in xrange(n): ret.append(self._fb_unpack(EX_CONSTRUCT, write_bytes)) if self._list_hook is not None: ret = self._list_hook(ret) # TODO is the interaction between `list_hook` and `use_list` ok? return ret if self._use_list else tuple(ret) if typ == TYPE_MAP: if execute == EX_SKIP: for i in xrange(n): # TODO check whether we need to call hooks self._fb_unpack(EX_SKIP, write_bytes) self._fb_unpack(EX_SKIP, write_bytes) return if self._object_pairs_hook is not None: ret = self._object_pairs_hook( (self._fb_unpack(EX_CONSTRUCT, write_bytes), self._fb_unpack(EX_CONSTRUCT, write_bytes)) for _ in xrange(n)) else: ret = {} for _ in xrange(n): key = self._fb_unpack(EX_CONSTRUCT, write_bytes) ret[key] = self._fb_unpack(EX_CONSTRUCT, write_bytes) if self._object_hook is not None: ret = self._object_hook(ret) return ret if execute == EX_SKIP: return if typ == TYPE_RAW: if self._encoding is not None: obj = obj.decode(self._encoding, self._unicode_errors) return obj if typ == TYPE_EXT: return self._ext_hook(n, obj) if typ == TYPE_BIN: return obj assert typ == TYPE_IMMEDIATE return obj def next(self): try: ret = self._fb_unpack(EX_CONSTRUCT, None) self._fb_consume() return ret except OutOfData: raise StopIteration __next__ = next def skip(self, write_bytes=None): self._fb_unpack(EX_SKIP, write_bytes) self._fb_consume() def unpack(self, write_bytes=None): ret = self._fb_unpack(EX_CONSTRUCT, write_bytes) self._fb_consume() return ret def read_array_header(self, write_bytes=None): ret = self._fb_unpack(EX_READ_ARRAY_HEADER, write_bytes) self._fb_consume() return ret def read_map_header(self, write_bytes=None): ret = self._fb_unpack(EX_READ_MAP_HEADER, write_bytes) self._fb_consume() return ret class Packer(object): """ MessagePack Packer usage: packer = Packer() astream.write(packer.pack(a)) astream.write(packer.pack(b)) Packer's constructor has some keyword arguments: :param callable default: Convert user type to builtin type that Packer supports. See also simplejson's document. :param str encoding: Convert unicode to bytes with this encoding. (default: 'utf-8') :param str unicode_errors: Error handler for encoding unicode. (default: 'strict') :param bool use_single_float: Use single precision float type for float. (default: False) :param bool autoreset: Reset buffer after each pack and return it's content as `bytes`. (default: True). If set this to false, use `bytes()` to get content and `.reset()` to clear buffer. :param bool use_bin_type: Use bin type introduced in msgpack spec 2.0 for bytes. It also enable str8 type for unicode. """ def __init__(self, default=None, encoding='utf-8', unicode_errors='strict', use_single_float=False, autoreset=True, use_bin_type=False): self._use_float = use_single_float self._autoreset = autoreset self._use_bin_type = use_bin_type self._encoding = encoding self._unicode_errors = unicode_errors self._buffer = StringIO() if default is not None: if not callable(default): raise TypeError("default must be callable") self._default = default def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT, isinstance=isinstance): default_used = False while True: if nest_limit < 0: raise PackValueError("recursion limit exceeded") if obj is None: return self._buffer.write(b"\xc0") if isinstance(obj, bool): if obj: return self._buffer.write(b"\xc3") return self._buffer.write(b"\xc2") if isinstance(obj, int_types): if 0 <= obj < 0x80: return self._buffer.write(struct.pack("B", obj)) if -0x20 <= obj < 0: return self._buffer.write(struct.pack("b", obj)) if 0x80 <= obj <= 0xff: return self._buffer.write(struct.pack("BB", 0xcc, obj)) if -0x80 <= obj < 0: return self._buffer.write(struct.pack(">Bb", 0xd0, obj)) if 0xff < obj <= 0xffff: return self._buffer.write(struct.pack(">BH", 0xcd, obj)) if -0x8000 <= obj < -0x80: return self._buffer.write(struct.pack(">Bh", 0xd1, obj)) if 0xffff < obj <= 0xffffffff: return self._buffer.write(struct.pack(">BI", 0xce, obj)) if -0x80000000 <= obj < -0x8000: return self._buffer.write(struct.pack(">Bi", 0xd2, obj)) if 0xffffffff < obj <= 0xffffffffffffffff: return self._buffer.write(struct.pack(">BQ", 0xcf, obj)) if -0x8000000000000000 <= obj < -0x80000000: return self._buffer.write(struct.pack(">Bq", 0xd3, obj)) raise PackValueError("Integer value out of range") if self._use_bin_type and isinstance(obj, bytes): n = len(obj) if n <= 0xff: self._buffer.write(struct.pack('>BB', 0xc4, n)) elif n <= 0xffff: self._buffer.write(struct.pack(">BH", 0xc5, n)) elif n <= 0xffffffff: self._buffer.write(struct.pack(">BI", 0xc6, n)) else: raise PackValueError("Bytes is too large") return self._buffer.write(obj) if isinstance(obj, (Unicode, bytes)): if isinstance(obj, Unicode): if self._encoding is None: raise TypeError( "Can't encode unicode string: " "no encoding is specified") obj = obj.encode(self._encoding, self._unicode_errors) n = len(obj) if n <= 0x1f: self._buffer.write(struct.pack('B', 0xa0 + n)) elif self._use_bin_type and n <= 0xff: self._buffer.write(struct.pack('>BB', 0xd9, n)) elif n <= 0xffff: self._buffer.write(struct.pack(">BH", 0xda, n)) elif n <= 0xffffffff: self._buffer.write(struct.pack(">BI", 0xdb, n)) else: raise PackValueError("String is too large") return self._buffer.write(obj) if isinstance(obj, float): if self._use_float: return self._buffer.write(struct.pack(">Bf", 0xca, obj)) return self._buffer.write(struct.pack(">Bd", 0xcb, obj)) if isinstance(obj, ExtType): code = obj.code data = obj.data assert isinstance(code, int) assert isinstance(data, bytes) L = len(data) if L == 1: self._buffer.write(b'\xd4') elif L == 2: self._buffer.write(b'\xd5') elif L == 4: self._buffer.write(b'\xd6') elif L == 8: self._buffer.write(b'\xd7') elif L == 16: self._buffer.write(b'\xd8') elif L <= 0xff: self._buffer.write(struct.pack(">BB", 0xc7, L)) elif L <= 0xffff: self._buffer.write(struct.pack(">BH", 0xc8, L)) else: self._buffer.write(struct.pack(">BI", 0xc9, L)) self._buffer.write(struct.pack("b", code)) self._buffer.write(data) return if isinstance(obj, (list, tuple)): n = len(obj) self._fb_pack_array_header(n) for i in xrange(n): self._pack(obj[i], nest_limit - 1) return if isinstance(obj, dict): return self._fb_pack_map_pairs(len(obj), dict_iteritems(obj), nest_limit - 1) if not default_used and self._default is not None: obj = self._default(obj) default_used = 1 continue raise TypeError("Cannot serialize %r" % obj) def pack(self, obj): self._pack(obj) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret def pack_map_pairs(self, pairs): self._fb_pack_map_pairs(len(pairs), pairs) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret def pack_array_header(self, n): if n >= 2**32: raise ValueError self._fb_pack_array_header(n) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret def pack_map_header(self, n): if n >= 2**32: raise ValueError self._fb_pack_map_header(n) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret def pack_ext_type(self, typecode, data): if not isinstance(typecode, int): raise TypeError("typecode must have int type.") if not 0 <= typecode <= 127: raise ValueError("typecode should be 0-127") if not isinstance(data, bytes): raise TypeError("data must have bytes type") L = len(data) if L > 0xffffffff: raise ValueError("Too large data") if L == 1: self._buffer.write(b'\xd4') elif L == 2: self._buffer.write(b'\xd5') elif L == 4: self._buffer.write(b'\xd6') elif L == 8: self._buffer.write(b'\xd7') elif L == 16: self._buffer.write(b'\xd8') elif L <= 0xff: self._buffer.write(b'\xc7' + struct.pack('B', L)) elif L <= 0xffff: self._buffer.write(b'\xc8' + struct.pack('>H', L)) else: self._buffer.write(b'\xc9' + struct.pack('>I', L)) self._buffer.write(struct.pack('B', typecode)) self._buffer.write(data) def _fb_pack_array_header(self, n): if n <= 0x0f: return self._buffer.write(struct.pack('B', 0x90 + n)) if n <= 0xffff: return self._buffer.write(struct.pack(">BH", 0xdc, n)) if n <= 0xffffffff: return self._buffer.write(struct.pack(">BI", 0xdd, n)) raise PackValueError("Array is too large") def _fb_pack_map_header(self, n): if n <= 0x0f: return self._buffer.write(struct.pack('B', 0x80 + n)) if n <= 0xffff: return self._buffer.write(struct.pack(">BH", 0xde, n)) if n <= 0xffffffff: return self._buffer.write(struct.pack(">BI", 0xdf, n)) raise PackValueError("Dict is too large") def _fb_pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT): self._fb_pack_map_header(n) for (k, v) in pairs: self._pack(k, nest_limit - 1) self._pack(v, nest_limit - 1) def bytes(self): return self._buffer.getvalue() def reset(self): self._buffer = StringIO()
RouxRC/weboob
refs/heads/master
modules/podnapisi/test.py
7
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest from random import choice class PodnapisiTest(BackendTest): MODULE = 'podnapisi' def test_subtitle(self): lsub = [] subtitles = self.backend.iter_subtitles('fr', 'spiderman') for i in range(5): subtitle = subtitles.next() lsub.append(subtitle) assert (len(lsub) > 0) # get the file of a random sub if len(lsub): subtitle = choice(lsub) self.backend.get_subtitle_file(subtitle.id) ss = self.backend.get_subtitle(subtitle.id) assert ss.url.startswith('http')
ric2b/Vivaldi-browser
refs/heads/master
chromium/third_party/blink/tools/blinkpy/web_tests/controllers/__init__.py
6014
# Required for Python to search this directory for module files
shybovycha/buck
refs/heads/master
test/com/facebook/buck/android/testdata/exopackage_integration/generate.py
6
#!/usr/bin/python import json import os import shutil import zipfile config = json.loads(open('state.config').read()) package = config['package'] data = config['data'] def generate_file(template_path, path, data): with open(template_path, 'r') as template_file: template = template_file.read() with open(path, 'w') as outfile: outfile.write(template.format(**data)) longstring = 'a bunch of useless data' * 100 print len(longstring) generate_file('Java.template', 'Java1.java', { 'class': 'Java1', 'data': data['java1'], 'longstring': longstring}) generate_file('Java.template', 'Java2.java', { 'class': 'Java2', 'data': data['java2'], 'longstring': longstring}) generate_file('Java.template', 'Java3.java', { 'class': 'Java3', 'data': data['java3'], 'longstring': longstring}) generate_file('MainJava.template', 'MainJava.java', { 'data': data['main_apk_java'] }) generate_file('Cxx.template', 'cxx1.c', { 'data': data['cxx1'] }) generate_file('Cxx.template', 'cxx2.c', { 'data': data['cxx2'] }) generate_file('Cxx.template', 'cxx3.c', { 'data': data['cxx3'] }) generate_file('AndroidManifest.template', 'AndroidManifest.xml', { 'data': data['manifest'], 'package': package }) resources_dir = 'res/values' if not os.path.exists(resources_dir): os.makedirs(resources_dir) generate_file('Resources.template', 'res/values/strings.xml', { 'resources': data['resources'] } ) main_resources_dir = 'main_res/values' if not os.path.exists(main_resources_dir): os.makedirs(main_resources_dir) generate_file('MainResources.template', 'main_res/values/strings.xml', { 'main_apk_resources': data['main_apk_resources'] } ) assets_dir = 'assets' if not os.path.exists(assets_dir): os.mkdir(assets_dir) with open(os.path.join(assets_dir, 'asset.txt'), 'w') as assetfile: assetfile.write(data['assets']) with zipfile.ZipFile('java_resources.jar', 'w') as zipout: zipout.writestr('java_resources.txt', data['java_resources']) shutil.copy('state.config', 'config.processed')
DasIch/django
refs/heads/master
django/contrib/gis/gdal/raster/band.py
28
import math from ctypes import byref, c_double, c_int, c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import raster as capi from django.contrib.gis.shortcuts import numpy from django.utils import six from django.utils.encoding import force_text from django.utils.six.moves import range from .const import GDAL_INTEGER_TYPES, GDAL_PIXEL_TYPES, GDAL_TO_CTYPES class GDALBand(GDALBase): """ Wraps a GDAL raster band, needs to be obtained from a GDALRaster object. """ def __init__(self, source, index): self.source = source self._ptr = capi.get_ds_raster_band(source._ptr, index) def _flush(self): """ Call the flush method on the Band's parent raster and force a refresh of the statistics attribute when requested the next time. """ self.source._flush() self._stats_refresh = True @property def description(self): """ Returns the description string of the band. """ return force_text(capi.get_band_description(self._ptr)) @property def width(self): """ Width (X axis) in pixels of the band. """ return capi.get_band_xsize(self._ptr) @property def height(self): """ Height (Y axis) in pixels of the band. """ return capi.get_band_ysize(self._ptr) @property def pixel_count(self): """ Returns the total number of pixels in this band. """ return self.width * self.height _stats_refresh = False def statistics(self, refresh=False, approximate=False): """ Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation). If approximate=True, the statistics may be computed based on overviews or a subset of image tiles. If refresh=True, the statistics will be computed from the data directly, and the cache will be updated where applicable. For empty bands (where all pixel values are nodata), all statistics values are returned as None. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file. """ # Prepare array with arguments for capi function smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double() stats_args = [ self._ptr, c_int(approximate), byref(smin), byref(smax), byref(smean), byref(sstd), c_void_p(), c_void_p(), ] if refresh or self._stats_refresh: capi.compute_band_statistics(*stats_args) else: # Add additional argument to force computation if there is no # existing PAM file to take the values from. force = True stats_args.insert(2, c_int(force)) capi.get_band_statistics(*stats_args) result = smin.value, smax.value, smean.value, sstd.value # Check if band is empty (in that case, set all statistics to None) if any((math.isnan(val) for val in result)): result = (None, None, None, None) self._stats_refresh = False return result @property def min(self): """ Return the minimum pixel value for this band. """ return self.statistics()[0] @property def max(self): """ Return the maximum pixel value for this band. """ return self.statistics()[1] @property def mean(self): """ Return the mean of all pixel values of this band. """ return self.statistics()[2] @property def std(self): """ Return the standard deviation of all pixel values of this band. """ return self.statistics()[3] @property def nodata_value(self): """ Returns the nodata value for this band, or None if it isn't set. """ # Get value and nodata exists flag nodata_exists = c_int() value = capi.get_band_nodata_value(self._ptr, nodata_exists) if not nodata_exists: value = None # If the pixeltype is an integer, convert to int elif self.datatype() in GDAL_INTEGER_TYPES: value = int(value) return value @nodata_value.setter def nodata_value(self, value): """ Sets the nodata value for this band. """ if not isinstance(value, (int, float)): raise ValueError('Nodata value must be numeric.') capi.set_band_nodata_value(self._ptr, value) self._flush() def datatype(self, as_string=False): """ Returns the GDAL Pixel Datatype for this band. """ dtype = capi.get_band_datatype(self._ptr) if as_string: dtype = GDAL_PIXEL_TYPES[dtype] return dtype def data(self, data=None, offset=None, size=None, as_memoryview=False): """ Reads or writes pixel values for this band. Blocks of data can be accessed by specifying the width, height and offset of the desired block. The same specification can be used to update parts of a raster by providing an array of values. Allowed input data types are bytes, memoryview, list, tuple, and array. """ if not offset: offset = (0, 0) if not size: size = (self.width - offset[0], self.height - offset[1]) if any(x <= 0 for x in size): raise ValueError('Offset too big for this raster.') if size[0] > self.width or size[1] > self.height: raise ValueError('Size is larger than raster.') # Create ctypes type array generator ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (size[0] * size[1]) if data is None: # Set read mode access_flag = 0 # Prepare empty ctypes array data_array = ctypes_array() else: # Set write mode access_flag = 1 # Instantiate ctypes array holding the input data if isinstance(data, (bytes, six.memoryview)) or (numpy and isinstance(data, numpy.ndarray)): data_array = ctypes_array.from_buffer_copy(data) else: data_array = ctypes_array(*data) # Access band capi.band_io(self._ptr, access_flag, offset[0], offset[1], size[0], size[1], byref(data_array), size[0], size[1], self.datatype(), 0, 0) # Return data as numpy array if possible, otherwise as list if data is None: if as_memoryview: return memoryview(data_array) elif numpy: return numpy.frombuffer( data_array, dtype=numpy.dtype(data_array)).reshape(size) else: return list(data_array) else: self._flush() class BandList(list): def __init__(self, source): self.source = source list.__init__(self) def __iter__(self): for idx in range(1, len(self) + 1): yield GDALBand(self.source, idx) def __len__(self): return capi.get_ds_raster_count(self.source._ptr) def __getitem__(self, index): try: return GDALBand(self.source, index + 1) except GDALException: raise GDALException('Unable to get band index %d' % index)
CooperLuan/airflow
refs/heads/master
airflow/executors/base_executor.py
30
from builtins import range from builtins import object import logging from airflow.utils import State from airflow.configuration import conf PARALLELISM = conf.getint('core', 'PARALLELISM') class BaseExecutor(object): def __init__(self, parallelism=PARALLELISM): """ Class to derive in order to interface with executor-type systems like Celery, Mesos, Yarn and the likes. :param parallelism: how many jobs should run at one time. Set to ``0`` for infinity :type parallelism: int """ self.parallelism = parallelism self.queued_tasks = {} self.running = {} self.event_buffer = {} def start(self): # pragma: no cover """ Executors may need to get things started. For example LocalExecutor starts N workers. """ pass def queue_command(self, key, command, priority=1, queue=None): if key not in self.queued_tasks and key not in self.running: logging.info("Adding to queue: " + command) self.queued_tasks[key] = (command, priority, queue) def queue_task_instance( self, task_instance, mark_success=False, pickle_id=None, force=False, ignore_dependencies=False, task_start_date=None): command = task_instance.command( local=True, mark_success=mark_success, force=force, ignore_dependencies=ignore_dependencies, task_start_date=task_start_date, pickle_id=pickle_id) self.queue_command( task_instance.key, command, priority=task_instance.task.priority_weight_total, queue=task_instance.task.queue) def sync(self): """ Sync will get called periodically by the heartbeat method. Executors should override this to perform gather statuses. """ pass def heartbeat(self): # Calling child class sync method logging.debug("Calling the {} sync method".format(self.__class__)) self.sync() # Triggering new jobs if not self.parallelism: open_slots = len(self.queued_tasks) else: open_slots = self.parallelism - len(self.running) logging.debug("{} running task instances".format(len(self.running))) logging.debug("{} in queue".format(len(self.queued_tasks))) logging.debug("{} open slots".format(open_slots)) sorted_queue = sorted( [(k, v) for k, v in self.queued_tasks.items()], key=lambda x: x[1][1], reverse=True) for i in range(min((open_slots, len(self.queued_tasks)))): key, (command, priority, queue) = sorted_queue.pop(0) self.running[key] = command del self.queued_tasks[key] self.execute_async(key, command=command, queue=queue) def change_state(self, key, state): del self.running[key] self.event_buffer[key] = state def fail(self, key): self.change_state(key, State.FAILED) def success(self, key): self.change_state(key, State.SUCCESS) def get_event_buffer(self): """ Returns and flush the event buffer """ d = self.event_buffer self.event_buffer = {} return d def execute_async(self, key, command, queue=None): # pragma: no cover """ This method will execute the command asynchronously. """ raise NotImplementedError() def end(self): # pragma: no cover """ This method is called when the caller is done submitting job and is wants to wait synchronously for the job submitted previously to be all done. """ raise NotImplementedError()
mengxn/tensorflow
refs/heads/master
tensorflow/python/platform/flags_test.py
79
# Copyright 2015 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 our flags implementation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import unittest from tensorflow.python.platform import app from tensorflow.python.platform import flags flags.DEFINE_string("string_foo", "default_val", "HelpString") flags.DEFINE_integer("int_foo", 42, "HelpString") flags.DEFINE_float("float_foo", 42.0, "HelpString") flags.DEFINE_boolean("bool_foo", True, "HelpString") flags.DEFINE_boolean("bool_negation", True, "HelpString") flags.DEFINE_boolean("bool-dash-negation", True, "HelpString") flags.DEFINE_boolean("bool_a", False, "HelpString") flags.DEFINE_boolean("bool_c", False, "HelpString") flags.DEFINE_boolean("bool_d", True, "HelpString") flags.DEFINE_bool("bool_e", True, "HelpString") FLAGS = flags.FLAGS class FlagsTest(unittest.TestCase): def testString(self): res = FLAGS.string_foo self.assertEqual(res, "default_val") FLAGS.string_foo = "bar" self.assertEqual("bar", FLAGS.string_foo) def testBool(self): res = FLAGS.bool_foo self.assertTrue(res) FLAGS.bool_foo = False self.assertFalse(FLAGS.bool_foo) def testBoolCommandLines(self): # Specified on command line with no args, sets to True, # even if default is False. self.assertEqual(True, FLAGS.bool_a) # --no before the flag forces it to False, even if the # default is True self.assertEqual(False, FLAGS.bool_negation) # --bool_flag=True sets to True self.assertEqual(True, FLAGS.bool_c) # --bool_flag=False sets to False self.assertEqual(False, FLAGS.bool_d) def testInt(self): res = FLAGS.int_foo self.assertEquals(res, 42) FLAGS.int_foo = -1 self.assertEqual(-1, FLAGS.int_foo) def testFloat(self): res = FLAGS.float_foo self.assertEquals(42.0, res) FLAGS.float_foo = -1.0 self.assertEqual(-1.0, FLAGS.float_foo) def main(_): # unittest.main() tries to interpret the unknown flags, so use the # direct functions instead. runner = unittest.TextTestRunner() itersuite = unittest.TestLoader().loadTestsFromTestCase(FlagsTest) runner.run(itersuite) if __name__ == "__main__": # Test command lines sys.argv.extend([ "--bool_a", "--nobool_negation", "--bool_c=True", "--bool_d=False", "and_argument" ]) app.run()
CiscoUcs/Ironic
refs/heads/master
build/lib/ironic/tests/__init__.py
16
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ :mod:`Ironic.tests` -- ironic Unittests ===================================================== .. automodule:: ironic.tests :platform: Unix """ # TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR import eventlet eventlet.monkey_patch(os=False) # See http://code.google.com/p/python-nose/issues/detail?id=373 # The code below enables nosetests to work with i18n _() blocks import six.moves.builtins as __builtin__ setattr(__builtin__, '_', lambda x: x)
JioCloud/keystone
refs/heads/master
keystone/tests/test_v3_auth.py
2
# Copyright 2012 OpenStack Foundation # # 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 copy import datetime import json import uuid from keystoneclient.common import cms from keystone import auth from keystone.common import dependency from keystone import config from keystone import exception from keystone.openstack.common import timeutils from keystone import tests from keystone.tests import test_v3 CONF = config.CONF class TestAuthInfo(test_v3.RestfulTestCase): # TODO(henry-nash) These tests are somewhat inefficient, since by # using the test_v3.RestfulTestCase class to gain access to the auth # building helper functions, they cause backend databases and fixtures # to be loaded unnecessarily. Separating out the helper functions from # this base class would improve efficiency (Bug #1134836) def test_missing_auth_methods(self): auth_data = {'identity': {}} auth_data['identity']['token'] = {'id': uuid.uuid4().hex} self.assertRaises(exception.ValidationError, auth.controllers.AuthInfo.create, None, auth_data) def test_unsupported_auth_method(self): auth_data = {'methods': ['abc']} auth_data['abc'] = {'test': 'test'} auth_data = {'identity': auth_data} self.assertRaises(exception.AuthMethodNotSupported, auth.controllers.AuthInfo.create, None, auth_data) def test_missing_auth_method_data(self): auth_data = {'methods': ['password']} auth_data = {'identity': auth_data} self.assertRaises(exception.ValidationError, auth.controllers.AuthInfo.create, None, auth_data) def test_project_name_no_domain(self): auth_data = self.build_authentication_request( username='test', password='test', project_name='abc')['auth'] self.assertRaises(exception.ValidationError, auth.controllers.AuthInfo.create, None, auth_data) def test_both_project_and_domain_in_scope(self): auth_data = self.build_authentication_request( user_id='test', password='test', project_name='test', domain_name='test')['auth'] self.assertRaises(exception.ValidationError, auth.controllers.AuthInfo.create, None, auth_data) def test_get_method_names_duplicates(self): auth_data = self.build_authentication_request( token='test', user_id='test', password='test')['auth'] auth_data['identity']['methods'] = ['password', 'token', 'password', 'password'] context = None auth_info = auth.controllers.AuthInfo.create(context, auth_data) self.assertEqual(auth_info.get_method_names(), ['password', 'token']) def test_get_method_data_invalid_method(self): auth_data = self.build_authentication_request( user_id='test', password='test')['auth'] context = None auth_info = auth.controllers.AuthInfo.create(context, auth_data) method_name = uuid.uuid4().hex self.assertRaises(exception.ValidationError, auth_info.get_method_data, method_name) class TokenAPITests(object): # Why is this not just setUP? Because TokenAPITests is not a test class # itself. If TokenAPITests became a subclass of the testcase, it would get # called by the enumerate-tests-in-file code. The way the functions get # resolved in Python for multiple inheritance means that a setUp in this # would get skipped by the testrunner. def doSetUp(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=self.domain_id, password=self.user['password']) resp = self.post('/auth/tokens', body=auth_data) self.token_data = resp.result self.token = resp.headers.get('X-Subject-Token') self.headers = {'X-Subject-Token': resp.headers.get('X-Subject-Token')} def test_default_fixture_scope_token(self): self.assertIsNotNone(self.get_scoped_token()) def verify_token(self, *args, **kwargs): return cms.verify_token(*args, **kwargs) def test_v3_token_id(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) resp = self.post('/auth/tokens', body=auth_data) token_data = resp.result token_id = resp.headers.get('X-Subject-Token') self.assertIn('expires_at', token_data['token']) decoded_token = self.verify_token(token_id, CONF.signing.certfile, CONF.signing.ca_certs) decoded_token_dict = json.loads(decoded_token) token_resp_dict = json.loads(resp.body) self.assertEqual(decoded_token_dict, token_resp_dict) # should be able to validate hash PKI token as well hash_token_id = cms.cms_hash_token(token_id) headers = {'X-Subject-Token': hash_token_id} resp = self.get('/auth/tokens', headers=headers) expected_token_data = resp.result self.assertDictEqual(expected_token_data, token_data) def test_v3_v2_intermix_non_default_domain_failed(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_intermix_new_default_domain(self): # If the default_domain_id config option is changed, then should be # able to validate a v3 token with user in the new domain. # 1) Create a new domain for the user. new_domain_id = uuid.uuid4().hex new_domain = { 'description': uuid.uuid4().hex, 'enabled': True, 'id': new_domain_id, 'name': uuid.uuid4().hex, } self.assignment_api.create_domain(new_domain_id, new_domain) # 2) Create user in new domain. new_user_id = uuid.uuid4().hex new_user_password = uuid.uuid4().hex new_user = { 'id': new_user_id, 'name': uuid.uuid4().hex, 'domain_id': new_domain_id, 'password': new_user_password, 'email': uuid.uuid4().hex, } self.identity_api.create_user(new_user_id, new_user) # 3) Update the default_domain_id config option to the new domain self.config_fixture.config(group='identity', default_domain_id=new_domain_id) # 4) Get a token using v3 api. auth_data = self.build_authentication_request( user_id=new_user_id, password=new_user_password) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # 5) Authenticate token using v2 api. path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET') def test_v3_v2_intermix_domain_scoped_token_failed(self): # grant the domain role to user path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_id=self.domain['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_intermix_non_default_project_failed(self): auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.project['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_unscoped_token_intermix(self): auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password']) resp = self.post('/auth/tokens', body=auth_data) token_data = resp.result token = resp.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET') v2_token = resp.result self.assertEqual(v2_token['access']['user']['id'], token_data['token']['user']['id']) # v2 token time has not fraction of second precision so # just need to make sure the non fraction part agrees self.assertIn(v2_token['access']['token']['expires'][:-1], token_data['token']['expires_at']) def test_v3_v2_token_intermix(self): # FIXME(gyee): PKI tokens are not interchangeable because token # data is baked into the token itself. auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.default_domain_project['id']) resp = self.post('/auth/tokens', body=auth_data) token_data = resp.result token = resp.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET') v2_token = resp.result self.assertEqual(v2_token['access']['user']['id'], token_data['token']['user']['id']) # v2 token time has not fraction of second precision so # just need to make sure the non fraction part agrees self.assertIn(v2_token['access']['token']['expires'][:-1], token_data['token']['expires_at']) self.assertEqual(v2_token['access']['user']['roles'][0]['id'], token_data['token']['roles'][0]['id']) def test_v3_v2_hashed_pki_token_intermix(self): auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.default_domain_project['id']) resp = self.post('/auth/tokens', body=auth_data) token_data = resp.result token = resp.headers.get('X-Subject-Token') # should be able to validate a hash PKI token in v2 too token = cms.cms_hash_token(token) path = '/v2.0/tokens/%s' % (token) resp = self.admin_request(path=path, token='ADMIN', method='GET') v2_token = resp.result self.assertEqual(v2_token['access']['user']['id'], token_data['token']['user']['id']) # v2 token time has not fraction of second precision so # just need to make sure the non fraction part agrees self.assertIn(v2_token['access']['token']['expires'][:-1], token_data['token']['expires_at']) self.assertEqual(v2_token['access']['user']['roles'][0]['id'], token_data['token']['roles'][0]['id']) def test_v2_v3_unscoped_token_intermix(self): body = { 'auth': { 'passwordCredentials': { 'userId': self.user['id'], 'password': self.user['password'] } }} resp = self.admin_request(path='/v2.0/tokens', method='POST', body=body) v2_token_data = resp.result v2_token = v2_token_data['access']['token']['id'] headers = {'X-Subject-Token': v2_token} resp = self.get('/auth/tokens', headers=headers) token_data = resp.result self.assertEqual(v2_token_data['access']['user']['id'], token_data['token']['user']['id']) # v2 token time has not fraction of second precision so # just need to make sure the non fraction part agrees self.assertIn(v2_token_data['access']['token']['expires'][-1], token_data['token']['expires_at']) def test_v2_v3_token_intermix(self): body = { 'auth': { 'passwordCredentials': { 'userId': self.user['id'], 'password': self.user['password'] }, 'tenantId': self.project['id'] }} resp = self.admin_request(path='/v2.0/tokens', method='POST', body=body) v2_token_data = resp.result v2_token = v2_token_data['access']['token']['id'] headers = {'X-Subject-Token': v2_token} resp = self.get('/auth/tokens', headers=headers) token_data = resp.result self.assertEqual(v2_token_data['access']['user']['id'], token_data['token']['user']['id']) # v2 token time has not fraction of second precision so # just need to make sure the non fraction part agrees self.assertIn(v2_token_data['access']['token']['expires'][-1], token_data['token']['expires_at']) self.assertEqual(v2_token_data['access']['user']['roles'][0]['name'], token_data['token']['roles'][0]['name']) v2_issued_at = timeutils.parse_isotime( v2_token_data['access']['token']['issued_at']) v3_issued_at = timeutils.parse_isotime( token_data['token']['issued_at']) self.assertEqual(v2_issued_at, v3_issued_at) def test_rescoping_token(self): expires = self.token_data['token']['expires_at'] auth_data = self.build_authentication_request( token=self.token, project_id=self.project_id) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectScopedTokenResponse(r) # make sure expires stayed the same self.assertEqual(expires, r.result['token']['expires_at']) def test_check_token(self): self.head('/auth/tokens', headers=self.headers, expected_status=200) def test_validate_token(self): r = self.get('/auth/tokens', headers=self.headers) self.assertValidUnscopedTokenResponse(r) def test_validate_token_nocatalog(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=self.project['id']) resp = self.post('/auth/tokens', body=auth_data) headers = {'X-Subject-Token': resp.headers.get('X-Subject-Token')} r = self.get('/auth/tokens?nocatalog', headers=headers) self.assertValidProjectScopedTokenResponse(r, require_catalog=False) class TestPKITokenAPIs(test_v3.RestfulTestCase, TokenAPITests): def config_overrides(self): super(TestPKITokenAPIs, self).config_overrides() self.config_fixture.config( group='token', provider='keystone.token.providers.pki.Provider') def setUp(self): super(TestPKITokenAPIs, self).setUp() self.doSetUp() class TestUUIDTokenAPIs(test_v3.RestfulTestCase, TokenAPITests): def config_overrides(self): super(TestUUIDTokenAPIs, self).config_overrides() self.config_fixture.config( group='token', provider='keystone.token.providers.uuid.Provider') def setUp(self): super(TestUUIDTokenAPIs, self).setUp() self.doSetUp() def test_v3_token_id(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) resp = self.post('/auth/tokens', body=auth_data) token_data = resp.result token_id = resp.headers.get('X-Subject-Token') self.assertIn('expires_at', token_data['token']) self.assertFalse(cms.is_ans1_token(token_id)) def test_v3_v2_hashed_pki_token_intermix(self): # this test is only applicable for PKI tokens # skipping it for UUID tokens pass class TestTokenRevokeSelfAndAdmin(test_v3.RestfulTestCase): """Test token revoke using v3 Identity API by token owner and admin.""" def setUp(self): """Setup for Test Cases. Two domains, domainA and domainB Two users in domainA, userNormalA and userAdminA One user in domainB, userAdminB """ super(TestTokenRevokeSelfAndAdmin, self).setUp() # DomainA setup self.domainA = self.new_domain_ref() self.assignment_api.create_domain(self.domainA['id'], self.domainA) self.userAdminA = self.new_user_ref(domain_id=self.domainA['id']) self.userAdminA['password'] = uuid.uuid4().hex self.identity_api.create_user(self.userAdminA['id'], self.userAdminA) self.userNormalA = self.new_user_ref( domain_id=self.domainA['id']) self.userNormalA['password'] = uuid.uuid4().hex self.identity_api.create_user(self.userNormalA['id'], self.userNormalA) self.role1 = self.new_role_ref() self.role1['name'] = 'admin' self.assignment_api.create_role(self.role1['id'], self.role1) self.assignment_api.create_grant(self.role1['id'], user_id=self.userAdminA['id'], domain_id=self.domainA['id']) # Finally, switch to the v3 sample policy file self.orig_policy_file = CONF.policy_file from keystone.policy.backends import rules rules.reset() def config_overrides(self): super(TestTokenRevokeSelfAndAdmin, self).config_overrides() self.config_fixture.config( policy_file=tests.dirs.etc('policy.v3cloudsample.json')) def test_user_revokes_own_token(self): r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userNormalA['id'], password=self.userNormalA['password'], user_domain_id=self.domainA['id'])) user_token = r.headers.get('X-Subject-Token') self.assertNotEmpty(user_token) headers = {'X-Subject-Token': user_token} r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userAdminA['id'], password=self.userAdminA['password'], domain_name=self.domainA['name'])) adminA_token = r.headers.get('X-Subject-Token') self.head('/auth/tokens', headers=headers, expected_status=200, token=adminA_token) self.head('/auth/tokens', headers=headers, expected_status=200, token=user_token) self.delete('/auth/tokens', headers=headers, expected_status=204, token=user_token) # invalid X-Auth-Token and invalid X-Subject-Token (401) self.head('/auth/tokens', headers=headers, expected_status=401, token=user_token) # invalid X-Auth-Token and invalid X-Subject-Token (401) self.delete('/auth/tokens', headers=headers, expected_status=401, token=user_token) # valid X-Auth-Token and invalid X-Subject-Token (404) self.delete('/auth/tokens', headers=headers, expected_status=404, token=adminA_token) # valid X-Auth-Token and invalid X-Subject-Token (404) self.head('/auth/tokens', headers=headers, expected_status=404, token=adminA_token) def test_adminA_revokes_userA_token(self): r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userNormalA['id'], password=self.userNormalA['password'], user_domain_id=self.domainA['id'])) user_token = r.headers.get('X-Subject-Token') self.assertNotEmpty(user_token) headers = {'X-Subject-Token': user_token} r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userAdminA['id'], password=self.userAdminA['password'], domain_name=self.domainA['name'])) adminA_token = r.headers.get('X-Subject-Token') self.head('/auth/tokens', headers=headers, expected_status=200, token=adminA_token) self.head('/auth/tokens', headers=headers, expected_status=200, token=user_token) self.delete('/auth/tokens', headers=headers, expected_status=204, token=adminA_token) # invalid X-Auth-Token and invalid X-Subject-Token (401) self.head('/auth/tokens', headers=headers, expected_status=401, token=user_token) # valid X-Auth-Token and invalid X-Subject-Token (404) self.delete('/auth/tokens', headers=headers, expected_status=404, token=adminA_token) # valid X-Auth-Token and invalid X-Subject-Token (404) self.head('/auth/tokens', headers=headers, expected_status=404, token=adminA_token) def test_adminB_fails_revoking_userA_token(self): # DomainB setup self.domainB = self.new_domain_ref() self.assignment_api.create_domain(self.domainB['id'], self.domainB) self.userAdminB = self.new_user_ref(domain_id=self.domainB['id']) self.userAdminB['password'] = uuid.uuid4().hex self.identity_api.create_user(self.userAdminB['id'], self.userAdminB) self.assignment_api.create_grant(self.role1['id'], user_id=self.userAdminB['id'], domain_id=self.domainB['id']) r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userNormalA['id'], password=self.userNormalA['password'], user_domain_id=self.domainA['id'])) user_token = r.headers.get('X-Subject-Token') headers = {'X-Subject-Token': user_token} r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.userAdminB['id'], password=self.userAdminB['password'], domain_name=self.domainB['name'])) adminB_token = r.headers.get('X-Subject-Token') self.head('/auth/tokens', headers=headers, expected_status=403, token=adminB_token) self.delete('/auth/tokens', headers=headers, expected_status=403, token=adminB_token) @dependency.requires('revoke_api') class TestTokenRevokeById(test_v3.RestfulTestCase): """Test token revocation on the v3 Identity API.""" def config_overrides(self): super(TestTokenRevokeById, self).config_overrides() self.config_fixture.config( group='revoke', driver='keystone.contrib.revoke.backends.kvs.Revoke') self.config_fixture.config( group='token', provider='keystone.token.providers.pki.Provider', revoke_by_id=False) def setUp(self): """Setup for Token Revoking Test Cases. As well as the usual housekeeping, create a set of domains, users, groups, roles and projects for the subsequent tests: - Two domains: A & B - Three users (1, 2 and 3) - Three groups (1, 2 and 3) - Two roles (1 and 2) - DomainA owns user1, domainB owns user2 and user3 - DomainA owns group1 and group2, domainB owns group3 - User1 and user2 are members of group1 - User3 is a member of group2 - Two projects: A & B, both in domainA - Group1 has role1 on Project A and B, meaning that user1 and user2 will get these roles by virtue of membership - User1, 2 and 3 have role1 assigned to projectA - Group1 has role1 on Project A and B, meaning that user1 and user2 will get role1 (duplicated) by virtue of membership - User1 has role2 assigned to domainA """ super(TestTokenRevokeById, self).setUp() # Start by creating a couple of domains and projects self.domainA = self.new_domain_ref() self.assignment_api.create_domain(self.domainA['id'], self.domainA) self.domainB = self.new_domain_ref() self.assignment_api.create_domain(self.domainB['id'], self.domainB) self.projectA = self.new_project_ref(domain_id=self.domainA['id']) self.assignment_api.create_project(self.projectA['id'], self.projectA) self.projectB = self.new_project_ref(domain_id=self.domainA['id']) self.assignment_api.create_project(self.projectB['id'], self.projectB) # Now create some users self.user1 = self.new_user_ref( domain_id=self.domainA['id']) self.user1['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user1['id'], self.user1) self.user2 = self.new_user_ref( domain_id=self.domainB['id']) self.user2['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user2['id'], self.user2) self.user3 = self.new_user_ref( domain_id=self.domainB['id']) self.user3['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user3['id'], self.user3) self.group1 = self.new_group_ref( domain_id=self.domainA['id']) self.identity_api.create_group(self.group1['id'], self.group1) self.group2 = self.new_group_ref( domain_id=self.domainA['id']) self.identity_api.create_group(self.group2['id'], self.group2) self.group3 = self.new_group_ref( domain_id=self.domainB['id']) self.identity_api.create_group(self.group3['id'], self.group3) self.identity_api.add_user_to_group(self.user1['id'], self.group1['id']) self.identity_api.add_user_to_group(self.user2['id'], self.group1['id']) self.identity_api.add_user_to_group(self.user3['id'], self.group2['id']) self.role1 = self.new_role_ref() self.assignment_api.create_role(self.role1['id'], self.role1) self.role2 = self.new_role_ref() self.assignment_api.create_role(self.role2['id'], self.role2) self.assignment_api.create_grant(self.role2['id'], user_id=self.user1['id'], domain_id=self.domainA['id']) self.assignment_api.create_grant(self.role1['id'], user_id=self.user1['id'], project_id=self.projectA['id']) self.assignment_api.create_grant(self.role1['id'], user_id=self.user2['id'], project_id=self.projectA['id']) self.assignment_api.create_grant(self.role1['id'], user_id=self.user3['id'], project_id=self.projectA['id']) self.assignment_api.create_grant(self.role1['id'], group_id=self.group1['id'], project_id=self.projectA['id']) def test_unscoped_token_remains_valid_after_role_assignment(self): r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'])) unscoped_token = r.headers.get('X-Subject-Token') r = self.post( '/auth/tokens', body=self.build_authentication_request( token=unscoped_token, project_id=self.projectA['id'])) scoped_token = r.headers.get('X-Subject-Token') # confirm both tokens are valid self.head('/auth/tokens', headers={'X-Subject-Token': unscoped_token}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': scoped_token}, expected_status=200) # create a new role role = self.new_role_ref() self.assignment_api.create_role(role['id'], role) # assign a new role self.put( '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % { 'project_id': self.projectA['id'], 'user_id': self.user1['id'], 'role_id': role['id']}) # both tokens should remain valid self.head('/auth/tokens', headers={'X-Subject-Token': unscoped_token}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': scoped_token}, expected_status=200) def test_deleting_user_grant_revokes_token(self): """Test deleting a user grant revokes token. Test Plan: - Get a token for user1, scoped to ProjectA - Delete the grant user1 has on ProjectA - Check token is no longer valid """ auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # Confirm token is valid self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) # Delete the grant, which should invalidate the token grant_url = ( '/projects/%(project_id)s/users/%(user_id)s/' 'roles/%(role_id)s' % { 'project_id': self.projectA['id'], 'user_id': self.user1['id'], 'role_id': self.role1['id']}) self.delete(grant_url) self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=404) def role_data_fixtures(self): self.projectC = self.new_project_ref(domain_id=self.domainA['id']) self.assignment_api.create_project(self.projectC['id'], self.projectC) self.user4 = self.new_user_ref(domain_id=self.domainB['id']) self.user4['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user4['id'], self.user4) self.user5 = self.new_user_ref( domain_id=self.domainA['id']) self.user5['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user5['id'], self.user5) self.user6 = self.new_user_ref( domain_id=self.domainA['id']) self.user6['password'] = uuid.uuid4().hex self.identity_api.create_user(self.user6['id'], self.user6) self.identity_api.add_user_to_group(self.user5['id'], self.group1['id']) self.assignment_api.create_grant(self.role1['id'], group_id=self.group1['id'], project_id=self.projectB['id']) self.assignment_api.create_grant(self.role2['id'], user_id=self.user4['id'], project_id=self.projectC['id']) self.assignment_api.create_grant(self.role1['id'], user_id=self.user6['id'], project_id=self.projectA['id']) self.assignment_api.create_grant(self.role1['id'], user_id=self.user6['id'], domain_id=self.domainA['id']) def test_deleting_role_revokes_token(self): """Test deleting a role revokes token. Add some additional test data, namely: - A third project (project C) - Three additional users - user4 owned by domainB and user5 and 6 owned by domainA (different domain ownership should not affect the test results, just provided to broaden test coverage) - User5 is a member of group1 - Group1 gets an additional assignment - role1 on projectB as well as its existing role1 on projectA - User4 has role2 on Project C - User6 has role1 on projectA and domainA - This allows us to create 5 tokens by virtue of different types of role assignment: - user1, scoped to ProjectA by virtue of user role1 assignment - user5, scoped to ProjectB by virtue of group role1 assignment - user4, scoped to ProjectC by virtue of user role2 assignment - user6, scoped to ProjectA by virtue of user role1 assignment - user6, scoped to DomainA by virtue of user role1 assignment - role1 is then deleted - Check the tokens on Project A and B, and DomainA are revoked, but not the one for Project C """ self.role_data_fixtures() # Now we are ready to start issuing requests auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) tokenA = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user5['id'], password=self.user5['password'], project_id=self.projectB['id']) resp = self.post('/auth/tokens', body=auth_data) tokenB = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user4['id'], password=self.user4['password'], project_id=self.projectC['id']) resp = self.post('/auth/tokens', body=auth_data) tokenC = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user6['id'], password=self.user6['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) tokenD = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user6['id'], password=self.user6['password'], domain_id=self.domainA['id']) resp = self.post('/auth/tokens', body=auth_data) tokenE = resp.headers.get('X-Subject-Token') # Confirm tokens are valid self.head('/auth/tokens', headers={'X-Subject-Token': tokenA}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': tokenB}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': tokenC}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': tokenD}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': tokenE}, expected_status=200) # Delete the role, which should invalidate the tokens role_url = '/roles/%s' % self.role1['id'] self.delete(role_url) # Check the tokens that used role1 is invalid self.head('/auth/tokens', headers={'X-Subject-Token': tokenA}, expected_status=404) self.head('/auth/tokens', headers={'X-Subject-Token': tokenB}, expected_status=404) self.head('/auth/tokens', headers={'X-Subject-Token': tokenD}, expected_status=404) self.head('/auth/tokens', headers={'X-Subject-Token': tokenE}, expected_status=404) # ...but the one using role2 is still valid self.head('/auth/tokens', headers={'X-Subject-Token': tokenC}, expected_status=200) def test_domain_user_role_assignment_maintains_token(self): """Test user-domain role assignment maintains existing token. Test Plan: - Get a token for user1, scoped to ProjectA - Create a grant for user1 on DomainB - Check token is still valid """ auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # Confirm token is valid self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) # Assign a role, which should not affect the token grant_url = ( '/domains/%(domain_id)s/users/%(user_id)s/' 'roles/%(role_id)s' % { 'domain_id': self.domainB['id'], 'user_id': self.user1['id'], 'role_id': self.role1['id']}) self.put(grant_url) self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) def test_disabling_project_revokes_token(self): resp = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id'])) token = resp.headers.get('X-Subject-Token') # confirm token is valid self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) # disable the project, which should invalidate the token self.patch( '/projects/%(project_id)s' % {'project_id': self.projectA['id']}, body={'project': {'enabled': False}}) # user should no longer have access to the project self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=404) resp = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id']), expected_status=401) def test_deleting_project_revokes_token(self): resp = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id'])) token = resp.headers.get('X-Subject-Token') # confirm token is valid self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) # delete the project, which should invalidate the token self.delete( '/projects/%(project_id)s' % {'project_id': self.projectA['id']}) # user should no longer have access to the project self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=404) resp = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id']), expected_status=401) def test_deleting_group_grant_revokes_tokens(self): """Test deleting a group grant revokes tokens. Test Plan: - Get a token for user1, scoped to ProjectA - Get a token for user2, scoped to ProjectA - Get a token for user3, scoped to ProjectA - Delete the grant group1 has on ProjectA - Check tokens for user1 & user2 are no longer valid, since user1 and user2 are members of group1 - Check token for user3 is still valid """ auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token1 = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user2['id'], password=self.user2['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token2 = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token3 = resp.headers.get('X-Subject-Token') # Confirm tokens are valid self.head('/auth/tokens', headers={'X-Subject-Token': token1}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': token2}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': token3}, expected_status=200) # Delete the group grant, which should invalidate the # tokens for user1 and user2 grant_url = ( '/projects/%(project_id)s/groups/%(group_id)s/' 'roles/%(role_id)s' % { 'project_id': self.projectA['id'], 'group_id': self.group1['id'], 'role_id': self.role1['id']}) self.delete(grant_url) self.head('/auth/tokens', headers={'X-Subject-Token': token1}, expected_status=404) self.head('/auth/tokens', headers={'X-Subject-Token': token2}, expected_status=404) # But user3's token should still be valid self.head('/auth/tokens', headers={'X-Subject-Token': token3}, expected_status=200) def test_domain_group_role_assignment_maintains_token(self): """Test domain-group role assignment maintains existing token. Test Plan: - Get a token for user1, scoped to ProjectA - Create a grant for group1 on DomainB - Check token is still longer valid """ auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') # Confirm token is valid self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) # Delete the grant, which should invalidate the token grant_url = ( '/domains/%(domain_id)s/groups/%(group_id)s/' 'roles/%(role_id)s' % { 'domain_id': self.domainB['id'], 'group_id': self.group1['id'], 'role_id': self.role1['id']}) self.put(grant_url) self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=200) def test_group_membership_changes_revokes_token(self): """Test add/removal to/from group revokes token. Test Plan: - Get a token for user1, scoped to ProjectA - Get a token for user2, scoped to ProjectA - Remove user1 from group1 - Check token for user1 is no longer valid - Check token for user2 is still valid, even though user2 is also part of group1 - Add user2 to group2 - Check token for user2 is now no longer valid """ auth_data = self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token1 = resp.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( user_id=self.user2['id'], password=self.user2['password'], project_id=self.projectA['id']) resp = self.post('/auth/tokens', body=auth_data) token2 = resp.headers.get('X-Subject-Token') # Confirm tokens are valid self.head('/auth/tokens', headers={'X-Subject-Token': token1}, expected_status=200) self.head('/auth/tokens', headers={'X-Subject-Token': token2}, expected_status=200) # Remove user1 from group1, which should invalidate # the token self.delete('/groups/%(group_id)s/users/%(user_id)s' % { 'group_id': self.group1['id'], 'user_id': self.user1['id']}) self.head('/auth/tokens', headers={'X-Subject-Token': token1}, expected_status=404) # But user2's token should still be valid self.head('/auth/tokens', headers={'X-Subject-Token': token2}, expected_status=200) # Adding user2 to a group should not invalidate token self.put('/groups/%(group_id)s/users/%(user_id)s' % { 'group_id': self.group2['id'], 'user_id': self.user2['id']}) self.head('/auth/tokens', headers={'X-Subject-Token': token2}, expected_status=200) def test_removing_role_assignment_does_not_affect_other_users(self): """Revoking a role from one user should not affect other users.""" r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])) user1_token = r.headers.get('X-Subject-Token') r = self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id'])) user3_token = r.headers.get('X-Subject-Token') # delete relationships between user1 and projectA from setUp self.delete( '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % { 'project_id': self.projectA['id'], 'user_id': self.user1['id'], 'role_id': self.role1['id']}) self.delete( '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' % {'project_id': self.projectA['id'], 'group_id': self.group1['id'], 'role_id': self.role1['id']}) # authorization for the first user should now fail self.head('/auth/tokens', headers={'X-Subject-Token': user1_token}, expected_status=404) self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id']), expected_status=401) # authorization for the second user should still succeed self.head('/auth/tokens', headers={'X-Subject-Token': user3_token}, expected_status=200) self.post( '/auth/tokens', body=self.build_authentication_request( user_id=self.user3['id'], password=self.user3['password'], project_id=self.projectA['id'])) def test_deleting_project_deletes_grants(self): # This is to make it a little bit more pretty with PEP8 role_path = ('/projects/%(project_id)s/users/%(user_id)s/' 'roles/%(role_id)s') role_path = role_path % {'user_id': self.user['id'], 'project_id': self.projectA['id'], 'role_id': self.role['id']} # grant the user a role on the project self.put(role_path) # delete the project, which should remove the roles self.delete( '/projects/%(project_id)s' % {'project_id': self.projectA['id']}) # Make sure that we get a NotFound(404) when heading that role. self.head(role_path, expected_status=404) def get_v2_token(self, token=None, project_id=None): body = {'auth': {}, } if token: body['auth']['token'] = { 'id': token } else: body['auth']['passwordCredentials'] = { 'username': self.default_domain_user['name'], 'password': self.default_domain_user['password'], } if project_id: body['auth']['tenantId'] = project_id r = self.admin_request(method='POST', path='/v2.0/tokens', body=body) return r.json_body['access']['token']['id'] def test_revoke_v2_token_no_check(self): # Test that a V2 token can be revoked without validating it first. token = self.get_v2_token() self.delete('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=204) self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_status=404) def test_revoke_token_from_token(self): # Test that a scoped token can be requested from an unscoped token, # the scoped token can be revoked, and the unscoped token remains # valid. unscoped_token = self.get_requested_token( self.build_authentication_request( user_id=self.user1['id'], password=self.user1['password'])) # Get a project-scoped token from the unscoped token project_scoped_token = self.get_requested_token( self.build_authentication_request( token=unscoped_token, project_id=self.projectA['id'])) # Get a domain-scoped token from the unscoped token domain_scoped_token = self.get_requested_token( self.build_authentication_request( token=unscoped_token, domain_id=self.domainA['id'])) # revoke the project-scoped token. self.delete('/auth/tokens', headers={'X-Subject-Token': project_scoped_token}, expected_status=204) # The project-scoped token is invalidated. self.head('/auth/tokens', headers={'X-Subject-Token': project_scoped_token}, expected_status=404) # The unscoped token should still be valid. self.head('/auth/tokens', headers={'X-Subject-Token': unscoped_token}, expected_status=200) # The domain-scoped token should still be valid. self.head('/auth/tokens', headers={'X-Subject-Token': domain_scoped_token}, expected_status=200) # revoke the domain-scoped token. self.delete('/auth/tokens', headers={'X-Subject-Token': domain_scoped_token}, expected_status=204) # The domain-scoped token is invalid. self.head('/auth/tokens', headers={'X-Subject-Token': domain_scoped_token}, expected_status=404) # The unscoped token should still be valid. self.head('/auth/tokens', headers={'X-Subject-Token': unscoped_token}, expected_status=200) def test_revoke_token_from_token_v2(self): # Test that a scoped token can be requested from an unscoped token, # the scoped token can be revoked, and the unscoped token remains # valid. # FIXME(blk-u): This isn't working correctly. The scoped token should # be revoked. See bug 1347318. unscoped_token = self.get_v2_token() # Get a project-scoped token from the unscoped token project_scoped_token = self.get_v2_token( token=unscoped_token, project_id=self.default_domain_project['id']) # revoke the project-scoped token. self.delete('/auth/tokens', headers={'X-Subject-Token': project_scoped_token}, expected_status=204) # The project-scoped token is invalidated. self.head('/auth/tokens', headers={'X-Subject-Token': project_scoped_token}, expected_status=404) # The unscoped token should still be valid. self.head('/auth/tokens', headers={'X-Subject-Token': unscoped_token}, expected_status=200) @dependency.requires('revoke_api') class TestTokenRevokeApi(TestTokenRevokeById): EXTENSION_NAME = 'revoke' EXTENSION_TO_ADD = 'revoke_extension' """Test token revocation on the v3 Identity API.""" def config_overrides(self): super(TestTokenRevokeApi, self).config_overrides() self.config_fixture.config( group='revoke', driver='keystone.contrib.revoke.backends.kvs.Revoke') self.config_fixture.config( group='token', provider='keystone.token.providers.pki.Provider', revoke_by_id=False) def assertValidDeletedProjectResponse(self, events_response, project_id): events = events_response['events'] self.assertEqual(1, len(events)) self.assertEqual(project_id, events[0]['project_id']) self.assertIsNotNone(events[0]['issued_before']) self.assertIsNotNone(events_response['links']) del (events_response['events'][0]['issued_before']) del (events_response['links']) expected_response = {'events': [{'project_id': project_id}]} self.assertEqual(expected_response, events_response) def assertDomainInList(self, events_response, domain_id): events = events_response['events'] self.assertEqual(1, len(events)) self.assertEqual(domain_id, events[0]['domain_id']) self.assertIsNotNone(events[0]['issued_before']) self.assertIsNotNone(events_response['links']) del (events_response['events'][0]['issued_before']) del (events_response['links']) expected_response = {'events': [{'domain_id': domain_id}]} self.assertEqual(expected_response, events_response) def assertValidRevokedTokenResponse(self, events_response, user_id, project_id=None): events = events_response['events'] self.assertEqual(1, len(events)) self.assertEqual(user_id, events[0]['user_id']) if project_id: self.assertEqual(project_id, events[0]['project_id']) self.assertIsNotNone(events[0]['expires_at']) self.assertIsNotNone(events[0]['issued_before']) self.assertIsNotNone(events_response['links']) del (events_response['events'][0]['expires_at']) del (events_response['events'][0]['issued_before']) del (events_response['links']) expected_event_data = {'user_id': user_id} if project_id: expected_event_data['project_id'] = project_id expected_response = {'events': [expected_event_data]} self.assertEqual(expected_response, events_response) def test_revoke_token(self): scoped_token = self.get_scoped_token() headers = {'X-Subject-Token': scoped_token} self.head('/auth/tokens', headers=headers, expected_status=200) self.delete('/auth/tokens', headers=headers, expected_status=204) self.head('/auth/tokens', headers=headers, expected_status=404) events_response = self.get('/OS-REVOKE/events', expected_status=200).json_body self.assertValidRevokedTokenResponse(events_response, self.user['id'], project_id=self.project['id']) def test_revoke_v2_token(self): token = self.get_v2_token() headers = {'X-Subject-Token': token} self.head('/auth/tokens', headers=headers, expected_status=200) self.delete('/auth/tokens', headers=headers, expected_status=204) self.head('/auth/tokens', headers=headers, expected_status=404) events_response = self.get('/OS-REVOKE/events', expected_status=200).json_body self.assertValidRevokedTokenResponse(events_response, self.default_domain_user['id']) def test_revoke_by_id_false_410(self): self.get('/auth/tokens/OS-PKI/revoked', expected_status=410) def test_list_delete_project_shows_in_event_list(self): self.role_data_fixtures() events = self.get('/OS-REVOKE/events', expected_status=200).json_body['events'] self.assertEqual([], events) self.delete( '/projects/%(project_id)s' % {'project_id': self.projectA['id']}) events_response = self.get('/OS-REVOKE/events', expected_status=200).json_body self.assertValidDeletedProjectResponse(events_response, self.projectA['id']) def test_disable_domain_shows_in_event_list(self): events = self.get('/OS-REVOKE/events', expected_status=200).json_body['events'] self.assertEqual([], events) disable_body = {'domain': {'enabled': False}} self.patch( '/domains/%(project_id)s' % {'project_id': self.domainA['id']}, body=disable_body) events = self.get('/OS-REVOKE/events', expected_status=200).json_body self.assertDomainInList(events, self.domainA['id']) def assertUserAndExpiryInList(self, events, user_id, expires_at): found = False for e in events: # Timestamps in the event list are accurate to second. expires_at = timeutils.parse_isotime(expires_at) expires_at = timeutils.isotime(expires_at) if e['user_id'] == user_id and e['expires_at'] == expires_at: found = True self.assertTrue(found, 'event with correct user_id %s and expires_at value ' 'not in list' % user_id) def test_list_delete_token_shows_in_event_list(self): self.role_data_fixtures() events = self.get('/OS-REVOKE/events', expected_status=200).json_body['events'] self.assertEqual([], events) scoped_token = self.get_scoped_token() headers = {'X-Subject-Token': scoped_token} auth_req = self.build_authentication_request(token=scoped_token) response = self.post('/auth/tokens', body=auth_req) token2 = response.json_body['token'] headers2 = {'X-Subject-Token': response.headers['X-Subject-Token']} response = self.post('/auth/tokens', body=auth_req) response.json_body['token'] headers3 = {'X-Subject-Token': response.headers['X-Subject-Token']} self.head('/auth/tokens', headers=headers, expected_status=200) self.head('/auth/tokens', headers=headers2, expected_status=200) self.head('/auth/tokens', headers=headers3, expected_status=200) self.delete('/auth/tokens', headers=headers, expected_status=204) # NOTE(ayoung): not deleting token3, as it should be deleted # by previous events_response = self.get('/OS-REVOKE/events', expected_status=200).json_body events = events_response['events'] self.assertEqual(1, len(events)) self.assertUserAndExpiryInList(events, token2['user']['id'], token2['expires_at']) self.assertValidRevokedTokenResponse(events_response, self.user['id'], project_id=self.project['id']) self.head('/auth/tokens', headers=headers, expected_status=404) self.head('/auth/tokens', headers=headers2, expected_status=200) self.head('/auth/tokens', headers=headers3, expected_status=200) def test_list_with_filter(self): self.role_data_fixtures() events = self.get('/OS-REVOKE/events', expected_status=200).json_body['events'] self.assertEqual(0, len(events)) scoped_token = self.get_scoped_token() headers = {'X-Subject-Token': scoped_token} auth = self.build_authentication_request(token=scoped_token) response = self.post('/auth/tokens', body=auth) headers2 = {'X-Subject-Token': response.headers['X-Subject-Token']} self.delete('/auth/tokens', headers=headers, expected_status=204) self.delete('/auth/tokens', headers=headers2, expected_status=204) events = self.get('/OS-REVOKE/events', expected_status=200).json_body['events'] self.assertEqual(2, len(events)) future = timeutils.isotime(timeutils.utcnow() + datetime.timedelta(seconds=1000)) events = self.get('/OS-REVOKE/events?since=%s' % (future), expected_status=200).json_body['events'] self.assertEqual(0, len(events)) class TestAuthExternalDisabled(test_v3.RestfulTestCase): def config_overrides(self): super(TestAuthExternalDisabled, self).config_overrides() self.config_fixture.config( group='auth', methods=['keystone.auth.plugins.password.Password', 'keystone.auth.plugins.token.Token']) def test_remote_user_disabled(self): api = auth.controllers.Auth() remote_user = '%s@%s' % (self.user['name'], self.domain['name']) context, auth_info, auth_context = self.build_external_auth_request( remote_user) self.assertRaises(exception.Unauthorized, api.authenticate, context, auth_info, auth_context) class TestAuthExternalLegacyDefaultDomain(test_v3.RestfulTestCase): content_type = 'json' def config_overrides(self): super(TestAuthExternalLegacyDefaultDomain, self).config_overrides() self.config_fixture.config( group='auth', methods=['keystone.auth.plugins.external.LegacyDefaultDomain', 'keystone.auth.plugins.password.Password', 'keystone.auth.plugins.token.Token']) def test_remote_user_no_realm(self): CONF.auth.methods = 'external' api = auth.controllers.Auth() context, auth_info, auth_context = self.build_external_auth_request( self.default_domain_user['name']) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.default_domain_user['id']) def test_remote_user_no_domain(self): api = auth.controllers.Auth() context, auth_info, auth_context = self.build_external_auth_request( self.user['name']) self.assertRaises(exception.Unauthorized, api.authenticate, context, auth_info, auth_context) class TestAuthExternalLegacyDomain(test_v3.RestfulTestCase): content_type = 'json' def config_overrides(self): super(TestAuthExternalLegacyDomain, self).config_overrides() self.config_fixture.config( group='auth', methods=['keystone.auth.plugins.external.LegacyDomain', 'keystone.auth.plugins.password.Password', 'keystone.auth.plugins.token.Token']) def test_remote_user_with_realm(self): api = auth.controllers.Auth() remote_user = '%s@%s' % (self.user['name'], self.domain['name']) context, auth_info, auth_context = self.build_external_auth_request( remote_user) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.user['id']) # Now test to make sure the user name can, itself, contain the # '@' character. user = {'name': 'myname@mydivision'} self.identity_api.update_user(self.user['id'], user) remote_user = '%s@%s' % (user['name'], self.domain['name']) context, auth_info, auth_context = self.build_external_auth_request( remote_user) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.user['id']) def test_project_id_scoped_with_remote_user(self): CONF.token.bind = ['kerberos'] auth_data = self.build_authentication_request( project_id=self.project['id']) remote_user = '%s@%s' % (self.user['name'], self.domain['name']) self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidProjectScopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], self.user['name']) def test_unscoped_bind_with_remote_user(self): CONF.token.bind = ['kerberos'] auth_data = self.build_authentication_request() remote_user = '%s@%s' % (self.user['name'], self.domain['name']) self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidUnscopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], self.user['name']) class TestAuthExternalDomain(test_v3.RestfulTestCase): content_type = 'json' def config_overrides(self): super(TestAuthExternalDomain, self).config_overrides() self.config_fixture.config( group='auth', methods=['keystone.auth.plugins.external.Domain', 'keystone.auth.plugins.password.Password', 'keystone.auth.plugins.token.Token']) def test_remote_user_with_realm(self): api = auth.controllers.Auth() remote_user = self.user['name'] remote_domain = self.domain['name'] context, auth_info, auth_context = self.build_external_auth_request( remote_user, remote_domain=remote_domain) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.user['id']) # Now test to make sure the user name can, itself, contain the # '@' character. user = {'name': 'myname@mydivision'} self.identity_api.update_user(self.user['id'], user) remote_user = user['name'] context, auth_info, auth_context = self.build_external_auth_request( remote_user, remote_domain=remote_domain) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.user['id']) def test_project_id_scoped_with_remote_user(self): CONF.token.bind = ['kerberos'] auth_data = self.build_authentication_request( project_id=self.project['id']) remote_user = self.user['name'] remote_domain = self.domain['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'REMOTE_DOMAIN': remote_domain, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidProjectScopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], self.user['name']) def test_unscoped_bind_with_remote_user(self): CONF.token.bind = ['kerberos'] auth_data = self.build_authentication_request() remote_user = self.user['name'] remote_domain = self.domain['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'REMOTE_DOMAIN': remote_domain, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidUnscopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], self.user['name']) class TestAuthJSON(test_v3.RestfulTestCase): content_type = 'json' def test_unscoped_token_with_user_id(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_unscoped_token_with_user_domain_id(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=self.domain['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_unscoped_token_with_user_domain_name(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_name=self.domain['name'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_project_id_scoped_token_with_user_id(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectScopedTokenResponse(r) def test_default_project_id_scoped_token_with_user_id(self): # create a second project to work with ref = self.new_project_ref(domain_id=self.domain_id) r = self.post('/projects', body={'project': ref}) project = self.assertValidProjectResponse(r, ref) # grant the user a role on the project self.put( '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % { 'user_id': self.user['id'], 'project_id': project['id'], 'role_id': self.role['id']}) # set the user's preferred project body = {'user': {'default_project_id': project['id']}} r = self.patch('/users/%(user_id)s' % { 'user_id': self.user['id']}, body=body) self.assertValidUserResponse(r) # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectScopedTokenResponse(r) self.assertEqual(r.result['token']['project']['id'], project['id']) def test_default_project_id_scoped_token_with_user_id_no_catalog(self): # create a second project to work with ref = self.new_project_ref(domain_id=self.domain_id) r = self.post('/projects', body={'project': ref}) project = self.assertValidProjectResponse(r, ref) # grant the user a role on the project self.put( '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % { 'user_id': self.user['id'], 'project_id': project['id'], 'role_id': self.role['id']}) # set the user's preferred project body = {'user': {'default_project_id': project['id']}} r = self.patch('/users/%(user_id)s' % { 'user_id': self.user['id']}, body=body) self.assertValidUserResponse(r) # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens?nocatalog', body=auth_data) self.assertValidProjectScopedTokenResponse(r, require_catalog=False) self.assertEqual(r.result['token']['project']['id'], project['id']) def test_implicit_project_id_scoped_token_with_user_id_no_catalog(self): # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens?nocatalog', body=auth_data) self.assertValidProjectScopedTokenResponse(r, require_catalog=False) self.assertEqual(r.result['token']['project']['id'], self.project['id']) def _check_disabled_endpoint_result(self, catalog, disabled_endpoint_id): endpoints = catalog[0]['endpoints'] endpoint_ids = [ep['id'] for ep in endpoints] self.assertEqual([self.endpoint_id], endpoint_ids) def test_auth_catalog_disabled_service(self): """On authenticate, get a catalog that excludes disabled services.""" # although the child endpoint is enabled, the service is disabled self.assertTrue(self.endpoint['enabled']) self.catalog_api.update_service( self.endpoint['service_id'], {'enabled': False}) service = self.catalog_api.get_service(self.endpoint['service_id']) self.assertFalse(service['enabled']) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens', body=auth_data) # In JSON, this is an empty list. In XML, this is an empty string. self.assertFalse(r.result['token']['catalog']) def test_auth_catalog_disabled_endpoint(self): """On authenticate, get a catalog that excludes disabled endpoints.""" # Create a disabled endpoint that's like the enabled one. disabled_endpoint_ref = copy.copy(self.endpoint) disabled_endpoint_id = uuid.uuid4().hex disabled_endpoint_ref.update({ 'id': disabled_endpoint_id, 'enabled': False, 'interface': 'internal' }) self.catalog_api.create_endpoint(disabled_endpoint_id, disabled_endpoint_ref) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens', body=auth_data) self._check_disabled_endpoint_result(r.result['token']['catalog'], disabled_endpoint_id) def test_project_id_scoped_token_with_user_id_401(self): project_id = uuid.uuid4().hex project = self.new_project_ref(domain_id=self.domain_id) self.assignment_api.create_project(project_id, project) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=project['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_user_and_group_roles_scoped_token(self): """Test correct roles are returned in scoped token. Test Plan: - Create a domain, with 1 project, 2 users (user1 and user2) and 2 groups (group1 and group2) - Make user1 a member of group1, user2 a member of group2 - Create 8 roles, assigning them to each of the 8 combinations of users/groups on domain/project - Get a project scoped token for user1, checking that the right two roles are returned (one directly assigned, one by virtue of group membership) - Repeat this for a domain scoped token - Make user1 also a member of group2 - Get another scoped token making sure the additional role shows up - User2 is just here as a spoiler, to make sure we don't get any roles uniquely assigned to it returned in any of our tokens """ domainA = self.new_domain_ref() self.assignment_api.create_domain(domainA['id'], domainA) projectA = self.new_project_ref(domain_id=domainA['id']) self.assignment_api.create_project(projectA['id'], projectA) user1 = self.new_user_ref( domain_id=domainA['id']) user1['password'] = uuid.uuid4().hex self.identity_api.create_user(user1['id'], user1) user2 = self.new_user_ref( domain_id=domainA['id']) user2['password'] = uuid.uuid4().hex self.identity_api.create_user(user2['id'], user2) group1 = self.new_group_ref( domain_id=domainA['id']) self.identity_api.create_group(group1['id'], group1) group2 = self.new_group_ref( domain_id=domainA['id']) self.identity_api.create_group(group2['id'], group2) self.identity_api.add_user_to_group(user1['id'], group1['id']) self.identity_api.add_user_to_group(user2['id'], group2['id']) # Now create all the roles and assign them role_list = [] for _ in range(8): role = self.new_role_ref() self.assignment_api.create_role(role['id'], role) role_list.append(role) self.assignment_api.create_grant(role_list[0]['id'], user_id=user1['id'], domain_id=domainA['id']) self.assignment_api.create_grant(role_list[1]['id'], user_id=user1['id'], project_id=projectA['id']) self.assignment_api.create_grant(role_list[2]['id'], user_id=user2['id'], domain_id=domainA['id']) self.assignment_api.create_grant(role_list[3]['id'], user_id=user2['id'], project_id=projectA['id']) self.assignment_api.create_grant(role_list[4]['id'], group_id=group1['id'], domain_id=domainA['id']) self.assignment_api.create_grant(role_list[5]['id'], group_id=group1['id'], project_id=projectA['id']) self.assignment_api.create_grant(role_list[6]['id'], group_id=group2['id'], domain_id=domainA['id']) self.assignment_api.create_grant(role_list[7]['id'], group_id=group2['id'], project_id=projectA['id']) # First, get a project scoped token - which should # contain the direct user role and the one by virtue # of group membership auth_data = self.build_authentication_request( user_id=user1['id'], password=user1['password'], project_id=projectA['id']) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidScopedTokenResponse(r) roles_ids = [] for ref in token['roles']: roles_ids.append(ref['id']) self.assertEqual(2, len(token['roles'])) self.assertIn(role_list[1]['id'], roles_ids) self.assertIn(role_list[5]['id'], roles_ids) # Now the same thing for a domain scoped token auth_data = self.build_authentication_request( user_id=user1['id'], password=user1['password'], domain_id=domainA['id']) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidScopedTokenResponse(r) roles_ids = [] for ref in token['roles']: roles_ids.append(ref['id']) self.assertEqual(2, len(token['roles'])) self.assertIn(role_list[0]['id'], roles_ids) self.assertIn(role_list[4]['id'], roles_ids) # Finally, add user1 to the 2nd group, and get a new # scoped token - the extra role should now be included # by virtue of the 2nd group self.identity_api.add_user_to_group(user1['id'], group2['id']) auth_data = self.build_authentication_request( user_id=user1['id'], password=user1['password'], project_id=projectA['id']) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidScopedTokenResponse(r) roles_ids = [] for ref in token['roles']: roles_ids.append(ref['id']) self.assertEqual(3, len(token['roles'])) self.assertIn(role_list[1]['id'], roles_ids) self.assertIn(role_list[5]['id'], roles_ids) self.assertIn(role_list[7]['id'], roles_ids) def test_project_id_scoped_token_with_user_domain_id(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=self.domain['id'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectScopedTokenResponse(r) def test_project_id_scoped_token_with_user_domain_name(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_name=self.domain['name'], password=self.user['password'], project_id=self.project['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectScopedTokenResponse(r) def test_domain_id_scoped_token_with_user_id(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_id=self.domain['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_id_scoped_token_with_user_domain_id(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=self.domain['id'], password=self.user['password'], domain_id=self.domain['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_id_scoped_token_with_user_domain_name(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( username=self.user['name'], user_domain_name=self.domain['name'], password=self.user['password'], domain_id=self.domain['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_name_scoped_token_with_user_id(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_name=self.domain['name']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_name_scoped_token_with_user_domain_id(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=self.domain['id'], password=self.user['password'], domain_name=self.domain['name']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_name_scoped_token_with_user_domain_name(self): path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) auth_data = self.build_authentication_request( username=self.user['name'], user_domain_name=self.domain['name'], password=self.user['password'], domain_name=self.domain['name']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_scope_token_with_group_role(self): group_id = uuid.uuid4().hex group = self.new_group_ref( domain_id=self.domain_id) group['id'] = group_id self.identity_api.create_group(group_id, group) # add user to group self.identity_api.add_user_to_group(self.user['id'], group['id']) # grant the domain role to group path = '/domains/%s/groups/%s/roles/%s' % ( self.domain['id'], group['id'], self.role['id']) self.put(path=path) # now get a domain-scoped token auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_id=self.domain['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_scope_token_with_name(self): # grant the domain role to user path = '/domains/%s/users/%s/roles/%s' % ( self.domain['id'], self.user['id'], self.role['id']) self.put(path=path) # now get a domain-scoped token auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_name=self.domain['name']) r = self.post('/auth/tokens', body=auth_data) self.assertValidDomainScopedTokenResponse(r) def test_domain_scope_failed(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], domain_id=self.domain['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_auth_with_id(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) token = r.headers.get('X-Subject-Token') # test token auth auth_data = self.build_authentication_request(token=token) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def get_v2_token(self, tenant_id=None): body = { 'auth': { 'passwordCredentials': { 'username': self.default_domain_user['name'], 'password': self.default_domain_user['password'], }, }, } r = self.admin_request(method='POST', path='/v2.0/tokens', body=body) return r def test_validate_v2_unscoped_token_with_v3_api(self): v2_token = self.get_v2_token().result['access']['token']['id'] auth_data = self.build_authentication_request(token=v2_token) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_validate_v2_scoped_token_with_v3_api(self): v2_response = self.get_v2_token( tenant_id=self.default_domain_project['id']) result = v2_response.result v2_token = result['access']['token']['id'] auth_data = self.build_authentication_request( token=v2_token, project_id=self.default_domain_project['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidScopedTokenResponse(r) def test_invalid_user_id(self): auth_data = self.build_authentication_request( user_id=uuid.uuid4().hex, password=self.user['password']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_invalid_user_name(self): auth_data = self.build_authentication_request( username=uuid.uuid4().hex, user_domain_id=self.domain['id'], password=self.user['password']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_invalid_domain_id(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_id=uuid.uuid4().hex, password=self.user['password']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_invalid_domain_name(self): auth_data = self.build_authentication_request( username=self.user['name'], user_domain_name=uuid.uuid4().hex, password=self.user['password']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_invalid_password(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=uuid.uuid4().hex) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_remote_user_no_realm(self): CONF.auth.methods = 'external' api = auth.controllers.Auth() context, auth_info, auth_context = self.build_external_auth_request( self.default_domain_user['name']) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.default_domain_user['id']) # Now test to make sure the user name can, itself, contain the # '@' character. user = {'name': 'myname@mydivision'} self.identity_api.update_user(self.default_domain_user['id'], user) context, auth_info, auth_context = self.build_external_auth_request( user["name"]) api.authenticate(context, auth_info, auth_context) self.assertEqual(auth_context['user_id'], self.default_domain_user['id']) def test_remote_user_no_domain(self): api = auth.controllers.Auth() context, auth_info, auth_context = self.build_external_auth_request( self.user['name']) self.assertRaises(exception.Unauthorized, api.authenticate, context, auth_info, auth_context) def test_remote_user_and_password(self): #both REMOTE_USER and password methods must pass. #note that they do not have to match api = auth.controllers.Auth() auth_data = self.build_authentication_request( user_domain_id=self.domain['id'], username=self.user['name'], password=self.user['password'])['auth'] context, auth_info, auth_context = self.build_external_auth_request( self.default_domain_user['name'], auth_data=auth_data) api.authenticate(context, auth_info, auth_context) def test_remote_user_and_explicit_external(self): #both REMOTE_USER and password methods must pass. #note that they do not have to match auth_data = self.build_authentication_request( user_domain_id=self.domain['id'], username=self.user['name'], password=self.user['password'])['auth'] auth_data['identity']['methods'] = ["password", "external"] auth_data['identity']['external'] = {} api = auth.controllers.Auth() auth_info = auth.controllers.AuthInfo(None, auth_data) auth_context = {'extras': {}, 'method_names': []} self.assertRaises(exception.Unauthorized, api.authenticate, self.empty_context, auth_info, auth_context) def test_remote_user_bad_password(self): #both REMOTE_USER and password methods must pass. api = auth.controllers.Auth() auth_data = self.build_authentication_request( user_domain_id=self.domain['id'], username=self.user['name'], password='badpassword')['auth'] context, auth_info, auth_context = self.build_external_auth_request( self.default_domain_user['name'], auth_data=auth_data) self.assertRaises(exception.Unauthorized, api.authenticate, context, auth_info, auth_context) def test_bind_not_set_with_remote_user(self): CONF.token.bind = [] auth_data = self.build_authentication_request() remote_user = self.default_domain_user['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidUnscopedTokenResponse(r) self.assertNotIn('bind', token) #TODO(ayoung): move to TestPKITokenAPIs; it will be run for both formats def test_verify_with_bound_token(self): self.config_fixture.config(group='token', bind='kerberos') auth_data = self.build_authentication_request( project_id=self.project['id']) remote_user = self.default_domain_user['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') headers = {'X-Subject-Token': token} r = self.get('/auth/tokens', headers=headers, token=token) token = self.assertValidProjectScopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], self.default_domain_user['name']) def test_auth_with_bind_token(self): CONF.token.bind = ['kerberos'] auth_data = self.build_authentication_request() remote_user = self.default_domain_user['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) r = self.post('/auth/tokens', body=auth_data) # the unscoped token should have bind information in it token = self.assertValidUnscopedTokenResponse(r) self.assertEqual(token['bind']['kerberos'], remote_user) token = r.headers.get('X-Subject-Token') # using unscoped token with remote user succeeds auth_params = {'token': token, 'project_id': self.project_id} auth_data = self.build_authentication_request(**auth_params) r = self.post('/auth/tokens', body=auth_data) token = self.assertValidProjectScopedTokenResponse(r) # the bind information should be carried over from the original token self.assertEqual(token['bind']['kerberos'], remote_user) def test_v2_v3_bind_token_intermix(self): self.config_fixture.config(group='token', bind='kerberos') # we need our own user registered to the default domain because of # the way external auth works. remote_user = self.default_domain_user['name'] self.admin_app.extra_environ.update({'REMOTE_USER': remote_user, 'AUTH_TYPE': 'Negotiate'}) body = {'auth': {}} resp = self.admin_request(path='/v2.0/tokens', method='POST', body=body) v2_token_data = resp.result bind = v2_token_data['access']['token']['bind'] self.assertEqual(bind['kerberos'], self.default_domain_user['name']) v2_token_id = v2_token_data['access']['token']['id'] headers = {'X-Subject-Token': v2_token_id} resp = self.get('/auth/tokens', headers=headers) token_data = resp.result self.assertDictEqual(v2_token_data['access']['token']['bind'], token_data['token']['bind']) def test_authenticating_a_user_with_no_password(self): user = self.new_user_ref(domain_id=self.domain['id']) user.pop('password', None) # can't have a password for this test self.identity_api.create_user(user['id'], user) auth_data = self.build_authentication_request( user_id=user['id'], password='password') self.post('/auth/tokens', body=auth_data, expected_status=401) def test_disabled_default_project_result_in_unscoped_token(self): # create a disabled project to work with project = self.create_new_default_project_for_user( self.user['id'], self.domain_id, enable_project=False) # assign a role to user for the new project self.assignment_api.add_role_to_user_and_project(self.user['id'], project['id'], self.role_id) # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_disabled_default_project_domain_result_in_unscoped_token(self): domain_ref = self.new_domain_ref() r = self.post('/domains', body={'domain': domain_ref}) domain = self.assertValidDomainResponse(r, domain_ref) project = self.create_new_default_project_for_user( self.user['id'], domain['id']) # assign a role to user for the new project self.assignment_api.add_role_to_user_and_project(self.user['id'], project['id'], self.role_id) # now disable the project domain body = {'domain': {'enabled': False}} r = self.patch('/domains/%(domain_id)s' % {'domain_id': domain['id']}, body=body) self.assertValidDomainResponse(r) # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_no_access_to_default_project_result_in_unscoped_token(self): # create a disabled project to work with self.create_new_default_project_for_user(self.user['id'], self.domain_id) # attempt to authenticate without requesting a project auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password']) r = self.post('/auth/tokens', body=auth_data) self.assertValidUnscopedTokenResponse(r) def test_disabled_scope_project_domain_result_in_401(self): # create a disabled domain domain = self.new_domain_ref() domain['enabled'] = False self.assignment_api.create_domain(domain['id'], domain) # create a project in the disabled domain project = self.new_project_ref(domain_id=domain['id']) self.assignment_api.create_project(project['id'], project) # assign some role to self.user for the project in the disabled domain self.assignment_api.add_role_to_user_and_project( self.user['id'], project['id'], self.role_id) # user should not be able to auth with project_id auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_id=project['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) # user should not be able to auth with project_name & domain auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], project_name=project['name'], project_domain_id=domain['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) class TestAuthXML(TestAuthJSON): content_type = 'xml' def _check_disabled_endpoint_result(self, catalog, disabled_endpoint_id): # FIXME(blk-u): As far as I can tell the catalog in the XML result is # broken. Looks like it includes only one endpoint or the other, and # which one is included is random. endpoint = catalog['service']['endpoint'] self.assertEqual(self.endpoint_id, endpoint['id']) class TestTrustOptional(test_v3.RestfulTestCase): def config_overrides(self): super(TestTrustOptional, self).config_overrides() self.config_fixture.config(group='trust', enabled=False) def test_trusts_404(self): self.get('/OS-TRUST/trusts', body={'trust': {}}, expected_status=404) self.post('/OS-TRUST/trusts', body={'trust': {}}, expected_status=404) def test_auth_with_scope_in_trust_403(self): auth_data = self.build_authentication_request( user_id=self.user['id'], password=self.user['password'], trust_id=uuid.uuid4().hex) self.post('/auth/tokens', body=auth_data, expected_status=403) @dependency.requires('revoke_api') class TestTrustAuth(TestAuthInfo): EXTENSION_NAME = 'revoke' EXTENSION_TO_ADD = 'revoke_extension' def config_overrides(self): super(TestTrustAuth, self).config_overrides() self.config_fixture.config( group='revoke', driver='keystone.contrib.revoke.backends.kvs.Revoke') self.config_fixture.config( group='token', provider='keystone.token.providers.pki.Provider', revoke_by_id=False) self.config_fixture.config(group='trust', enabled=True) def setUp(self): super(TestTrustAuth, self).setUp() # create a trustee to delegate stuff to self.trustee_user_id = uuid.uuid4().hex self.trustee_user = self.new_user_ref(domain_id=self.domain_id) self.trustee_user['id'] = self.trustee_user_id self.identity_api.create_user(self.trustee_user_id, self.trustee_user) def test_create_trust_400(self): # The server returns a 403 Forbidden rather than a 400, see bug 1133435 self.post('/OS-TRUST/trusts', body={'trust': {}}, expected_status=403) def test_create_unscoped_trust(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) self.assertValidTrustResponse(r, ref) def test_create_trust_no_roles(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=403) def _initialize_test_consume_trust(self, count): # Make sure remaining_uses is decremented as we consume the trust ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, remaining_uses=count, role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) # make sure the trust exists trust = self.assertValidTrustResponse(r, ref) r = self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=200) # get a token for the trustee auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password']) r = self.post('/auth/tokens', body=auth_data, expected_status=201) token = r.headers.get('X-Subject-Token') # get a trust token, consume one use auth_data = self.build_authentication_request( token=token, trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data, expected_status=201) return trust def test_consume_trust_once(self): trust = self._initialize_test_consume_trust(2) # check decremented value r = self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=200) trust = r.result.get('trust') self.assertIsNotNone(trust) self.assertEqual(trust['remaining_uses'], 1) def test_create_one_time_use_trust(self): trust = self._initialize_test_consume_trust(1) # No more uses, the trust is made unavailable self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=404) # this time we can't get a trust token auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_create_trust_with_bad_values_for_remaining_uses(self): # negative values for the remaining_uses parameter are forbidden self._create_trust_with_bad_remaining_use(bad_value=-1) # 0 is a forbidden value as well self._create_trust_with_bad_remaining_use(bad_value=0) # as are non integer values self._create_trust_with_bad_remaining_use(bad_value="a bad value") self._create_trust_with_bad_remaining_use(bad_value=7.2) def _create_trust_with_bad_remaining_use(self, bad_value): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, remaining_uses=bad_value, role_ids=[self.role_id]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=400) def test_create_unlimited_use_trust(self): # by default trusts are unlimited in terms of tokens that can be # generated from them, this test creates such a trust explicitly ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, remaining_uses=None, role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r, ref) r = self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=200) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password']) r = self.post('/auth/tokens', body=auth_data, expected_status=201) token = r.headers.get('X-Subject-Token') auth_data = self.build_authentication_request( token=token, trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data, expected_status=201) r = self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=200) trust = r.result.get('trust') self.assertIsNone(trust['remaining_uses']) def test_trust_crud(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r, ref) r = self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=200) self.assertValidTrustResponse(r, ref) # validate roles on the trust r = self.get( '/OS-TRUST/trusts/%(trust_id)s/roles' % { 'trust_id': trust['id']}, expected_status=200) roles = self.assertValidRoleListResponse(r, self.role) self.assertIn(self.role['id'], [x['id'] for x in roles]) self.head( '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % { 'trust_id': trust['id'], 'role_id': self.role['id']}, expected_status=200) r = self.get( '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % { 'trust_id': trust['id'], 'role_id': self.role['id']}, expected_status=200) self.assertValidRoleResponse(r, self.role) r = self.get('/OS-TRUST/trusts', expected_status=200) self.assertValidTrustListResponse(r, trust) # trusts are immutable self.patch( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, body={'trust': ref}, expected_status=404) self.delete( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=204) self.get( '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']}, expected_status=404) def test_create_trust_trustee_404(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=uuid.uuid4().hex, project_id=self.project_id, role_ids=[self.role_id]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404) def test_create_trust_trustor_trustee_backwards(self): ref = self.new_trust_ref( trustor_user_id=self.trustee_user_id, trustee_user_id=self.user_id, project_id=self.project_id, role_ids=[self.role_id]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=403) def test_create_trust_project_404(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=uuid.uuid4().hex, role_ids=[self.role_id]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404) def test_create_trust_role_id_404(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, role_ids=[uuid.uuid4().hex]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404) def test_create_trust_role_name_404(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, role_names=[uuid.uuid4().hex]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404) def test_create_expired_trust(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, expires=dict(seconds=-1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r, ref) self.get('/OS-TRUST/trusts/%(trust_id)s' % { 'trust_id': trust['id']}, expected_status=404) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_v3_v2_intermix_trustor_not_in_default_domain_failed(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.default_domain_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse( r, self.default_domain_user) token = r.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) self.admin_request( path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_intermix_trustor_not_in_default_domaini_failed(self): ref = self.new_trust_ref( trustor_user_id=self.default_domain_user_id, trustee_user_id=self.trustee_user_id, project_id=self.default_domain_project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.default_domain_project_id) r = self.post('/auth/tokens', body=auth_data) token = r.headers.get('X-Subject-Token') r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse( r, self.trustee_user) token = r.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) self.admin_request( path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_intermix_project_not_in_default_domaini_failed(self): # create a trustee in default domain to delegate stuff to trustee_user_id = uuid.uuid4().hex trustee_user = self.new_user_ref(domain_id=test_v3.DEFAULT_DOMAIN_ID) trustee_user['id'] = trustee_user_id self.identity_api.create_user(trustee_user_id, trustee_user) ref = self.new_trust_ref( trustor_user_id=self.default_domain_user_id, trustee_user_id=trustee_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.default_domain_project_id) r = self.post('/auth/tokens', body=auth_data) token = r.headers.get('X-Subject-Token') r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=trustee_user['id'], password=trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse( r, trustee_user) token = r.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) self.admin_request( path=path, token='ADMIN', method='GET', expected_status=401) def test_v3_v2_intermix(self): # create a trustee in default domain to delegate stuff to trustee_user_id = uuid.uuid4().hex trustee_user = self.new_user_ref(domain_id=test_v3.DEFAULT_DOMAIN_ID) trustee_user['id'] = trustee_user_id self.identity_api.create_user(trustee_user_id, trustee_user) ref = self.new_trust_ref( trustor_user_id=self.default_domain_user_id, trustee_user_id=trustee_user_id, project_id=self.default_domain_project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.default_domain_project_id) r = self.post('/auth/tokens', body=auth_data) token = r.headers.get('X-Subject-Token') r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=trustee_user['id'], password=trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse( r, trustee_user) token = r.headers.get('X-Subject-Token') # now validate the v3 token with v2 API path = '/v2.0/tokens/%s' % (token) self.admin_request( path=path, token='ADMIN', method='GET', expected_status=200) def test_exercise_trust_scoped_token_without_impersonation(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse(r, self.trustee_user) self.assertEqual(r.result['token']['user']['id'], self.trustee_user['id']) self.assertEqual(r.result['token']['user']['name'], self.trustee_user['name']) self.assertEqual(r.result['token']['user']['domain']['id'], self.domain['id']) self.assertEqual(r.result['token']['user']['domain']['name'], self.domain['name']) self.assertEqual(r.result['token']['project']['id'], self.project['id']) self.assertEqual(r.result['token']['project']['name'], self.project['name']) def test_exercise_trust_scoped_token_with_impersonation(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse(r, self.user) self.assertEqual(r.result['token']['user']['id'], self.user['id']) self.assertEqual(r.result['token']['user']['name'], self.user['name']) self.assertEqual(r.result['token']['user']['domain']['id'], self.domain['id']) self.assertEqual(r.result['token']['user']['domain']['name'], self.domain['name']) self.assertEqual(r.result['token']['project']['id'], self.project['id']) self.assertEqual(r.result['token']['project']['name'], self.project['name']) def test_impersonation_token_cannot_create_new_trust(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) trust_token = r.headers['X-Subject-Token'] # Build second trust ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] self.post('/OS-TRUST/trusts', body={'trust': ref}, token=trust_token, expected_status=403) def assertTrustTokensRevoked(self, trust_id): revocation_response = self.get('/OS-REVOKE/events', expected_status=200) revocation_events = revocation_response.json_body['events'] found = False for event in revocation_events: if event.get('OS-TRUST:trust_id') == trust_id: found = True self.assertTrue(found, 'event with trust_id %s not found in list' % trust_id) def test_delete_trust_revokes_tokens(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) trust_id = trust['id'] auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust_id) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse( r, self.trustee_user) trust_token = r.headers['X-Subject-Token'] self.delete('/OS-TRUST/trusts/%(trust_id)s' % { 'trust_id': trust_id}, expected_status=204) headers = {'X-Subject-Token': trust_token} self.head('/auth/tokens', headers=headers, expected_status=404) self.assertTrustTokensRevoked(trust_id) def test_delete_trust(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r, ref) self.delete('/OS-TRUST/trusts/%(trust_id)s' % { 'trust_id': trust['id']}, expected_status=204) self.get('/OS-TRUST/trusts/%(trust_id)s' % { 'trust_id': trust['id']}, expected_status=404) self.get('/OS-TRUST/trusts/%(trust_id)s' % { 'trust_id': trust['id']}, expected_status=404) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) self.post('/auth/tokens', body=auth_data, expected_status=401) def test_list_trusts(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] for i in range(3): r = self.post('/OS-TRUST/trusts', body={'trust': ref}) self.assertValidTrustResponse(r, ref) r = self.get('/OS-TRUST/trusts', expected_status=200) trusts = r.result['trusts'] self.assertEqual(3, len(trusts)) self.assertValidTrustListResponse(r) r = self.get('/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id, expected_status=200) trusts = r.result['trusts'] self.assertEqual(3, len(trusts)) self.assertValidTrustListResponse(r) r = self.get('/OS-TRUST/trusts?trustee_user_id=%s' % self.user_id, expected_status=200) trusts = r.result['trusts'] self.assertEqual(0, len(trusts)) def test_change_password_invalidates_trust_tokens(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, expires=dict(minutes=1), role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password'], trust_id=trust['id']) r = self.post('/auth/tokens', body=auth_data) self.assertValidProjectTrustScopedTokenResponse(r, self.user) trust_token = r.headers.get('X-Subject-Token') self.get('/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id, expected_status=200, token=trust_token) self.assertValidUserResponse( self.patch('/users/%s' % self.trustee_user['id'], body={'user': {'password': uuid.uuid4().hex}}, expected_status=200)) self.get('/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id, expected_status=401, token=trust_token) def test_trustee_can_do_role_ops(self): ref = self.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, role_ids=[self.role_id]) del ref['id'] r = self.post('/OS-TRUST/trusts', body={'trust': ref}) trust = self.assertValidTrustResponse(r) auth_data = self.build_authentication_request( user_id=self.trustee_user['id'], password=self.trustee_user['password']) r = self.get( '/OS-TRUST/trusts/%(trust_id)s/roles' % { 'trust_id': trust['id']}, auth=auth_data) self.assertValidRoleListResponse(r, self.role) self.head( '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % { 'trust_id': trust['id'], 'role_id': self.role['id']}, auth=auth_data, expected_status=200) r = self.get( '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % { 'trust_id': trust['id'], 'role_id': self.role['id']}, auth=auth_data, expected_status=200) self.assertValidRoleResponse(r, self.role) class TestAPIProtectionWithoutAuthContextMiddleware(test_v3.RestfulTestCase): def test_api_protection_with_no_auth_context_in_env(self): auth_data = self.build_authentication_request( user_id=self.default_domain_user['id'], password=self.default_domain_user['password'], project_id=self.project['id']) resp = self.post('/auth/tokens', body=auth_data) token = resp.headers.get('X-Subject-Token') auth_controller = auth.controllers.Auth() # all we care is that auth context is not in the environment and # 'token_id' is used to build the auth context instead context = {'subject_token_id': token, 'token_id': token, 'query_string': {}, 'environment': {}} r = auth_controller.validate_token(context) self.assertEqual(200, r.status_code)
dbergan/AutobahnPython
refs/heads/master
examples/twisted/wamp/basic/pubsub/complex/__init__.py
561
############################################################################### ## ## Copyright (C) 2014 Tavendo GmbH ## ## 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. ## ###############################################################################
jimberlage/servo
refs/heads/master
components/style/gecko/regen_atoms.py
2
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import re import os import sys from io import BytesIO GECKO_DIR = os.path.dirname(__file__.replace('\\', '/')) sys.path.insert(0, os.path.join(os.path.dirname(GECKO_DIR), "properties")) import build # Matches lines like `GK_ATOM(foo, "foo", 0x12345678, nsStaticAtom, PseudoElementAtom)`. PATTERN = re.compile('^GK_ATOM\(([^,]*),[^"]*"([^"]*)",\s*(0x[0-9a-f]+),\s*([^,]*),\s*([^)]*)\)', re.MULTILINE) FILE = "include/nsGkAtomList.h" def map_atom(ident): if ident in {"box", "loop", "match", "mod", "ref", "self", "type", "use", "where", "in"}: return ident + "_" return ident class Atom: def __init__(self, ident, value, hash, ty, atom_type): self.ident = "nsGkAtoms_{}".format(ident) self.original_ident = ident self.value = value self.hash = hash # The Gecko type: "nsStaticAtom", "nsCSSPseudoElementStaticAtom", or # "nsAnonBoxPseudoStaticAtom". self.ty = ty # The type of atom: "Atom", "PseudoElement", "NonInheritingAnonBox", # or "InheritingAnonBox". self.atom_type = atom_type if self.is_pseudo() or self.is_anon_box(): self.pseudo_ident = (ident.split("_", 1))[1] if self.is_anon_box(): assert self.is_inheriting_anon_box() or self.is_non_inheriting_anon_box() def type(self): return self.ty def capitalized_pseudo(self): return self.pseudo_ident[0].upper() + self.pseudo_ident[1:] def is_pseudo(self): return self.atom_type == "PseudoElementAtom" def is_anon_box(self): return self.is_non_inheriting_anon_box() or self.is_inheriting_anon_box() def is_non_inheriting_anon_box(self): return self.atom_type == "NonInheritingAnonBoxAtom" def is_inheriting_anon_box(self): return self.atom_type == "InheritingAnonBoxAtom" def is_tree_pseudo_element(self): return self.value.startswith(":-moz-tree-") def collect_atoms(objdir): atoms = [] path = os.path.abspath(os.path.join(objdir, FILE)) print("cargo:rerun-if-changed={}".format(path)) with open(path) as f: content = f.read() for result in PATTERN.finditer(content): atoms.append(Atom(result.group(1), result.group(2), result.group(3), result.group(4), result.group(5))) return atoms class FileAvoidWrite(BytesIO): """File-like object that buffers output and only writes if content changed.""" def __init__(self, filename): BytesIO.__init__(self) self.name = filename def write(self, buf): if isinstance(buf, unicode): buf = buf.encode('utf-8') BytesIO.write(self, buf) def close(self): buf = self.getvalue() BytesIO.close(self) try: with open(self.name, 'rb') as f: old_content = f.read() if old_content == buf: print("{} is not changed, skip".format(self.name)) return except IOError: pass with open(self.name, 'wb') as f: f.write(buf) def __enter__(self): return self def __exit__(self, type, value, traceback): if not self.closed: self.close() PRELUDE = ''' /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // Autogenerated file created by components/style/gecko/regen_atoms.py. // DO NOT EDIT DIRECTLY '''[1:] IMPORTS = ''' use gecko_bindings::structs::nsStaticAtom; use string_cache::Atom; ''' UNSAFE_STATIC = ''' #[inline(always)] pub unsafe fn atom_from_static(ptr: *const nsStaticAtom) -> Atom { Atom::from_static(ptr) } ''' SATOMS_TEMPLATE = ''' #[link_name = \"{link_name}\"] pub static nsGkAtoms_sAtoms: *const nsStaticAtom; '''[1:] CFG_IF_TEMPLATE = ''' cfg_if! {{ if #[cfg(not(target_env = "msvc"))] {{ extern {{ {gnu}\ }} }} else if #[cfg(target_pointer_width = "64")] {{ extern {{ {msvc64}\ }} }} else {{ extern {{ {msvc32}\ }} }} }}\n ''' CONST_TEMPLATE = ''' pub const k_{name}: isize = {index}; '''[1:] RULE_TEMPLATE = ''' ("{atom}") => {{{{ use $crate::string_cache::atom_macro; #[allow(unsafe_code)] #[allow(unused_unsafe)] unsafe {{ atom_macro::atom_from_static(atom_macro::nsGkAtoms_sAtoms.offset(atom_macro::k_{name})) }} }}}}; '''[1:] MACRO_TEMPLATE = ''' #[macro_export] macro_rules! atom {{ {body}\ }} ''' def write_atom_macro(atoms, file_name): with FileAvoidWrite(file_name) as f: f.write(PRELUDE) f.write(IMPORTS) f.write(UNSAFE_STATIC) gnu_name='_ZN9nsGkAtoms6sAtomsE' gnu_symbols = SATOMS_TEMPLATE.format(link_name=gnu_name) # Prepend "\x01" to avoid LLVM prefixing the mangled name with "_". # See https://github.com/rust-lang/rust/issues/36097 msvc32_name = '\\x01?sAtoms@nsGkAtoms@@0QBVnsStaticAtom@@B' msvc32_symbols = SATOMS_TEMPLATE.format(link_name=msvc32_name) msvc64_name = '?sAtoms@nsGkAtoms@@0QEBVnsStaticAtom@@EB' msvc64_symbols = SATOMS_TEMPLATE.format(link_name=msvc64_name) f.write(CFG_IF_TEMPLATE.format(gnu=gnu_symbols, msvc32=msvc32_symbols, msvc64=msvc64_symbols)) consts = [CONST_TEMPLATE.format(name=atom.ident, index=i) for (i, atom) in enumerate(atoms)] f.write('{}'.format(''.join(consts))) macro_rules = [RULE_TEMPLATE.format(atom=atom.value, name=atom.ident) for atom in atoms] f.write(MACRO_TEMPLATE.format(body=''.join(macro_rules))) def write_pseudo_elements(atoms, target_filename): pseudos = [] for atom in atoms: if atom.type() == "nsCSSPseudoElementStaticAtom" or atom.type() == "nsCSSAnonBoxPseudoStaticAtom": pseudos.append(atom) pseudo_definition_template = os.path.join(GECKO_DIR, "pseudo_element_definition.mako.rs") print("cargo:rerun-if-changed={}".format(pseudo_definition_template)) contents = build.render(pseudo_definition_template, PSEUDOS=pseudos) with FileAvoidWrite(target_filename) as f: f.write(contents) def generate_atoms(dist, out): atoms = collect_atoms(dist) write_atom_macro(atoms, os.path.join(out, "atom_macro.rs")) write_pseudo_elements(atoms, os.path.join(out, "pseudo_element_definition.rs")) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: {} dist out".format(sys.argv[0])) exit(2) generate_atoms(sys.argv[1], sys.argv[2])
AMechler/AliPhysics
refs/heads/master
PWGJE/EMCALJetTasks/Tracks/analysis/base/Helper.py
42
#************************************************************************** #* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. * #* * #* Author: The ALICE Off-line Project. * #* Contributors are mentioned in the code where appropriate. * #* * #* Permission to use, copy, modify and distribute this software and its * #* documentation strictly for non-commercial purposes is hereby granted * #* without fee, provided that the above copyright notice appears in all * #* copies and that both the copyright notice and this permission notice * #* appear in the supporting documentation. The authors make no claims * #* about the suitability of this software for any purpose. It is * #* provided "as is" without express or implied warranty. * #************************************************************************** """ Helper tools for spectrum plotting @author Markus Fasel @contact: markus.fasel@cern.ch @organization: ALICE Collaboration @organization: Lawrence Berkeley National Laboratory @copyright: 1998-2014, ALICE Experiment at CERN, All rights reserved """ from ROOT import TFile, TGraphErrors, gDirectory from copy import deepcopy def NormaliseBinWidth(hist): """ Normalise each bin by its width @param hist: Histogram to normalize by the bin width """ for mybin in range(1,hist.GetXaxis().GetNbins()+1): bw = hist.GetXaxis().GetBinWidth(mybin) hist.SetBinContent(mybin, hist.GetBinContent(mybin)/bw) hist.SetBinError(mybin, hist.GetBinError(mybin)/bw) def GetListOfBinLimits(inputhist): """ Convert bin limits to a list @param inputhist: Histogram to obtain the bin limits from @return: list of bin limits """ binlimits = [] for i in range(1, inputhist.GetXaxis().GetNbins()+1): if i == 1: binlimits.append(inputhist.GetXaxis().GetBinLowEdge(i)) newlimit = inputhist.GetXaxis().GetBinUpEdge(i) if newlimit in binlimits: continue binlimits.append(newlimit) return binlimits def MakeRatio(num, den, isBinomial = False): """ Calculate ratio between 2 histograms Option indicates whether we use binomial error calculation or gaussian error calculation @param num: Numerator hisrogram @param den: Denominator histogram @param isBinomial: If true binomial errors are used @return: The division result """ result = deepcopy(num) option = "" if isBinomial: option = "B" result.Divide(num, den, 1., 1., option) return result def HistToGraph(hist, xmin = None, xmax = None): """ Build a graph from a histogram. Optionally one can set the bin ranges @param hist: Histogram to build the graph from @param xmin: Minimum x for the x-range of the points @param xmax: Maximum x for the x-range of the points @return: A TGraphErrors created from the histogram """ output = TGraphErrors() npoints = 0 for mybin in range(1, hist.GetXaxis().GetNbins()+1): if xmin and hist.GetXaxis().GetBinLowEdge(mybin) < xmin: continue if xmax and hist.GetXaxis().GetBinLowEdge(mybin) > xmax: break output.SetPoint(npoints, hist.GetXaxis().GetBinCenter(mybin), hist.GetBinContent(mybin)) output.SetPointError(npoints, hist.GetXaxis().GetBinWidth(mybin)/2., hist.GetBinError(mybin)) npoints = npoints + 1 return output
thomashaw/SecGen
refs/heads/master
modules/utilities/unix/audit_tools/ghidra/files/release/Ghidra/Features/Python/data/jython-2.7.1/Lib/lib2to3/fixes/fix_buffer.py
327
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that changes buffer(...) into memoryview(...).""" # Local imports from .. import fixer_base from ..fixer_util import Name class FixBuffer(fixer_base.BaseFix): BM_compatible = True explicit = True # The user must ask for this fixer PATTERN = """ power< name='buffer' trailer< '(' [any] ')' > any* > """ def transform(self, node, results): name = results["name"] name.replace(Name(u"memoryview", prefix=name.prefix))
iiman/mytardis
refs/heads/master
tardis/apps/sync/models.py
1
# -*- coding: utf-8 -*- # # Copyright (c) 2010-2012, Monash e-Research Centre # (Monash University, Australia) # Copyright (c) 2010-2012, VeRSI Consortium # (Victorian eResearch Strategic Initiative, Australia) # 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 the VeRSI, the VeRSI Consortium members, 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 REGENTS 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 REGENTS AND 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. # """ models.py .. moduleauthor:: Kieran Spear <kispear@gmail.com> .. moduleauthor:: Shaun O'Keefe <shaun.okeefe.0@gmail.com> """ import json from django.db import models from django.dispatch import receiver from tardis.tardis_portal.models import Experiment from tardis.tardis_portal.signals import received_remote from tardis.apps.sync.consumer_fsm import ConsumerFSMField import logging logger = logging.getLogger(__file__) # # Maybe a common base class so we can turn anything into # a synced model? # class SyncedExperiment(models.Model): experiment = models.ForeignKey(Experiment) uid = models.TextField() state = ConsumerFSMField(default='Ingested') #prev_state = ConsumerFSMField(default='Ingested') # Keep track of which provider this experiment came from. # This might be better as another table if there's more to store. provider_url = models.TextField() msg = models.TextField(default='') def is_complete(self): return self.state.is_final_state() def progress(self): self.state = self.state.get_next_state(self) self.save() def status(self): try: return json.loads(self.msg) except ValueError: return None def save_status(self, status_dict): self.msg = json.dumps(status_dict) self.save() @receiver(received_remote, sender=Experiment) def experiment_received(sender, **kwargs): exp = kwargs['instance'] uid = kwargs['uid'] from_url = kwargs['from_url'] logger.info('Sync app saw experiment %s' % uid) synced_exp = SyncedExperiment(experiment=exp, uid=uid, provider_url=from_url) synced_exp.save()
nikhilprathapani/python-for-android
refs/heads/master
python3-alpha/python3-src/Tools/msi/msi.py
45
# Python MSI Generator # (C) 2003 Martin v. Loewis # See "FOO" in comments refers to MSDN sections with the title FOO. import msilib, schema, sequence, os, glob, time, re, shutil, zipfile from msilib import Feature, CAB, Directory, Dialog, Binary, add_data import uisample from win32com.client import constants from distutils.spawn import find_executable from uuids import product_codes import tempfile # Settings can be overridden in config.py below # 0 for official python.org releases # 1 for intermediate releases by anybody, with # a new product code for every package. snapshot = 1 # 1 means that file extension is px, not py, # and binaries start with x testpackage = 0 # Location of build tree srcdir = os.path.abspath("../..") # Text to be displayed as the version in dialogs etc. # goes into file name and ProductCode. Defaults to # current_version.day for Snapshot, current_version otherwise full_current_version = None # Is Tcl available at all? have_tcl = True # path to PCbuild directory PCBUILD="PCbuild" # msvcrt version MSVCR = "90" # Name of certificate in default store to sign MSI with certname = None # Make a zip file containing the PDB files for this build? pdbzip = True try: from config import * except ImportError: pass # Extract current version from Include/patchlevel.h lines = open(srcdir + "/Include/patchlevel.h").readlines() major = minor = micro = level = serial = None levels = { 'PY_RELEASE_LEVEL_ALPHA':0xA, 'PY_RELEASE_LEVEL_BETA': 0xB, 'PY_RELEASE_LEVEL_GAMMA':0xC, 'PY_RELEASE_LEVEL_FINAL':0xF } for l in lines: if not l.startswith("#define"): continue l = l.split() if len(l) != 3: continue _, name, value = l if name == 'PY_MAJOR_VERSION': major = value if name == 'PY_MINOR_VERSION': minor = value if name == 'PY_MICRO_VERSION': micro = value if name == 'PY_RELEASE_LEVEL': level = levels[value] if name == 'PY_RELEASE_SERIAL': serial = value short_version = major+"."+minor # See PC/make_versioninfo.c FIELD3 = 1000*int(micro) + 10*level + int(serial) current_version = "%s.%d" % (short_version, FIELD3) # This should never change. The UpgradeCode of this package can be # used in the Upgrade table of future packages to make the future # package replace this one. See "UpgradeCode Property". # upgrade_code gets set to upgrade_code_64 when we have determined # that the target is Win64. upgrade_code_snapshot='{92A24481-3ECB-40FC-8836-04B7966EC0D5}' upgrade_code='{65E6DE48-A358-434D-AA4F-4AF72DB4718F}' upgrade_code_64='{6A965A0C-6EE6-4E3A-9983-3263F56311EC}' if snapshot: current_version = "%s.%s.%s" % (major, minor, int(time.time()/3600/24)) product_code = msilib.gen_uuid() else: product_code = product_codes[current_version] if full_current_version is None: full_current_version = current_version extensions = [ 'bz2.pyd', 'pyexpat.pyd', 'select.pyd', 'unicodedata.pyd', 'winsound.pyd', '_elementtree.pyd', '_socket.pyd', '_ssl.pyd', '_testcapi.pyd', '_tkinter.pyd', '_msi.pyd', '_ctypes.pyd', '_ctypes_test.pyd', '_sqlite3.pyd', '_hashlib.pyd', '_multiprocessing.pyd' ] # Well-known component UUIDs # These are needed for SharedDLLs reference counter; if # a different UUID was used for each incarnation of, say, # python24.dll, an upgrade would set the reference counter # from 1 to 2 (due to what I consider a bug in MSI) # Using the same UUID is fine since these files are versioned, # so Installer will always keep the newest version. # NOTE: All uuids are self generated. pythondll_uuid = { "24":"{9B81E618-2301-4035-AC77-75D9ABEB7301}", "25":"{2e41b118-38bd-4c1b-a840-6977efd1b911}", "26":"{34ebecac-f046-4e1c-b0e3-9bac3cdaacfa}", "27":"{4fe21c76-1760-437b-a2f2-99909130a175}", "30":"{6953bc3b-6768-4291-8410-7914ce6e2ca8}", "31":"{4afcba0b-13e4-47c3-bebe-477428b46913}", "32":"{3ff95315-1096-4d31-bd86-601d5438ad5e}", } [major+minor] # Compute the name that Sphinx gives to the docfile docfile = "" if int(micro): docfile = micro if level < 0xf: if level == 0xC: docfile += "rc%s" % (serial,) else: docfile += '%x%s' % (level, serial) docfile = 'python%s%s%s.chm' % (major, minor, docfile) # Build the mingw import library, libpythonXY.a # This requires 'nm' and 'dlltool' executables on your PATH def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib): warning = "WARNING: %s - libpythonXX.a not built" nm = find_executable('nm') dlltool = find_executable('dlltool') if not nm or not dlltool: print(warning % "nm and/or dlltool were not found") return False nm_command = '%s -Cs %s' % (nm, lib_file) dlltool_command = "%s --dllname %s --def %s --output-lib %s" % \ (dlltool, dll_file, def_file, mingw_lib) export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match f = open(def_file,'w') f.write("LIBRARY %s\n" % dll_file) f.write("EXPORTS\n") nm_pipe = os.popen(nm_command) for line in nm_pipe.readlines(): m = export_match(line) if m: f.write(m.group(1)+"\n") f.close() exit = nm_pipe.close() if exit: print(warning % "nm did not run successfully") return False if os.system(dlltool_command) != 0: print(warning % "dlltool did not run successfully") return False return True # Target files (.def and .a) go in PCBuild directory lib_file = os.path.join(srcdir, PCBUILD, "python%s%s.lib" % (major, minor)) def_file = os.path.join(srcdir, PCBUILD, "python%s%s.def" % (major, minor)) dll_file = "python%s%s.dll" % (major, minor) mingw_lib = os.path.join(srcdir, PCBUILD, "libpython%s%s.a" % (major, minor)) have_mingw = build_mingw_lib(lib_file, def_file, dll_file, mingw_lib) # Determine the target architecture dll_path = os.path.join(srcdir, PCBUILD, dll_file) msilib.set_arch_from_file(dll_path) if msilib.pe_type(dll_path) != msilib.pe_type("msisupport.dll"): raise SystemError("msisupport.dll for incorrect architecture") if msilib.Win64: upgrade_code = upgrade_code_64 # Bump the last digit of the code by one, so that 32-bit and 64-bit # releases get separate product codes digit = hex((int(product_code[-2],16)+1)%16)[-1] product_code = product_code[:-2] + digit + '}' if testpackage: ext = 'px' testprefix = 'x' else: ext = 'py' testprefix = '' if msilib.Win64: SystemFolderName = "[System64Folder]" registry_component = 4|256 else: SystemFolderName = "[SystemFolder]" registry_component = 4 msilib.reset() # condition in which to install pythonxy.dll in system32: # a) it is Windows 9x or # b) it is NT, the user is privileged, and has chosen per-machine installation sys32cond = "(Windows9x or (Privileged and ALLUSERS))" def build_database(): """Generate an empty database, with just the schema and the Summary information stream.""" if snapshot: uc = upgrade_code_snapshot else: uc = upgrade_code if msilib.Win64: productsuffix = " (64-bit)" else: productsuffix = "" # schema represents the installer 2.0 database schema. # sequence is the set of standard sequences # (ui/execute, admin/advt/install) msiname = "python-%s%s.msi" % (full_current_version, msilib.arch_ext) db = msilib.init_database(msiname, schema, ProductName="Python "+full_current_version+productsuffix, ProductCode=product_code, ProductVersion=current_version, Manufacturer=u"Python Software Foundation", request_uac = True) # The default sequencing of the RemoveExistingProducts action causes # removal of files that got just installed. Place it after # InstallInitialize, so we first uninstall everything, but still roll # back in case the installation is interrupted msilib.change_sequence(sequence.InstallExecuteSequence, "RemoveExistingProducts", 1510) msilib.add_tables(db, sequence) # We cannot set ALLUSERS in the property table, as this cannot be # reset if the user choses a per-user installation. Instead, we # maintain WhichUsers, which can be "ALL" or "JUSTME". The UI manages # this property, and when the execution starts, ALLUSERS is set # accordingly. add_data(db, "Property", [("UpgradeCode", uc), ("WhichUsers", "ALL"), ("ProductLine", "Python%s%s" % (major, minor)), ]) db.Commit() return db, msiname def remove_old_versions(db): "Fill the upgrade table." start = "%s.%s.0" % (major, minor) # This requests that feature selection states of an older # installation should be forwarded into this one. Upgrading # requires that both the old and the new installation are # either both per-machine or per-user. migrate_features = 1 # See "Upgrade Table". We remove releases with the same major and # minor version. For an snapshot, we remove all earlier snapshots. For # a release, we remove all snapshots, and all earlier releases. if snapshot: add_data(db, "Upgrade", [(upgrade_code_snapshot, start, current_version, None, # Ignore language migrate_features, None, # Migrate ALL features "REMOVEOLDSNAPSHOT")]) props = "REMOVEOLDSNAPSHOT" else: add_data(db, "Upgrade", [(upgrade_code, start, current_version, None, migrate_features, None, "REMOVEOLDVERSION"), (upgrade_code_snapshot, start, "%s.%d.0" % (major, int(minor)+1), None, migrate_features, None, "REMOVEOLDSNAPSHOT")]) props = "REMOVEOLDSNAPSHOT;REMOVEOLDVERSION" props += ";TARGETDIR;DLLDIR" # Installer collects the product codes of the earlier releases in # these properties. In order to allow modification of the properties, # they must be declared as secure. See "SecureCustomProperties Property" add_data(db, "Property", [("SecureCustomProperties", props)]) class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 bmwidth = 152*ruler/328 if kw.get("bitmap", True): self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 135, 10, 220, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\python_icon.exe"): raise RuntimeError("Run icons.mak in PC directory") add_data(db, "Binary", [("PythonWin", msilib.Binary(r"%s\PCbuild\installer.bmp" % srcdir)), # 152x328 pixels ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")), ]) add_data(db, "Icon", [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))]) # Scripts # CheckDir sets TargetExists if TARGETDIR exists. # UpdateEditIDLE sets the REGISTRY.tcl component into # the installed/uninstalled state according to both the # Extensions and TclTk features. if os.system("nmake /nologo /c /f msisupport.mak") != 0: raise RuntimeError("'nmake /f msisupport.mak' failed") add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))]) # See "Custom Action Type 1" if msilib.Win64: CheckDir = "CheckDir" UpdateEditIDLE = "UpdateEditIDLE" else: CheckDir = "_CheckDir@4" UpdateEditIDLE = "_UpdateEditIDLE@4" add_data(db, "CustomAction", [("CheckDir", 1, "Script", CheckDir)]) if have_tcl: add_data(db, "CustomAction", [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)]) # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair")]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x "bad_coding|badsyntax|site-packages|py2_|lib2to3\\tests" "[TARGETDIR]Lib"' lib2to3args = r'-c "import lib2to3.pygram, lib2to3.patcomp;lib2to3.patcomp.PatternCompiler()"' # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty # See "Custom Action Type 51", # "Custom Action Execution Scheduling Options" ("InitialTargetDir", 307, "TARGETDIR", "[WindowsVolume]Python%s%s" % (major, minor)), ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"), ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName), # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile # See "Custom Action Type 18" ("CompilePyc", 18, "python.exe", compileargs), ("CompilePyo", 18, "python.exe", "-O "+compileargs), ("CompileGrammar", 18, "python.exe", lib2to3args), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), ("InitialTargetDir", 'TARGETDIR=""', 750), # In the user interface, assume all-users installation if privileged. ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, "AdminUISequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ]) # Execute Sequences add_data(db, "InstallExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("UpdateEditIDLE", None, 1050), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ("CompileGrammar", "COMPILEALL", 6802), ]) add_data(db, "AdminExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ("CompileGrammar", "COMPILEALL", 6802), ]) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") # See "ControlEvent Table". Parameters are the event, the parameter # to the action, and optionally the condition for the event, and the order # of events. c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003, "Special Windows thanks to:\n" " Mark Hammond, without whose years of freely \n" " shared Windows expertise, Python for Windows \n" " would still be Python for DOS.") c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003, "{\\VerdanaRed9}Warning: Python 2.5.x is the last " "Python release for Windows 9x.") c.condition("Hide", "NOT Version9X") exit_dialog.text("Description", 135, 235, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") costing.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 135, 70, 220, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 135, 110, 220, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 135, 135, 220, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") c = seldlg.text("Existing", 135, 25, 235, 30, 0x30003, "{\VerdanaRed9}This update will replace your existing [ProductLine] installation.") c.condition("Hide", 'REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""') seldlg.text("Description", 135, 50, 220, 40, 0x30003, "Please select a directory for the [ProductName] files.") seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("DoAction", "CheckDir", "TargetExistsOk<>1", order=1) # If the target exists, but we found that we are going to remove old versions, don't bother # confirming that the target directory exists. Strictly speaking, we should determine that # the target directory is indeed the target of the product that we are going to remove, but # I don't know how to do that. c.event("SpawnDialog", "ExistingDirectoryDlg", 'TargetExists=1 and REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""', 2) c.event("SetTargetPath", "TARGETDIR", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 3) c.event("SpawnWaitDialog", "WaitForCostingDlg", "CostingComplete=1", 4) c.event("NewDialog", "SelectFeaturesDlg", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 5) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 135, 70, 172, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 135, 90, 208, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 135, 230, 206, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # SelectFeaturesDlg features = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal|track_disk_space, title, "Tree", "Next", "Cancel") features.title("Customize [ProductName]") features.text("Description", 135, 35, 220, 15, 0x30003, "Select the way you want features to be installed.") features.text("Text", 135,45,220,30, 3, "Click on the icons in the tree below to change the way features will be installed.") c=features.back("< Back", "Next") c.event("NewDialog", "SelectDirectoryDlg") c=features.next("Next >", "Cancel") c.mapping("SelectionNoItems", "Enabled") c.event("SpawnDialog", "DiskCostDlg", "OutOfDiskSpace=1", order=1) c.event("EndDialog", "Return", "OutOfDiskSpace<>1", order=2) c=features.cancel("Cancel", "Tree") c.event("SpawnDialog", "CancelDlg") # The browse property is not used, since we have only a single target path (selected already) features.control("Tree", "SelectionTree", 135, 75, 220, 95, 7, "_BrowseProperty", "Tree of selections", "Back", None) #c=features.pushbutton("Reset", 42, 243, 56, 17, 3, "Reset", "DiskCost") #c.mapping("SelectionNoItems", "Enabled") #c.event("Reset", "0") features.control("Box", "GroupBox", 135, 170, 225, 90, 1, None, None, None, None) c=features.xbutton("DiskCost", "Disk &Usage", None, 0.10) c.mapping("SelectionNoItems","Enabled") c.event("SpawnDialog", "DiskCostDlg") c=features.xbutton("Advanced", "Advanced", None, 0.30) c.event("SpawnDialog", "AdvancedDlg") c=features.text("ItemDescription", 140, 180, 210, 30, 3, "Multiline description of the currently selected item.") c.mapping("SelectionDescription","Text") c=features.text("ItemSize", 140, 210, 210, 45, 3, "The size of the currently selected item.") c.mapping("SelectionSize", "Text") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 135, 60, 235, 80, 3, "WhichUsers", "", "Next") g.condition("Disable", "VersionNT=600") # Not available on Vista and Windows 2008 g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 235, 20, "Install just for me (not available on Windows Vista)") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", order = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Advanced Dialog. advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title, "CompilePyc", "Ok", "Ok") advanced.title("Advanced Options for [ProductName]") # A radio group with two options: allusers, justme advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3, "COMPILEALL", "Compile .py files to byte code after installation", "Ok") c = advanced.cancel("Ok", "CompilePyc", name="Ok") # Button just has location of cancel button. c.event("EndDialog", "Return") ##################################################################### # Existing Directory dialog dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title, "No", "No", "No") dlg.text("Title", 10, 20, 180, 40, 3, "[TARGETDIR] exists. Are you sure you want to overwrite existing files?") c=dlg.pushbutton("Yes", 30, 60, 55, 17, 3, "Yes", "No") c.event("[TargetExists]", "0", order=1) c.event("[TargetExistsOk]", "1", order=2) c.event("EndDialog", "Return", order=3) c=dlg.pushbutton("No", 115, 60, 55, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 135, 63, 230, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 135, 108, 230, 60, 3, "MaintenanceForm_Action", "", "Next") g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") # See "Feature Table". The feature level is 1 for all features, # and the feature attributes are 0 for the DefaultFeature, and # FollowParent for all other features. The numbers are the Display # column. def add_features(db): # feature attributes: # msidbFeatureAttributesFollowParent == 2 # msidbFeatureAttributesDisallowAdvertise == 8 # Features that need to be installed with together with the main feature # (i.e. additional Python libraries) need to follow the parent feature. # Features that have no advertisement trigger (e.g. the test suite) # must not support advertisement global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature, private_crt default_feature = Feature(db, "DefaultFeature", "Python", "Python Interpreter and Libraries", 1, directory = "TARGETDIR") shared_crt = Feature(db, "SharedCRT", "MSVCRT", "C Run-Time (system-wide)", 0, level=0) private_crt = Feature(db, "PrivateCRT", "MSVCRT", "C Run-Time (private)", 0, level=0) add_data(db, "Condition", [("SharedCRT", 1, sys32cond), ("PrivateCRT", 1, "not "+sys32cond)]) # We don't support advertisement of extensions ext_feature = Feature(db, "Extensions", "Register Extensions", "Make this Python installation the default Python installation", 3, parent = default_feature, attributes=2|8) if have_tcl: tcltk = Feature(db, "TclTk", "Tcl/Tk", "Tkinter, IDLE, pydoc", 5, parent = default_feature, attributes=2) htmlfiles = Feature(db, "Documentation", "Documentation", "Python HTMLHelp File", 7, parent = default_feature) tools = Feature(db, "Tools", "Utility Scripts", "Python utility scripts (Tools/", 9, parent = default_feature, attributes=2) testsuite = Feature(db, "Testsuite", "Test suite", "Python test suite (Lib/test/)", 11, parent = default_feature, attributes=2|8) def extract_msvcr90(): # Find the redistributable files if msilib.Win64: arch = "amd64" else: arch = "x86" dir = os.path.join(os.environ['VS90COMNTOOLS'], r"..\..\VC\redist\%s\Microsoft.VC90.CRT" % arch) result = [] installer = msilib.MakeInstaller() # omit msvcm90 and msvcp90, as they aren't really needed files = ["Microsoft.VC90.CRT.manifest", "msvcr90.dll"] for f in files: path = os.path.join(dir, f) kw = {'src':path} if f.endswith('.dll'): kw['version'] = installer.FileVersion(path, 0) kw['language'] = installer.FileVersion(path, 1) result.append((f, kw)) return result def generate_license(): import shutil, glob out = open("LICENSE.txt", "w") shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out) shutil.copyfileobj(open("crtlicense.txt"), out) for name, pat, file in (("bzip2","bzip2-*", "LICENSE"), ("openssl", "openssl-*", "LICENSE"), ("Tcl", "tcl8*", "license.terms"), ("Tk", "tk8*", "license.terms"), ("Tix", "tix-*", "license.terms")): out.write("\nThis copy of Python includes a copy of %s, which is licensed under the following terms:\n\n" % name) dirs = glob.glob(srcdir+"/../"+pat) if not dirs: raise ValueError, "Could not find "+srcdir+"/../"+pat if len(dirs) > 2: raise ValueError, "Multiple copies of "+pat dir = dirs[0] shutil.copyfileobj(open(os.path.join(dir, file)), out) out.close() class PyDirectory(Directory): """By default, all components in the Python installer can run from source.""" def __init__(self, *args, **kw): if "componentflags" not in kw: kw['componentflags'] = 2 #msidbComponentAttributesOptional Directory.__init__(self, *args, **kw) def check_unpackaged(self): self.unpackaged_files.discard('__pycache__') self.unpackaged_files.discard('.svn') if self.unpackaged_files: print "Warning: Unpackaged files in %s" % self.absolute print self.unpackaged_files # See "File Table", "Component Table", "Directory Table", # "FeatureComponents Table" def add_files(db): cab = CAB("python") tmpfiles = [] # Add all executables, icons, text files into the TARGETDIR component root = PyDirectory(db, cab, None, srcdir, "TARGETDIR", "SourceDir") default_feature.set_current() if not msilib.Win64: root.add_file("%s/w9xpopen.exe" % PCBUILD) root.add_file("README.txt", src="README") root.add_file("NEWS.txt", src="Misc/NEWS") generate_license() root.add_file("LICENSE.txt", src=os.path.abspath("LICENSE.txt")) root.start_component("python.exe", keyfile="python.exe") root.add_file("%s/python.exe" % PCBUILD) root.start_component("pythonw.exe", keyfile="pythonw.exe") root.add_file("%s/pythonw.exe" % PCBUILD) # msidbComponentAttributesSharedDllRefCount = 8, see "Component Table" dlldir = PyDirectory(db, cab, root, srcdir, "DLLDIR", ".") pydll = "python%s%s.dll" % (major, minor) pydllsrc = os.path.join(srcdir, PCBUILD, pydll) dlldir.start_component("DLLDIR", flags = 8, keyfile = pydll, uuid = pythondll_uuid) installer = msilib.MakeInstaller() pyversion = installer.FileVersion(pydllsrc, 0) if not snapshot: # For releases, the Python DLL has the same version as the # installer package. assert pyversion.split(".")[:3] == current_version.split(".") dlldir.add_file("%s/python%s%s.dll" % (PCBUILD, major, minor), version=pyversion, language=installer.FileVersion(pydllsrc, 1)) DLLs = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs") # msvcr90.dll: Need to place the DLL and the manifest into the root directory, # plus another copy of the manifest in the DLLs directory, with the manifest # pointing to the root directory root.start_component("msvcr90", feature=private_crt) # Results are ID,keyword pairs manifest, crtdll = extract_msvcr90() root.add_file(manifest[0], **manifest[1]) root.add_file(crtdll[0], **crtdll[1]) # Copy the manifest # Actually, don't do that anymore - no DLL in DLLs should have a manifest # dependency on msvcr90.dll anymore, so this should not be necessary #manifest_dlls = manifest[0]+".root" #open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr")) #DLLs.start_component("msvcr90_dlls", feature=private_crt) #DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls)) # Now start the main component for the DLLs directory; # no regular files have been added to the directory yet. DLLs.start_component() # Check if _ctypes.pyd exists have_ctypes = os.path.exists(srcdir+"/%s/_ctypes.pyd" % PCBUILD) if not have_ctypes: print("WARNING: _ctypes.pyd not found, ctypes will not be included") extensions.remove("_ctypes.pyd") # Add all .py files in Lib, except tkinter, test dirs = [] pydirs = [(root,"Lib")] while pydirs: # Commit every now and then, or else installer will complain db.Commit() parent, dir = pydirs.pop() if dir == ".svn" or dir == '__pycache__' or dir.startswith("plat-"): continue elif dir in ["tkinter", "idlelib", "Icons"]: if not have_tcl: continue tcltk.set_current() elif dir in ['test', 'tests', 'data', 'output']: # test: Lib, Lib/email, Lib/ctypes, Lib/sqlite3 # tests: Lib/distutils # data: Lib/email/test # output: Lib/test testsuite.set_current() elif not have_ctypes and dir == "ctypes": continue else: default_feature.set_current() lib = PyDirectory(db, cab, parent, dir, dir, "%s|%s" % (parent.make_short(dir), dir)) # Add additional files dirs.append(lib) lib.glob("*.txt") if dir=='site-packages': lib.add_file("README.txt", src="README") continue files = lib.glob("*.py") files += lib.glob("*.pyw") if files: # Add an entry to the RemoveFile table to remove bytecode files. lib.remove_pyc() # package READMEs if present lib.glob("README") if dir=='Lib': lib.add_file('wsgiref.egg-info') if dir=='test' and parent.physical=='Lib': lib.add_file("185test.db") lib.add_file("audiotest.au") lib.add_file("sgml_input.html") lib.add_file("testtar.tar") lib.add_file("test_difflib_expect.html") lib.add_file("check_soundcard.vbs") lib.add_file("empty.vbs") lib.add_file("Sine-1000Hz-300ms.aif") lib.glob("*.uue") lib.glob("*.pem") lib.glob("*.pck") lib.glob("cfgparser.*") lib.add_file("zip_cp437_header.zip") lib.add_file("zipdir.zip") if dir=='capath': lib.glob("*.0") if dir=='tests' and parent.physical=='distutils': lib.add_file("Setup.sample") if dir=='decimaltestdata': lib.glob("*.decTest") if dir=='xmltestdata': lib.glob("*.xml") lib.add_file("test.xml.out") if dir=='output': lib.glob("test_*") if dir=='sndhdrdata': lib.glob("sndhdr.*") if dir=='idlelib': lib.glob("*.def") lib.add_file("idle.bat") lib.add_file("ChangeLog") if dir=="Icons": lib.glob("*.gif") lib.add_file("idle.icns") if dir=="command" and parent.physical=="distutils": lib.glob("wininst*.exe") lib.add_file("command_template") if dir=="lib2to3": lib.removefile("pickle", "*.pickle") if dir=="macholib": lib.add_file("README.ctypes") lib.glob("fetch_macholib*") if dir=='turtledemo': lib.add_file("turtle.cfg") if dir=="pydoc_data": lib.add_file("_pydoc.css") if dir=="data" and parent.physical=="test" and parent.basedir.physical=="email": # This should contain all non-.svn files listed in subversion for f in os.listdir(lib.absolute): if f.endswith(".txt") or f==".svn":continue if f.endswith(".au") or f.endswith(".gif"): lib.add_file(f) else: print("WARNING: New file %s in email/test/data" % f) for f in os.listdir(lib.absolute): if os.path.isdir(os.path.join(lib.absolute, f)): pydirs.append((lib, f)) for d in dirs: d.check_unpackaged() # Add DLLs default_feature.set_current() lib = DLLs lib.add_file("py.ico", src=srcdir+"/PC/py.ico") lib.add_file("pyc.ico", src=srcdir+"/PC/pyc.ico") dlls = [] tclfiles = [] for f in extensions: if f=="_tkinter.pyd": continue if not os.path.exists(srcdir + "/" + PCBUILD + "/" + f): print("WARNING: Missing extension", f) continue dlls.append(f) lib.add_file(f) lib.add_file('python3.dll') # Add sqlite if msilib.msi_type=="Intel64;1033": sqlite_arch = "/ia64" elif msilib.msi_type=="x64;1033": sqlite_arch = "/amd64" tclsuffix = "64" else: sqlite_arch = "" tclsuffix = "" lib.add_file("sqlite3.dll") if have_tcl: if not os.path.exists("%s/%s/_tkinter.pyd" % (srcdir, PCBUILD)): print("WARNING: Missing _tkinter.pyd") else: lib.start_component("TkDLLs", tcltk) lib.add_file("_tkinter.pyd") dlls.append("_tkinter.pyd") tcldir = os.path.normpath(srcdir+("/../tcltk%s/bin" % tclsuffix)) for f in glob.glob1(tcldir, "*.dll"): lib.add_file(f, src=os.path.join(tcldir, f)) # check whether there are any unknown extensions for f in glob.glob1(srcdir+"/"+PCBUILD, "*.pyd"): if f.endswith("_d.pyd"): continue # debug version if f in dlls: continue print("WARNING: Unknown extension", f) # Add headers default_feature.set_current() lib = PyDirectory(db, cab, root, "include", "include", "INCLUDE|include") lib.glob("*.h") lib.add_file("pyconfig.h", src="../PC/pyconfig.h") # Add import libraries lib = PyDirectory(db, cab, root, PCBUILD, "libs", "LIBS|libs") for f in dlls: lib.add_file(f.replace('pyd','lib')) lib.add_file('python%s%s.lib' % (major, minor)) lib.add_file('python3.lib') # Add the mingw-format library if have_mingw: lib.add_file('libpython%s%s.a' % (major, minor)) if have_tcl: # Add Tcl/Tk tcldirs = [(root, '../tcltk%s/lib' % tclsuffix, 'tcl')] tcltk.set_current() while tcldirs: parent, phys, dir = tcldirs.pop() lib = PyDirectory(db, cab, parent, phys, dir, "%s|%s" % (parent.make_short(dir), dir)) if not os.path.exists(lib.absolute): continue for f in os.listdir(lib.absolute): if os.path.isdir(os.path.join(lib.absolute, f)): tcldirs.append((lib, f, f)) else: lib.add_file(f) # Add tools tools.set_current() tooldir = PyDirectory(db, cab, root, "Tools", "Tools", "TOOLS|Tools") for f in ['i18n', 'pynche', 'Scripts']: lib = PyDirectory(db, cab, tooldir, f, f, "%s|%s" % (tooldir.make_short(f), f)) lib.glob("*.py") lib.glob("*.pyw", exclude=['pydocgui.pyw']) lib.remove_pyc() lib.glob("*.txt") if f == "pynche": x = PyDirectory(db, cab, lib, "X", "X", "X|X") x.glob("*.txt") if os.path.exists(os.path.join(lib.absolute, "README")): lib.add_file("README.txt", src="README") if f == 'Scripts': lib.add_file("2to3.py", src="2to3") if have_tcl: lib.start_component("pydocgui.pyw", tcltk, keyfile="pydocgui.pyw") lib.add_file("pydocgui.pyw") # Add documentation htmlfiles.set_current() lib = PyDirectory(db, cab, root, "Doc", "Doc", "DOC|Doc") lib.start_component("documentation", keyfile=docfile) lib.add_file(docfile, src="build/htmlhelp/"+docfile) cab.commit(db) for f in tmpfiles: os.unlink(f) # See "Registry Table", "Component Table" def add_registry(db): # File extensions, associated with the REGISTRY.def component # IDLE verbs depend on the tcltk feature. # msidbComponentAttributesRegistryKeyPath = 4 # -1 for Root specifies "dependent on ALLUSERS property" tcldata = [] if have_tcl: tcldata = [ ("REGISTRY.tcl", msilib.gen_uuid(), "TARGETDIR", registry_component, None, "py.IDLE")] add_data(db, "Component", # msidbComponentAttributesRegistryKeyPath = 4 [("REGISTRY", msilib.gen_uuid(), "TARGETDIR", registry_component, None, "InstallPath"), ("REGISTRY.doc", msilib.gen_uuid(), "TARGETDIR", registry_component, None, "Documentation"), ("REGISTRY.def", msilib.gen_uuid(), "TARGETDIR", registry_component, None, None)] + tcldata) # See "FeatureComponents Table". # The association between TclTk and pythonw.exe is necessary to make ICE59 # happy, because the installer otherwise believes that the IDLE and PyDoc # shortcuts might get installed without pythonw.exe being install. This # is not true, since installing TclTk will install the default feature, which # will cause pythonw.exe to be installed. # REGISTRY.tcl is not associated with any feature, as it will be requested # through a custom action tcldata = [] if have_tcl: tcldata = [(tcltk.id, "pythonw.exe")] add_data(db, "FeatureComponents", [(default_feature.id, "REGISTRY"), (htmlfiles.id, "REGISTRY.doc"), (ext_feature.id, "REGISTRY.def")] + tcldata ) # Extensions are not advertised. For advertised extensions, # we would need separate binaries that install along with the # extension. pat = r"Software\Classes\%sPython.%sFile\shell\%s\command" ewi = "Edit with IDLE" pat2 = r"Software\Classes\%sPython.%sFile\DefaultIcon" pat3 = r"Software\Classes\%sPython.%sFile" pat4 = r"Software\Classes\%sPython.%sFile\shellex\DropHandler" tcl_verbs = [] if have_tcl: tcl_verbs=[ ("py.IDLE", -1, pat % (testprefix, "", ewi), "", r'"[TARGETDIR]pythonw.exe" "[TARGETDIR]Lib\idlelib\idle.pyw" -e "%1"', "REGISTRY.tcl"), ("pyw.IDLE", -1, pat % (testprefix, "NoCon", ewi), "", r'"[TARGETDIR]pythonw.exe" "[TARGETDIR]Lib\idlelib\idle.pyw" -e "%1"', "REGISTRY.tcl"), ] add_data(db, "Registry", [# Extensions ("py.ext", -1, r"Software\Classes\."+ext, "", "Python.File", "REGISTRY.def"), ("pyw.ext", -1, r"Software\Classes\."+ext+'w', "", "Python.NoConFile", "REGISTRY.def"), ("pyc.ext", -1, r"Software\Classes\."+ext+'c', "", "Python.CompiledFile", "REGISTRY.def"), ("pyo.ext", -1, r"Software\Classes\."+ext+'o', "", "Python.CompiledFile", "REGISTRY.def"), # MIME types ("py.mime", -1, r"Software\Classes\."+ext, "Content Type", "text/plain", "REGISTRY.def"), ("pyw.mime", -1, r"Software\Classes\."+ext+'w', "Content Type", "text/plain", "REGISTRY.def"), #Verbs ("py.open", -1, pat % (testprefix, "", "open"), "", r'"[TARGETDIR]python.exe" "%1" %*', "REGISTRY.def"), ("pyw.open", -1, pat % (testprefix, "NoCon", "open"), "", r'"[TARGETDIR]pythonw.exe" "%1" %*', "REGISTRY.def"), ("pyc.open", -1, pat % (testprefix, "Compiled", "open"), "", r'"[TARGETDIR]python.exe" "%1" %*', "REGISTRY.def"), ] + tcl_verbs + [ #Icons ("py.icon", -1, pat2 % (testprefix, ""), "", r'[DLLs]py.ico', "REGISTRY.def"), ("pyw.icon", -1, pat2 % (testprefix, "NoCon"), "", r'[DLLs]py.ico', "REGISTRY.def"), ("pyc.icon", -1, pat2 % (testprefix, "Compiled"), "", r'[DLLs]pyc.ico', "REGISTRY.def"), # Descriptions ("py.txt", -1, pat3 % (testprefix, ""), "", "Python File", "REGISTRY.def"), ("pyw.txt", -1, pat3 % (testprefix, "NoCon"), "", "Python File (no console)", "REGISTRY.def"), ("pyc.txt", -1, pat3 % (testprefix, "Compiled"), "", "Compiled Python File", "REGISTRY.def"), # Drop Handler ("py.drop", -1, pat4 % (testprefix, ""), "", "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"), ("pyw.drop", -1, pat4 % (testprefix, "NoCon"), "", "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"), ("pyc.drop", -1, pat4 % (testprefix, "Compiled"), "", "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"), ]) # Registry keys prefix = r"Software\%sPython\PythonCore\%s" % (testprefix, short_version) add_data(db, "Registry", [("InstallPath", -1, prefix+r"\InstallPath", "", "[TARGETDIR]", "REGISTRY"), ("InstallGroup", -1, prefix+r"\InstallPath\InstallGroup", "", "Python %s" % short_version, "REGISTRY"), ("PythonPath", -1, prefix+r"\PythonPath", "", r"[TARGETDIR]Lib;[TARGETDIR]DLLs", "REGISTRY"), ("Documentation", -1, prefix+r"\Help\Main Python Documentation", "", "[TARGETDIR]Doc\\"+docfile , "REGISTRY.doc"), ("Modules", -1, prefix+r"\Modules", "+", None, "REGISTRY"), ("AppPaths", -1, r"Software\Microsoft\Windows\CurrentVersion\App Paths\Python.exe", "", r"[TARGETDIR]Python.exe", "REGISTRY.def"), ("DisplayIcon", -1, r"Software\Microsoft\Windows\CurrentVersion\Uninstall\%s" % product_code, "DisplayIcon", "[TARGETDIR]python.exe", "REGISTRY") ]) # Shortcuts, see "Shortcut Table" add_data(db, "Directory", [("ProgramMenuFolder", "TARGETDIR", "."), ("MenuDir", "ProgramMenuFolder", "PY%s%s|%sPython %s.%s" % (major,minor,testprefix,major,minor))]) add_data(db, "RemoveFile", [("MenuDir", "TARGETDIR", None, "MenuDir", 2)]) tcltkshortcuts = [] if have_tcl: tcltkshortcuts = [ ("IDLE", "MenuDir", "IDLE|IDLE (Python GUI)", "pythonw.exe", tcltk.id, r'"[TARGETDIR]Lib\idlelib\idle.pyw"', None, None, "python_icon.exe", 0, None, "TARGETDIR"), ("PyDoc", "MenuDir", "MODDOCS|Module Docs", "pythonw.exe", tcltk.id, r'"[TARGETDIR]Tools\scripts\pydocgui.pyw"', None, None, "python_icon.exe", 0, None, "TARGETDIR"), ] add_data(db, "Shortcut", tcltkshortcuts + [# Advertised shortcuts: targets are features, not files ("Python", "MenuDir", "PYTHON|Python (command line)", "python.exe", default_feature.id, None, None, None, "python_icon.exe", 2, None, "TARGETDIR"), # Advertising the Manual breaks on (some?) Win98, and the shortcut lacks an # icon first. #("Manual", "MenuDir", "MANUAL|Python Manuals", "documentation", # htmlfiles.id, None, None, None, None, None, None, None), ## Non-advertised shortcuts: must be associated with a registry component ("Manual", "MenuDir", "MANUAL|Python Manuals", "REGISTRY.doc", "[#%s]" % docfile, None, None, None, None, None, None, None), ("Uninstall", "MenuDir", "UNINST|Uninstall Python", "REGISTRY", SystemFolderName+"msiexec", "/x%s" % product_code, None, None, None, None, None, None), ]) db.Commit() def build_pdbzip(): pdbexclude = ['kill_python.pdb', 'make_buildinfo.pdb', 'make_versioninfo.pdb'] path = "python-%s%s-pdb.zip" % (full_current_version, msilib.arch_ext) pdbzip = zipfile.ZipFile(path, 'w') for f in glob.glob1(os.path.join(srcdir, PCBUILD), "*.pdb"): if f not in pdbexclude and not f.endswith('_d.pdb'): pdbzip.write(os.path.join(srcdir, PCBUILD, f), f) pdbzip.close() db,msiname = build_database() try: add_features(db) add_ui(db) add_files(db) add_registry(db) remove_old_versions(db) db.Commit() finally: del db # Merge CRT into MSI file. This requires the database to be closed. mod_dir = os.path.join(os.environ["ProgramFiles"], "Common Files", "Merge Modules") if msilib.Win64: modules = ["Microsoft_VC90_CRT_x86_x64.msm", "policy_9_0_Microsoft_VC90_CRT_x86_x64.msm"] else: modules = ["Microsoft_VC90_CRT_x86.msm","policy_9_0_Microsoft_VC90_CRT_x86.msm"] for i, n in enumerate(modules): modules[i] = os.path.join(mod_dir, n) def merge(msi, feature, rootdir, modules): cab_and_filecount = [] # Step 1: Merge databases, extract cabfiles m = msilib.MakeMerge2() m.OpenLog("merge.log") m.OpenDatabase(msi) for module in modules: print module m.OpenModule(module,0) m.Merge(feature, rootdir) print "Errors:" for e in m.Errors: print e.Type, e.ModuleTable, e.DatabaseTable print " Modkeys:", for s in e.ModuleKeys: print s, print print " DBKeys:", for s in e.DatabaseKeys: print s, print cabname = tempfile.mktemp(suffix=".cab") m.ExtractCAB(cabname) cab_and_filecount.append((cabname, len(m.ModuleFiles))) m.CloseModule() m.CloseDatabase(True) m.CloseLog() # Step 2: Add CAB files i = msilib.MakeInstaller() db = i.OpenDatabase(msi, constants.msiOpenDatabaseModeTransact) v = db.OpenView("SELECT LastSequence FROM Media") v.Execute(None) maxmedia = -1 while 1: r = v.Fetch() if not r: break seq = r.IntegerData(1) if seq > maxmedia: maxmedia = seq print "Start of Media", maxmedia for cabname, count in cab_and_filecount: stream = "merged%d" % maxmedia msilib.add_data(db, "Media", [(maxmedia+1, maxmedia+count, None, "#"+stream, None, None)]) msilib.add_stream(db, stream, cabname) os.unlink(cabname) maxmedia += count # The merge module sets ALLUSERS to 1 in the property table. # This is undesired; delete that v = db.OpenView("DELETE FROM Property WHERE Property='ALLUSERS'") v.Execute(None) v.Close() db.Commit() merge(msiname, "SharedCRT", "TARGETDIR", modules) # certname (from config.py) should be (a substring of) # the certificate subject, e.g. "Python Software Foundation" if certname: os.system('signtool sign /n "%s" /t http://timestamp.verisign.com/scripts/timestamp.dll %s' % (certname, msiname)) if pdbzip: build_pdbzip()
acgtun/acgtun.com
refs/heads/master
acgtun/dict/dictionary.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import # Create your views here. from django.http import HttpResponse from django.template.loader import render_to_string from django.conf import settings import os import sys import string import pickle sys.path.append(os.path.join(settings.BASE_DIR, 'common')) word_directoin = os.path.join(settings.DATABASE_DIR, 'dictionary') def to_html(word): html = '' for w in word: attrs = w['attribute'] for att in attrs[:-1]: html += att html += '&nbsp;&nbsp;' html += attrs[-1] html += '<br>' definitions = w['definition'] for definition in definitions: head = definition['head'] means = definition['means'] if head != None: head = str(head) head = head.replace('h6', 'h4') html += str(head) html += '<ol>' for mean in means: html += '<li>' if type(mean) is list: for m in mean: html += m html += '<br>' else: html += mean html += '</li>' html += '</ol>' html += '<hr>\n' return html def search(request): print('fklsdjflks') word = request.GET.get('word') return as_view(request, word) def index(request): response = HttpResponse() response.write(render_to_string('dict/index.html')) response.close() return response def as_view(request, word=None): if(word == None): return index(request) print('word={}'.format(word)) if len(word) == 0: response = HttpResponse() response.write(render_to_string('dict/word.html', {'word': word, 'valid': False, 'message': 'The search sequence should not be empty.'})) response.close() return response word = word.replace(' ', '-') l = len(word) file = '/^^A' if l >= 2 and word[0] in string.ascii_lowercase and word[1] in string.ascii_lowercase: file = os.path.join(word_directoin, '{}{}'.format(word[0], word[1]), '{}.dict'.format(word)) elif word[0] in string.ascii_uppercase: file = os.path.join(word_directoin, '{}'.format(word[0]), '{}.dict'.format(word)) else: file = os.path.join(word_directoin, 'other', '{}.dict'.format(word)) # print(file) if not os.path.exists(file): new_word = word[0] new_word = str(new_word) new_word = new_word.upper() new_word = new_word + word[1:] word = new_word # print(word) if word[0] in string.ascii_uppercase: file = os.path.join(word_directoin, '{}'.format(word[0]), '{}.dict'.format(word)) else: file = os.path.join(word_directoin, 'other', '{}.dict'.format(word)) # prin(file) if os.path.exists(file): word_content = pickle.load(open(file, "rb")) valid = True message = to_html(word_content) else: message = '{} NOT FOUND'.format(word) valid = False response = HttpResponse() response.write(render_to_string('dict/word.html', {'word': word, 'valid': valid, 'message': message})) response.close() return response
tovrstra/horton
refs/heads/master
horton/io/test/test_cp2k.py
4
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2017 The HORTON Development Team # # This file is part of HORTON. # # HORTON 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. # # HORTON 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/> # # -- """Tests for CP2K ATOM output reader.""" from nose.tools import assert_raises from horton import * # pylint: disable=wildcard-import,unused-wildcard-import from horton.test.common import truncated_file def check_orthonormality(mol): """Helper function to test if the orbitals are orthonormal.""" olp = mol.obasis.compute_overlap() mol.orb_alpha.check_orthonormality(olp) if hasattr(mol, 'orb_beta'): mol.orb_beta.check_orthonormality(olp) def test_atom_si_uks(): fn_out = context.get_fn('test/atom_si.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 13 assert (mol.numbers == [14]).all() assert (mol.pseudo_numbers == [4]).all() assert (mol.orb_alpha.occupations == [1, 2.0/3.0, 2.0/3.0, 2.0/3.0]).all() assert (mol.orb_beta.occupations == [1, 0, 0, 0]).all() assert abs(mol.orb_alpha.energies - [-0.398761, -0.154896, -0.154896, -0.154896]).max() < 1e-4 assert abs(mol.orb_beta.energies - [-0.334567, -0.092237, -0.092237, -0.092237]).max() < 1e-4 assert abs(mol.energy - -3.761587698067) < 1e-10 assert (mol.obasis.shell_types == [0, 0, 1, 1, -2]).all() check_orthonormality(mol) def test_atom_o_rks(): fn_out = context.get_fn('test/atom_om2.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 13 assert (mol.numbers == [8]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.orb_alpha.occupations == [1, 1, 1, 1]).all() assert abs(mol.orb_alpha.energies - [0.102709, 0.606458, 0.606458, 0.606458]).max() < 1e-4 assert not hasattr(mol, 'orb_beta') assert abs(mol.energy - -15.464982778766) < 1e-10 assert (mol.obasis.shell_types == [0, 0, 1, 1, -2]).all() check_orthonormality(mol) def test_carbon_gs_ae_contracted(): fn_out = context.get_fn('test/carbon_gs_ae_contracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 18 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.orb_alpha.occupations == [1, 1, 2.0/3.0, 2.0/3.0, 2.0/3.0]).all() assert (mol.orb_alpha.energies == [-10.058194, -0.526244, -0.214978, -0.214978, -0.214978]).all() assert (mol.orb_beta.occupations == [1, 1, 0, 0, 0]).all() assert (mol.orb_beta.energies == [-10.029898, -0.434300, -0.133323, -0.133323, -0.133323]).all() assert mol.energy == -37.836423363057 check_orthonormality(mol) def test_carbon_gs_ae_uncontracted(): fn_out = context.get_fn('test/carbon_gs_ae_uncontracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 640 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.orb_alpha.occupations == [1, 1, 2.0/3.0, 2.0/3.0, 2.0/3.0]).all() assert (mol.orb_alpha.energies == [-10.050076, -0.528162, -0.217626, -0.217626, -0.217626]).all() assert (mol.orb_beta.occupations == [1, 1, 0, 0, 0]).all() assert (mol.orb_beta.energies == [-10.022715, -0.436340, -0.137135, -0.137135, -0.137135]).all() assert mol.energy == -37.842552743398 check_orthonormality(mol) def test_carbon_gs_pp_contracted(): fn_out = context.get_fn('test/carbon_gs_pp_contracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 17 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [4]).all() assert (mol.orb_alpha.occupations == [1, 2.0/3.0, 2.0/3.0, 2.0/3.0]).all() assert (mol.orb_alpha.energies == [-0.528007, -0.219974, -0.219974, -0.219974]).all() assert (mol.orb_beta.occupations == [1, 0, 0, 0]).all() assert (mol.orb_beta.energies == [-0.429657, -0.127060, -0.127060, -0.127060]).all() assert mol.energy == -5.399938535844 check_orthonormality(mol) def test_carbon_gs_pp_uncontracted(): fn_out = context.get_fn('test/carbon_gs_pp_uncontracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 256 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [4]).all() assert (mol.orb_alpha.occupations == [1, 2.0/3.0, 2.0/3.0, 2.0/3.0]).all() assert (mol.orb_alpha.energies == [-0.528146, -0.219803, -0.219803, -0.219803]).all() assert (mol.orb_beta.occupations == [1, 0, 0, 0]).all() assert (mol.orb_beta.energies == [-0.429358, -0.126411, -0.126411, -0.126411]).all() assert mol.energy == -5.402288849332 check_orthonormality(mol) def test_carbon_sc_ae_contracted(): fn_out = context.get_fn('test/carbon_sc_ae_contracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 18 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.orb_alpha.occupations == [1, 1, 1.0/3.0, 1.0/3.0, 1.0/3.0]).all() assert (mol.orb_alpha.energies == [-10.067251, -0.495823, -0.187878, -0.187878, -0.187878]).all() assert not hasattr(mol, 'orb_beta') assert mol.energy == -37.793939631890 check_orthonormality(mol) def test_carbon_sc_ae_uncontracted(): fn_out = context.get_fn('test/carbon_sc_ae_uncontracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 640 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.orb_alpha.occupations == [1, 1, 1.0/3.0, 1.0/3.0, 1.0/3.0]).all() assert (mol.orb_alpha.energies == [-10.062206, -0.499716, -0.192580, -0.192580, -0.192580]).all() assert not hasattr(mol, 'orb_beta') assert mol.energy == -37.800453482378 check_orthonormality(mol) def test_carbon_sc_pp_contracted(): fn_out = context.get_fn('test/carbon_sc_pp_contracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 17 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [4]).all() assert (mol.orb_alpha.occupations == [1, 1.0/3.0, 1.0/3.0, 1.0/3.0]).all() assert (mol.orb_alpha.energies == [-0.500732, -0.193138, -0.193138, -0.193138]).all() assert not hasattr(mol, 'orb_beta') assert mol.energy == -5.350765755382 check_orthonormality(mol) def test_carbon_sc_pp_uncontracted(): fn_out = context.get_fn('test/carbon_sc_pp_uncontracted.cp2k.out') mol = IOData.from_file(fn_out) assert mol.obasis.nbasis == 256 assert (mol.numbers == [6]).all() assert (mol.pseudo_numbers == [4]).all() assert (mol.orb_alpha.occupations == [1, 1.0/3.0, 1.0/3.0, 1.0/3.0]).all() assert (mol.orb_alpha.energies == [-0.500238, -0.192365, -0.192365, -0.192365]).all() assert not hasattr(mol, 'orb_beta') assert mol.energy == -5.352864672201 check_orthonormality(mol) def test_errors(): fn_test = context.get_fn('test/carbon_sc_pp_uncontracted.cp2k.out') with truncated_file('horton.io.test.test_cp2k.test_errors', fn_test, 0, 0) as fn: with assert_raises(IOError): IOData.from_file(fn) with truncated_file('horton.io.test.test_cp2k.test_errors', fn_test, 107, 10) as fn: with assert_raises(IOError): IOData.from_file(fn) with truncated_file('horton.io.test.test_cp2k.test_errors', fn_test, 357, 10) as fn: with assert_raises(IOError): IOData.from_file(fn) with truncated_file('horton.io.test.test_cp2k.test_errors', fn_test, 405, 10) as fn: with assert_raises(IOError): IOData.from_file(fn) fn_test = context.get_fn('test/carbon_gs_pp_uncontracted.cp2k.out') with truncated_file('horton.io.test.test_cp2k.test_errors', fn_test, 456, 10) as fn: with assert_raises(IOError): IOData.from_file(fn)
PreludeAndFugue/PySpend
refs/heads/master
setup.py
1
#!/usr/local/bin/python # -*- coding: utf-8 -*- import sys from distutils.core import setup #from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" setup( # py2exe #windows=['pyspend.py'], #cx_Freeze #executables=[Executable('pyspend/pyspend.py', base=base)], #build_options = {} name='PySpend', version='0.1dev', author='Gary Kerr', author_email='gdrummondk@gmail.com', packages=['pyspend', 'pyspend.test'], package_data={'pyspend': ['config.json', 'pyspend.pyw']}, license='LICENSE.txt', description='Record your expenditure', long_description=open('README.txt').read(), requires=['wxPython'], classifiers=[ 'Environment :: Win32 (MS Windows)', 'Environment :: X11 Applications', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython' ] )
Jaiz909/youtube-dl
refs/heads/master
devscripts/gh-pages/add-version.py
174
#!/usr/bin/env python3 from __future__ import unicode_literals import json import sys import hashlib import os.path if len(sys.argv) <= 1: print('Specify the version number as parameter') sys.exit() version = sys.argv[1] with open('update/LATEST_VERSION', 'w') as f: f.write(version) versions_info = json.load(open('update/versions.json')) if 'signature' in versions_info: del versions_info['signature'] new_version = {} filenames = { 'bin': 'youtube-dl', 'exe': 'youtube-dl.exe', 'tar': 'youtube-dl-%s.tar.gz' % version} build_dir = os.path.join('..', '..', 'build', version) for key, filename in filenames.items(): url = 'https://yt-dl.org/downloads/%s/%s' % (version, filename) fn = os.path.join(build_dir, filename) with open(fn, 'rb') as f: data = f.read() if not data: raise ValueError('File %s is empty!' % fn) sha256sum = hashlib.sha256(data).hexdigest() new_version[key] = (url, sha256sum) versions_info['versions'][version] = new_version versions_info['latest'] = version with open('update/versions.json', 'w') as jsonf: json.dump(versions_info, jsonf, indent=4, sort_keys=True)
zzqcn/wireshark
refs/heads/zzqcn
test/suite_dfilter/group_scanner.py
3
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu> # # SPDX-License-Identifier: GPL-2.0-or-later import unittest import fixtures from suite_dfilter.dfiltertest import * @fixtures.uses_fixtures class case_scanner(unittest.TestCase): trace_file = "http.pcap" def test_dquote_1(self, checkDFilterCount): dfilter = 'http.request.method == "HEAD"' checkDFilterCount(dfilter, 1) def test_dquote_2(self, checkDFilterCount): dfilter = 'http.request.method == "\\x48EAD"' checkDFilterCount(dfilter, 1) def test_dquote_3(self, checkDFilterCount): dfilter = 'http.request.method == "\\x58EAD"' checkDFilterCount(dfilter, 0) def test_dquote_4(self, checkDFilterCount): dfilter = 'http.request.method == "\\110EAD"' checkDFilterCount(dfilter, 1) def test_dquote_5(self, checkDFilterCount): dfilter = 'http.request.method == "\\111EAD"' checkDFilterCount(dfilter, 0) def test_dquote_6(self, checkDFilterCount): dfilter = 'http.request.method == "\\HEAD"' checkDFilterCount(dfilter, 1)
jcrocholl/nxdom
refs/heads/master
dictionaries/english.py
1
# Copyright 2000-2004 by Kevin Atkinson # Python wrapper by Johann C. Rocholl # # Permission to use, copy, modify, distribute and sell these word # lists, the associated scripts, the output created from the scripts, # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appears in all copies and # that both that copyright notice and this permission notice appear in # supporting documentation. Kevin Atkinson makes no representations # about the suitability of this array for any purpose. It is provided # "as is" without express or implied warranty. SCOWL10 = set(""" a abilities ability able about above absence absolute absolutely abuse academic accept acceptable accepted accepting accepts access accessible accident accidental accidentally accord accorded according accordingly accords account accounts accuracy accurate achieve achieved achieves achieving acquire acquired acquires acquiring across act acted acting action actions active activities activity acts actual actually add added adding addition additional address addressed addresses addressing adds adequate adjust administration admit admits admitted admittedly admitting adopt adopted adopting adopts advance advanced advances advancing advantage advantages advertise advertised advertises advertising advice advise advised advises advising affair affairs affect affected affecting affects afford afraid after afternoon again against age agency ages ago agree agreed agreeing agreement agrees ahead aid aim aimed aiming aims air alarm album algorithm algorithms alias alive all allow allowed allowing allows almost alone along already also alter altered altering alternate alternative alternatively alternatives alters although altogether always am ambiguous among amongst amount amounts amuse amused amuses amusing an analogue analysis ancient and angle angry animal announce announcement annoy annoyed annoying annoys annual anonymous another answer answered answering answers any anybody anyone anyplace anything anyway anywhere apart apologies apology apparent apparently appeal appear appearance appeared appearing appears apple application applications applied applies apply applying appreciate appreciated appreciates appreciating approach appropriate approval approve approved approves approving arbitrary are area areas argue argued argues arguing argument arguments arise arises arithmetic arm army around arrange arranged arrangement arrangements arranges arranging arrive arrived arrives arriving art article articles artificial artist as aside ask asked asking asks asleep aspect aspects assembler assembly assistant associate associated associates associating association assume assumed assumes assuming assumption assure assured assures assuring at ate atmosphere attach attached attaching attack attempt attempted attempting attempts attend attended attending attends attention attitude attract attractive audience author authorities authority authors automatic automatically automobile autumn available average avoid avoided avoiding avoids awake award aware away awful awkward back backed background backing backs backwards bad badly balance ball ban band bank bar bars base based bases basic basically basing basis battery be bear bearing bears beautiful became because become becomes becoming bed been before beforehand began begin beginning begins begun behalf behave behind being believe believed believes believing belong belongs below benefit benefits besides best bet bets better betting between beyond bid bidding bids big bigger biggest bill binary bind binding binds biology bit bite bites biting bits bitten bizarre black blame blank block blow blue board boards boat bodies body book books boot bore borne borrow borrowed borrowing borrows both bother bothered bothering bothers bottle bottom bought bound box boxes boy bracket brackets branch branches brand breach break breaking breaks bridge brief briefly bright bring bringing brings broadcast broadcasting broadcasts broke broken brother brought brown bucket budget buffer bug bugs build building buildings builds built bulk bulletin buried buries bury burying bus business busy but button buy buying buys by byte bytes calculate calculation calculations call called calling calls came campaign can candidate cannot capable capacity capital captain car card cardboard cards care careful carefully cares carried carries carry carrying case cases cassette cat catch catches catching categories category caught cause caused causes causing cease cell cent central century certain certainly chain chair chairman chance chances change changed changes changing channel channels chaos chapter char character characters charge charged charges charging chars cheap cheaper cheapest checked checking chemical child children chip chips choice choose chooses choosing chose chosen church circle circuit circulation circumstance circumstances citizen city claim claimed claiming claims clarify class classes clean clear cleared clearer clearest clearing clearly clears clever clock close closed closely closer closes closest closing club clue code coded codes coding coffee cold collapse collect collected collecting collection collects college colleges column combination combinations combine combined combines combining come comes coming command commands comment commented commenting comments commercial commission commitment committee common commonly communicate communication communications community company comparable comparatively compare compared compares comparing comparison compatibility compatible competition compiler complain complained complaining complains complaint complaints complete completed completely completes completing complex complexity complicate complicated complicates complicating component components compose composed composes composing composition comprehensive compromise compulsory compute computed computer computers computes computing concept concern concerned concerning concerns conclusion concrete condition conditions conference confident confirm confirmed confirming confirms confuse confused confuses confusing confusion connect connected connecting connection connections connects consequence consequences consequently consider considerable considerably consideration considered considering considers consist consistency consistent consists constant constraint constraints construct consumption contact contain contained containing contains content contents context continually continuation continue continued continues continuing continuous continuously contract contrary contrast contribute contribution contributions control controlled controlling controls convenient convention conventional conventions conversation convert convince convinced convinces convincing cope copied copies copy copying core corner corners correct corrected correcting correction correctly corrects corrupt corrupted corrupting corrupts cost costing costs could council count counted counter counting country counts county couple course courses court cover covered covering covers crash crashed crashes crashing crazy create created creates creating creation creature credit crisis crisp crisps critical criticism cross cry cs culture cumming cums cup cure curious current currently cursor customer cut cuts cutting cycle cycles daily damage damaged damages damaging danger dangerous dare dark data database date dated dates dating datum day days dead deal dealing deals dealt dear death debate decade decent decide decided decides deciding decision decisions declare declared declares declaring decrease dedicate dedicated dedicates dedicating deduce deem deemed deeming deems deep deeply default define defined defines defining definite definitely definition definitions definitive degree degrees delay delete deleted deletes deleting deliberate deliberately deliver delivered delivering delivers delivery demand demands democratic demonstrate demonstration department depend depended depending depends depth derive derived derives deriving describe described describes describing description descriptions design designed designing designs desirable desire desired desires desiring desk desperate despite destroy destroyed destroying destroys detail detailed detailing details detect detected detecting detects determine determined determines determining develop developed developing development develops device devices devote devoted devotes devoting dictionary did die died dies differ difference differences different differently difficult difficulties difficulty digit digital digits dinner direct directed directing direction directions directly director directory directs dirty disadvantage disagree disappear disappeared disappearing disappears disaster disc discipline discount discourage discouraged discourages discouraging discover discovered discovering discovers discs discuss discussed discusses discussing discussion discussions disk dislike display displayed displaying displays distance distant distinct distinction distinctly distinguish distribute distributed distributes distributing distribution district disturb disturbed disturbing disturbs ditto divide divided divides dividing division do document documentation documented documenting documents doe does dog doing dollar domain done door doors double doubt doubtful down dozen dozens drastic draw drawing drawn draws dream drew drink drive driven driver drivers drives driving drop dropped dropping drops drove dry dubious due dumb dump during duty dying each earlier earliest early earth ease easier easiest easily east easy eat eaten eating eats economic economy edge edit edited editing edition editor editors edits education educational effect effective effectively effects efficient effort efforts eight either elect elected electing election electric electronic electronics elects element elements elevator else elsewhere embarrass embarrassed embarrasses embarrassing emergency emphasis employee empty enable enables encounter encountered encountering encounters encourage encouraged encourages encouraging end ended ending ends enemy engineer engineered engineering engineers enjoy enormous enough ensure ensured ensures ensuring enter entered entering enters entire entirely entitle entitled entitles entitling entity entrance entries entry environment equal equally equipment equivalent eraser err error errors escape especially essential essentially establish established establishes establishing establishment estimate even evened evening evenings evens event events eventually ever every everybody everyone everything everywhere evidence exact exactly examine examined examines examining example examples excellent except exception exceptions excess excessive exchange exclude excluded excludes excluding exclusive excuse execute executed executes executing exercise exist existed existence existing exists expand expanded expanding expands expansion expect expected expecting expects expense expensive experience experienced experiences experiencing experiment experimental experiments expert experts explain explained explaining explains explanation explicit express expressed expresses expressing expression extend extended extending extends extension extensive extent external extra extract extreme extremely eye eyes face facilities facility fact factor factors facts fail failed failing fails failure fair fairly faith fall fallen falling falls false familiar family famous fan fancy far farm farther farthest fashion fast faster fastest fatal fate father fault faults fear feasible feature features fed federal feed feedback feeding feeds feel feeling feels feet fell felt few fewer fewest field fields fight figure figures file filed files filing fill filled filling fills film final finally financial find finding finds fine finger fingers finish finished finishes finishing finite fire firm firmly first firstly fiscal fish fishes fit fits fitted fitting five fix fixed fixes fixing flag flash flashed flashes flashing flat flew flexible flied flies flight float floated floating floats floor flow flown fly flying folk folks follow followed following follows food foot for force forced forces forcing foreign forever forget forgets forgetting forgot forgotten form formal format formed former forming forms forth forthcoming fortunately fortune forward found four fourth fraction frame free freedom freely french frequent frequently fresh friend friendly friends fries from front fry full fully fun function functions fund fundamental fundamentally funds funny further furthest future gain gained gaining gains game games gap garbage garden gas gasoline gather gave general generally generate generated generates generating generation genuine get gets getting girl give given gives giving glad glass global go goes going gone good goods got gotten government governor gradually graduate grand grands grant granted granting grants graph graphic graphics grateful grave great greater greatest greatly green grew grind grinding grinds gross grosses ground grounds group groups grow growing grown grows growth guarantee guaranteed guaranteeing guarantees guard guess guessed guesses guessing guide gun guy habit habits hack had hair half hall hand handed handing handle handled handles handling hands handy hang hanged hanging hangs happen happened happening happens happily happy hard harder hardest hardly hardware harm harmful harmless has hat hate have having he head headed header heading heads health healthy hear heard hearing hears heart heat heavily heavy held hell hello help helped helpful helping helps hence her here hereby herself hid hidden hide hides hiding high higher highest highly hill him himself hint hints his historical history hit hits hitting hold holding holds hole holes holiday holidays home honest hope hoped hopefully hopes hoping horrible horse horses hospital host hot hotel hour hours house how however huge human hundred hundreds hung hunt hurry husband ice idea ideal ideas identical identify identity if ignore ignored ignores ignoring ill illegal image images imagination imagine immediate immediately impact implement implemented implementing implements implication implications implied implies imply implying importance important importantly impose imposed imposes imposing impossible impression improve improved improvement improvements improves improving in inability inadequate inch inches incident incidentally incline inclined inclines inclining include included includes including income incompatible incomplete inconsistent inconvenience incorrect increase increased increases increasing indeed independent independently index indicate indicates indication individual individually individuals industrial industry inevitably inferior infinite influence info inform information informed informing informs initial initially initials inner innocent input inputs inputted inputting insert inserted inserting inserts inside insist insisted insisting insists install installed installing installs instance instant instantly instead institution institutions instruction instructions insurance integer integers integral intelligence intelligent intend intended intending intends intention interact interest interested interesting interests interface internal international interpret interpretation interpreted interpreting interprets interval intervals intervention into introduce introduced introduces introducing introduction invalid invariably invent invented inventing invents investigate invisible invitation invite invited invites inviting involve involved involves involving irrelevant irritate irritated irritates irritating is isolate isolated isolates isolating issue issued issues issuing it item items its itself job jobs join joined joining joins joint joke joy judge jump jumps junk just justification justified justifies justify justifying keen keep keeping keeps kept key keyboard keys kid kill killed killing kills kind kindly kinds king knew knock knocked knocking knocks know knowing knowledge known knows label labels laboratory lack lacked lacking lacks ladies lady lain land landed landing lands language languages large largely larger largest last lasts late later latest latter law laws lay layout lazy leach lead leaded leader leading leads leaf learn learning learns least leave leaved leaves leaving lecture lectures led left leg legal legally legs lend length less lesser lesson lessons let lets letter letters letting level levels liable libraries library lie lied lies life lifetime lift light lights like liked likely likes likewise liking limit limited limiting limits line linear lines link linked linking links list listed listen listing lists literally literature little live lived lives living load loaded loading loads loan local location locations lock locked locking locks log logged logging logic logical logs long longer longest look looked looking looks loop loose lorry lose loses losing loss lost lot lots loudly love low lower lowest luck lucky lunch lying machine machines mad made magic magnetic magnitude mail main mainly maintain maintained maintaining maintains major majority make makes making man manage managed manager manages managing manipulation manner manual manuals many map march mark marked market marking marks marriage marry mass massive master match matches material materials mathematical mathematics matter matters maximum may maybe me mean meaning meaningful meaningless meanings means meant measure measured measures measuring mechanic mechanics mechanism media medical medium mediums meet meeting meetings meets member members membership memory men mention mentioned mentioning mentions mere merely merit merits mess message messages messy met metal method methods middle midnight might mile miles military million millions mind minded minding minds mine minimal minimum minor minority minute minutes mislead misleading misleads misled miss missed misses missing mistake mistaken mistakes mistaking mistook misunderstand misunderstanding misunderstands misunderstood misuse mix mixed mixes mixing mod mode model models modern modified modifies modify modifying moment money monitor month months moral more morning mornings most mostly mother motion mouth move moved movement movements moves movie moving much multiple music must my myself mysterious naive name named namely names naming nasty nation national natural naturally nature naughty near nearby nearer nearest nearly necessarily necessary necessity neck need needed needing needs negative neither nervous net network networks never nevertheless new news next nice nicer nicest night nine no nobody noise noisy none nonsense nor normal normally north not note noted notes nothing notice noticed notices noticing notify noting novel now nowadays nowhere numb number numbers numbest numerical numerous obey object objected objecting objection objections objects obscure observation observe observed observes observing obtain obtained obtaining obtains obvious obviously occasion occasional occasionally occasions occupied occupies occupy occupying occur occurred occurring occurs odd odds of off offer offered offering offers office officer offices official often oh oil old older oldest omit omits omitted omitting on once one ones only onto open opened opening opens operate operated operates operating operation operations operator operators opinion opinions opportunities opportunity oppose opposed opposes opposing opposite opposition option optional options or order ordered ordering orders ordinary origin original originally other others otherwise ought our ours ourselves out outer output outside over overall owe owed owes owing own owner owners pack package packages packet page pages paid pain painful pair pairs paper papers paragraph parallel parent park part partial partially particular particularly parties partly parts party pass passed passes passing past patch path patient pattern patterns pause pay payed paying pays peace peak peculiar pen people per perfect perfectly perform performance performed performing performs perhaps period permanent permanently permission permit permits permitted permitting person personal personally persons persuade persuaded persuades persuading petrol phase phenomenon philosophy phone phrase phrases physical pi pick picked picking picks picture pictures piece pieces pile pint pipe place placed places placing plain plan plane planet planned planning plans plant plastic play played playing plays plea pleasant please pleased pleases pleasing plenty plot plots plug plus pocket poem poet point pointed pointing pointless points police policies policy political poll pool poor pop popular population port position positions positive possibilities possibility possible possibly post posted posting postmaster posts potential potentially pound pounds power powerful powers practical practically precise precisely prefer preferable preferably preference preferred preferring prefers preparation prepare prepared prepares preparing presence present presented presenting presents preserve president press pressed presses pressing pressure presumably presume pretty prevent prevented preventing prevents previous previously price prices primary prime primitive principle principles print printed printer printers printing printout prints prior private probably problem problems procedure process processed processes processing processor processors produce produced produces producing product production products professional programmer programmers progress project projects promise promised promises promising prompt promptly prone proof proper properly properties property proportion proposal propose proposed proposes proposing prospect protect protected protecting protection protects protest prove proved proves provide provided provides providing proving public publication publicity publicly publish published publishes publishing pull pulled pulling pulls punctuation puncture purchase pure purely purpose purposes push pushed pushes pushing put puts putt putted putting putts qualified qualifies qualify qualifying quality quantities quantity quarter question questions queue quick quicker quickest quickly quiet quietly quit quite quits quitting quote quoted quotes quoting race radio rain raise raised raises raising ran random randomly range rapid rapidly rare rarely rate rates rather raw re reach reached reaches reaching react reaction read readable reader readers readily reading reads ready real reality really reason reasonable reasonably reasons recall receive received receives receiving recent recently reception recognition recommend recommendation recommended recommending recommends record recorded recording records recover recovered recovering recovers red reduce reduced reduces reducing reduction redundant refer reference references referred referring refers reflect reflected reflecting reflection reflects refuse refused refuses refusing regard regarded regarding regardless regards region register registered registering registers regret regular regularly regulation regulations reject rejected rejecting rejects relate related relates relating relation relationship relative relatively release released releases releasing relevance relevant reliable religion religious reluctant rely remain remained remaining remains remark remarks remember remembered remembering remembers remind reminded reminding reminds remote remotely removal remove removed removes removing repair repeat repeated repeatedly repeating repeats replace replaced replacement replaces replacing replied replies reply replying report reported reporting reports represent representation representative represented representing represents reproduce request requested requesting requests require required requirement requirements requires requiring research reserve reserved reserves reserving resident resolution resort resource resourced resources resourcing respect respectively respects respond response responses responsibility responsible rest restart restore restored restores restoring restrict restricted restricting restricts result resulted resulting results retain return returned returning returns reveal revealed revealing reveals reverse review rewrite rid ridding ride ridiculous rids right rights ring rise risk river road role roll room rooms root rough roughly round route routine row rubber rubbish rule rules run running runs rush sad sadly safe safely safer safest safety said saint sake sale sales same sample sat satisfied satisfies satisfy satisfying save saved saves saving saw say saying says scale scan scene scheme school schools science sciences scientific score scores scrap scratch screen screens script search searched searches searching season second secondary secondly seconds secret secretary section sections secure security see seeing seek seeking seeks seem seemed seeming seems seen sees select selected selecting selection selects self sell selling sells seminar send sending sends senior sense sensible sensibly sensitive sent sentence sentences separate separately sequence sequences serial series serious seriously serve served server serves service services serving session sessions set sets setting settle settled settles settling seven several severe severely sex shall shame shape share shared shares sharing sharp she sheet shelf shell shift ship shoot shop shopped shopping shops short shortage shorter shortest shortly should show showed showing shown shows shut shuts shutting side sides sight sign signal signals signed significance significant significantly signing signs silly similar similarly simple simpler simplest simply simultaneous simultaneously since sincerely single sit site sites sits sitting situation situations six size sizes skill skills sleep slight slightly slip slow slower slowest slowly small smaller smallest smile smooth so social society soft software sold solely solid solution solutions solve solved solves solving some somebody somehow someone someplace something sometime sometimes somewhat somewhere son soon sooner soonest sophisticate sophisticated sophisticates sophisticating sorry sort sorted sorting sorts sought sound sounded sounding sounds source sources south southern space spaces spare speak speaker speakers speaking speaks special specially specific specifically specified specifies specify specifying speech speed spell spelling spells spend spending spends spent spirit spite split splits splitting spoke spoken spot spots spotted spotting spread spreading spreads spring square stable staff stage stages stand standard standards standing stands start started starting starts state stated statement statements states stating station stations statistic statistical statistics status stay stayed staying stays steal step stick sticking sticks still stock stone stones stood stop stopped stopping stops storage store stored stores storing straight straightforward strange strategy stream street strength strict strictly strike strikes striking string strings strong strongly struck structure structures stuck student students studied studies study studying stuff stupid style subject subjects submit submits submitted submitting subsequent subset substantial substitute subtle succeed success successful successfully such sudden suddenly suffer suffered suffering suffers suffice sufficient sufficiently sugar suggest suggested suggesting suggestion suggestions suggests suit suitable suitably suited suiting suits sum summary summer sun superior supervisor supplied supplies supply supplying support supported supporting supports suppose supposed supposedly supposes supposing sure surely surface surprise surprised surprises surprising survey survive survived survives surviving suspect suspected suspecting suspects suspend suspended suspending suspends suspicion switch switched switches switching symbol symbols syntax system systems table tables take taken takes taking talk talked talking talks tank tanks tape tapes target task tasks taste taught tax tea teach teacher teaches teaching team technical technique techniques technology tedious teeth telephone television tell telling tells temperature temporarily temporary ten tend tendency tends term terminal terminals terminology terms terribly test tested testing tests text than thank thanks that the their them themselves then theoretical theory there thereby therefore these they thin thing things think thinking thinks third this thoroughly those though thought thoughts thousand thousands threat three threw through throughout throw throwing thrown throws thus ticket tickets tie tied ties tight till time timed times timing tin title titles to today together token told tomorrow tonight too took tooth top topic topics total totally touch touched touches touching toward towards town trace track tracks traditional traffic train trained training trains transfer transferred transferring transfers translate translated translates translating translation transport trap trapped trapping traps trash travel treat treated treating treatment treats tree trees trial trick tried tries trip trivial trouble truck true truly trunk trust trusted trusting trusts truth try trying tune turn turned turning turns twelve twenty twice two tying type typed types typical typing ugly ultimate ultimately unable unacceptable unaware uncertain unclear under undergraduate undergraduates underneath understand understanding understands understood unfortunate unfortunately unhappy uniform unique unit unite units universal universities university unknown unless unlike unlikely unlimited unnecessarily unnecessary unpleasant unreasonable unsuitable until unusual unwanted up update updated updates updating upon upper upset upsets upsetting upwards us usage use used useful useless user users uses using usual usually utility utterly vacation vacations vague vaguely valid validity valuable value values van variable variables variation varied varies variety various vary varying vast vastly vector version versions very via vice video view views virtually virtue visible vision visit vital voice volume vote votes wait waited waiting waits walk walked walking walks wall walls want wanted wanting wants war warm warn warned warning warns was wash waste wasted wastes wasting watch watched watches watching water way ways we weapon wear wearing wears weather week weekend weeks weight weird welcome welcomed welcomes welcoming well went were west western what whatever whatsoever wheel wheels when whenever where whereas whereby wherever whether which while whilst white who whoever whole whom whose why wide widely wider widespread widest wife wild will willed willing wills win wind window windows wine winning wins winter wire wise wish wished wishes wishing with withdraw within without woman women won wonder wondered wonderful wondering wonders wooden word worded wording words wore work worked worker workers working works world worn worried worries worry worrying worse worst worth worthwhile worthy would write writer writes writing written wrong wrote year years yellow yes yesterday yet you young your yours yourself zero """.split()) SCOWL20 = set(""" aardvark abandon abandoned abandoning abandons abbreviate abbreviated abbreviates abbreviating abbreviation abbreviations abide abnormal abnormally abolish abolished abolishes abolishing abolition abort aborted aborting abortion aborts abroad absent absorb absorbed absorbing absorbs abstract abstraction absurd abused abuses abusing abusive abysmal academics accelerate accent accents acceptance accessed accesses accessing accidents accommodate accommodation accompanied accompanies accompany accompanying accomplish accomplished accomplishes accomplishing accordance accountant accountants accounted accounting accumulate accumulated accumulates accumulating accurately accusation accusations accuse accused accuses accusing accustom accustomed accustoming accustoms ace achievement achievements acid acknowledge acknowledged acknowledges acknowledging acorn acoustic acquaintance acquisition acronym acronyms activate activated activates activating actively actor actors acute adapt adaptation adapted adapting adapts addict addicted addicting addictive addicts additionally additions adequately adhere adhered adheres adhering adjacent adjective adjusted adjusting adjustment adjustments adjusts administer administered administering administers administrative admirable admiration admire admission adoption adult adults advantageous advent adventure adventures adventurous adverse adversely advert advertisement advertisements adverts advisable adviser advisers advisory advocate advocated advocates advocating aerial aesthetic aesthetically affection aforementioned afternoons aged agenda agent agents aggressive agony agreements agricultural aided aiding aids aircraft airport akin alarmed alarming alarms alas albeit albums alcohol alcoholic alert algebra algebraic aliases alien aliens align aligned aligning alignment aligns alike allegation allegations allege alleged allegedly alleges alleging allergic alleviate alliance allies allocate allocated allocates allocating allocation allocations allowable allowance allowances ally alongside aloud alpha alphabet alphabetic alphabetical alteration alterations amateur amaze amazed amazes amazing amazingly ambassador amber ambient ambiguities ambiguity ambitious amend amended amending amendment amends amp ample amplifier amusement anagram analogous analogy analyst anarchy anatomy ancestor ancestors anecdote anecdotes angel angels anger angles anguish animals anniversary announced announcements announces announcing annoyance annually anomalies anomaly anorak anoraks anthology anticipate anticipated anticipates anticipating anticipation antidote antique antisocial anxious anyhow apathetic apathy apostrophe appalled appalling appallingly apparatus apparatuses appealed appealing appeals appearances append appended appending appendix appends applause applicable applicant applicants appoint appointed appointing appointment appointments appoints appraisal appreciation approached approaches approaching appropriately approximate approximately approximation apt arbitrarily arc arcade arcane arch archaic architecture archive archived archives archiving arena arguable arguably arisen arising armed arming arms arose array arrays arrest arrested arresting arrests arrival arrogance arrogant arrow arrows artificially artistic artists arts ascend ascended ascending ascends ash ashamed ashcan ashes assault assemble assembled assembles assembling assert asserted asserting assertion asserts assess assessed assesses assessing assessment asset assets assign assigned assigning assignment assignments assigns assist assistance assisted assisting assists associations assort assorted assorting assorts assumptions asterisk asterisks astronomer astronomers astronomy asynchronous atheism atheist atheists atlas atmospheric atom atomic atoms atrocities atrocity attachment attacked attacking attacks attain attendance attendant attentions attitudes attorney attorneys attracted attracting attraction attracts attribute attributed attributes attributing audible audiences audio aunt authentic autobiography automate automated automates automating automobiles availability await awaited awaiting awaits awarded awarding awards awareness awfully axes axiom axioms axis babies baby backbone backgrounds backlog backspace backward bacteria bacterium badge baffle baffled baffles baffling bag baggage bags bake baked bakes baking balanced balances balancing ballet ballot balls banal banana bananas bands bandwagon bandwidth bang bankrupt banks banned banner banning bans bare barely bargain bark barked barking barks baroque barred barrel barrier barriers barring barrister barristers basement bash bashed bashes bashing basics basket bass basses bastard bastards bat batch bath bathroom baths batteries battle baud bay beach beam bean beans beard bearded bearding beards beast beasts beat beaten beating beats beautifully beauty bedroom beds beef beer beers beg beginner beginners behaved behaves behaving beings belief beliefs believable believer believers bell bells belonged belonging beloved belt bench bend bending bends beneath beneficial bent beside beta beware bias biased biases biasing bible biblical bicycle bicycles bigot bigoted bigotry billfold billion billions bills bin biochemistry biography biological biologist biologists bird birds birth birthday biscuit biscuits bishop bitmap bitter blackboard blackmail blacks blade blades blamed blames blaming blanket blanks blast blasted blasting blasts blatant blatantly bless blessed blesses blessing blew blind blindly blink bliss blob blocked blocking blocks blood bloody blowing blown blows blues blurb boats bob bobs bog bogged bogging boggle boggles bogs bogus boil boiled boiling boils bold bolt bomb bombed bombing bombs bond bone bones bonus booked booking booklet bookshop bookshops bookstore boom boost boots border borderline bored boredom bores boring born boss bottles bounce boundaries boundary bounds bout bow bowl boys bracketed bracketing brain brains brake brakes branded branding brands brass brave bread breakdown breakfast breath breathe breathed breathes breathing bred breed breeding breeds breeze brethren brick bricks bridges brigade brighter brightest brightly brightness brilliant brilliantly broad broadly brothers browse browsed browses browsing brush brutal bubble buck bucks buffered buffering buffers bugger buggers bulb bulbs bull bullet bullets bump bunch bundle burden bureaucracy burn burned burning burns burnt burst bursting bursts buses bush businesses buss bust butter buttons buyer buyers bye bypass cabbage cabinet cable cabled cables cabling cafe caffeine cage cake cakes calculated calculates calculating calculator calculus calendar caller calm cam camera cameras camp campaigned campaigning campaigns camps campus cancel cancels cancer candidates canonical cans cant cap capabilities capability capitalism capitalist capitals caps capture captured captures capturing carbon cared career careers careless caring carpet carriage carrier carrot carrots cars cartoon cartoons cartridge cartridges cased cash casing cassettes cast casting castle casts casual catastrophic categorically cater catered catering caters cathedral catholic cats cattle causal causality caution cave caveat ceased ceases ceasing ceiling celebrate celebrated celebrates celebrating celebration cells cellular censor censored censoring censors censorship centrally centuries ceremony certainty certificate chains chairs chalk challenge challenged challenges challenging chamber champagne champion chancellor changeover chaotic chap chapel chaps chapters characteristic characteristics charitable charities charity charm charmed charming charms chart charter charts chase chased chases chasing chat chats chatted chatting cheaply cheat cheated cheating cheats cheek cheer cheerful cheers cheese chemicals chemist chemistry chemists chess chest chestnut chew chewed chewing chews chicken chickens chief childhood childish chocolate choices choir chop chopped chopping chops choral chord chorus chuck chucked chucking chucks chunk chunks churches cider cigarette cinema circa circles circuitry circuits circular circulate circulated circulates circulating cite cited cites cities citing citizens civil civilian clarification clarified clarifies clarifying clarity clash clashes classed classic classical classics classification classified classifies classify classifying classing clause clauses cleaned cleaner cleaners cleanest cleaning cleanly cleans clearance cleverer cleverest cliche click client clients cliff climate climb climbed climbing climbs clinic clinical clip clipped clipping clips clique clocks clog clone clones closet closure cloth clothe clothed clothes clothing cloud clouds clubs clues clumsy cluster clusters coach coal coarse coast coat coats cobbler cobblers coherent coin coincide coincidence coined coining coins coke collaboration collapsed collapses collapsing collar collate collated collates collating colleague colleagues collections collective colon colony columns combat comedy comfort comfortable comfortably comic comics comma commandment commandments commas commence commentary commentator commentators commercially commissioned commissioning commissions commit commitments commits committed committees committing commodity commons communal communicated communicates communicating communism communist communists communities compact companies companion comparative comparisons compassion compel compelled compelling compels compensate compensation compete competed competence competent competes competing competitive competitor competitors compilation compile compiled compilers compiles compiling complacent complement complementary completeness completion complication complications compliment comply composer composers composite compound comprehend comprehensible comprehension compress compressed compresses compressing compression comprise comprised comprises comprising compulsion computation computational con concatenate concatenated concatenates concatenating conceal concealed concealing conceals concede conceivable conceivably conceive conceived conceives conceiving concentrate concentrated concentrates concentrating concentration conception concepts conceptual concert concerto concerts concise conclude concluded concludes concluding conclusions concur concurrently condemn condemnation condemned condemning condemns condense condensed condenses condensing conditional conditioned conditioning condom condone conduct conducted conducting conductor conducts conferences confess confidence confidential confidentiality configuration configurations configure configured configures configuring confine confined confines confining confirmation conflict conflicted conflicting conflicts conform confront confronted confronting confronts congest congested congesting congestion congests congratulate congratulations conjecture conjunction connector connotation connotations conscience conscious consciously consciousness consecutive consensus consent consented consenting consents consequent conservation conservative conservatives considerate considerations consisted consistently consisting consolation console conspicuous conspiracy constantly constants constituency constituent constituents constitute constitutes constitution constitutional constrain constrained constraining constrains constructed constructing construction constructions constructive constructs consult consultancy consultant consultants consultation consulted consulting consults consume consumed consumer consumes consuming contacted contacting contacts container contemplate contemplated contemplates contemplating contemporary contempt contend contention contentious contest contexts continent continental continual continuations continuity continuum contour contraception contracted contracting contracts contradict contradicted contradicting contradiction contradictory contradicts contravention contributed contributes contributing contributor contributors contrive contrived contrives contriving controller controllers controversial controversy convenience conveniently conversations converse conversely conversion conversions converted converter converting converts convey convict convicted convicting conviction convictions convicts convincingly cook cooked cookie cookies cooking cooks cool cooled cooling cools cooperate cooperation coordinate coordinates coordination coped copes coping copper copyright corn corporate corporation corpse corpses corrections correlate correlation correspond corresponded correspondence correspondent corresponding corresponds corridor corruption cosmic cosmology costly cotton cough councils counsel counsels counterexample counterpart counterparts countless countries countryside coupled couples coupling courage courier courtesy courts cousin coverage cow cows crack cracked cracking cracks craft cramp cramped cramping cramps crap crass crawl crawled crawling crawls cream creative creator creatures credibility credible credits creed creep crew cricket cried cries crime crimes criminal criminals criteria criterion critic criticisms critics crop crops crossed crosses crossing crossroad crossroads crossword crowd crowded crowding crowds crown crucial crude cruel cruelty cruise cruised cruises cruising crunch crunched crunches crunching crush crushed crushes crushing crying cryptic crystal crystals cube cubic cuckoo cuddly cue culprit cult cultural cultures cumbersome cumulative cunning cupboard cups cured cures curing curiosity curiously curly currency curriculum curry curse curtain curtains curve curves custard custom customary customers customs cute cycled cycling cyclist cyclists cylinder cynic cynical daft damn damnation damned damning damns damp dance danced dances dancing dangerously dangers dared dares daring darkness darling dash dashed dashes dashing databases daughter dawn daylight daytime deadline deadly deaf dealer dealers deaths debatable debated debates debating debt debug debugged debugger debugging debugs decades decay decimal deck declaration declarations decline declined declines declining decode decoded decodes decoding decreased decreases decreasing deduced deduces deducing deduction deductions deed deeds deeper deepest defaults defeat defeated defeating defeats defect defective defects defend defended defending defends deficiencies deficiency defy degenerate degradation degrade degraded degrades degrading deity delayed delaying delays deletion delicate delicious delight delighted delightful delighting delights delimiters delta delusion demanded demanding demented demise democracy democratically demolish demolished demolishes demolishing demonstrated demonstrates demonstrating demonstrations denied denies denominator denote denotes dense density dentist deny denying departmental departments departure dependence deposit depress depressed depresses depressing depression deprive deprived deprives depriving depths deputy derange deranged deranges deranging derivative derogatory descend descended descending descends descriptive desert deserted deserting deserts deserve deserved deserves deserving designate designated designates designating designer designers desktop despair desperately despise destination destine destined destines destining destruction destructive detach detached detaches detaching detectable detection detective detector deter determination deterrent detract devastate devastated devastates devastating developer developers developments deviation devil devious devise devised devises devising devoid diagnosis diagnostic diagnostics diagonal diagram diagrams dial dialect dialects dials diameter diary dice dictate dictator dictatorship dictionaries diesel diet differed differential differentiate differing differs dig digest digging dignity digs dilemma dim dimension dimensional dimensions dine dined diner dines dining dip diplomatic dire directive directives directories directors dirt disable disabled disables disabling disadvantages disagreed disagreeing disagreement disagrees disappoint disappointed disappointing disappointment disappoints disasters disastrous discard discarded discarding discards discharge disciplinary disclaimer disco disconnect disconnected disconnecting disconnects discontinue discontinued discontinues discontinuing discounts discoveries discovery discrepancy discrete discretion discriminate discriminated discriminates discriminating discrimination disease diseases disguise disguised disguises disguising disgust disgusted disgusting disgusts dish dishes dishonest disliked dislikes disliking dismal dismiss dismissed dismisses dismissing disorder disposable disposal dispose disposed disposes disposing disposition dispute disregard disrupt disruption dissertation dissimilar distances distasteful distinctions distinctive distinguished distinguishes distinguishing distort distorted distorting distortion distorts distract distracted distracting distracts distress distressed distresses distressing disturbance ditch dive dived diverse diversity divert diverted diverting diverts dives divine diving divisions divorce doctor doctors doctrine documentary dodge dogma dogs dole dollars domestic dominant dominate dominated dominates dominating don donate donated donates donating donation donations dons doom doomed dooming dooms dose doses dot dots dotted dotting doubled doubles doubling doubtless doubts downhill downright downstairs downwards drag dragged dragging dragon drags drain drained draining drains drama dramatic dramatically drank drastically drawback drawbacks drawings dread dreaded dreadful dreading dreads dreaming dreams dreary dress dressed dresses dressing dried dries drift drill drinking drinks drip dripped dripping drips drivel drown drowned drowning drowns drug drugs drum drums drunk drunken drying dual duck ducks duff dug dull duly dummy dumped dumping dumps dumpster duplicate duplicated duplicates duplicating duplication duration dust dustbin dusty duties dynamic dynamically dynamics eager eagerly eagle ear earn earned earning earns ears eastern eater eccentric echo echoed echoes echoing ecological ecology economical economically economics economies edges editions editorial educate educated educates educating effectiveness efficiency efficiently egg eggs ego egos eh eighteen eighth elaborate elderly elections electoral electorate electrical electricity electron electronically elegant elementary elephant elephants elevators eleven eligible eliminate eliminated eliminates eliminating elite elitist em embarrassment embed embedded embedding embeds emerge emerged emerges emerging eminent eminently emit emotion emotional emotionally emotions empire empirical employ employed employees employer employers employing employment employs emptied empties emptying emulate emulation emulator emulators enabled enabling enclose enclosed encloses enclosing encode encoded encodes encoding encouragement endings endless endlessly enemies energy enforce enforced enforces enforcing engage engaged engages engaging engine engines enhance enhanced enhancement enhances enhancing enjoyable enjoyed enjoying enjoyment enjoys enlarge enlarged enlarges enlarging enlighten enlightened enlightening enlightenment enlightens enormously entail entails enterprise entertain entertained entertaining entertainment entertains enthusiasm enthusiastic entirety entities envelope envelopes environmental environments envisage envisaged envisages envisaging envy epic episode episodes equality equals equate equation equations equilibrium equip equipped equipping equips equivalents era erase erased erases erasing ergo erroneous escaped escapes escaping esoteric essay essays essence establishments estate estimated estimates estimating estimation eternal eternity ethic ethical ethics ethnic etymology evaluate evaluated evaluates evaluating evaluation evenly eventual everyday evident evidently evil evils evolution evolutionary evolve evolved evolves evolving exaggerate exaggerated exaggerates exaggerating exam examination examiner exams exceed exceeded exceeding exceedingly exceeds excepted excepting exceptional exceptionally excepts excessively exchanged exchanges exchanging excite excited excitement excites exciting exclamation exclusion exclusively excuses executable execution executive exempt exercised exercises exercising exhaust exhausted exhausting exhaustive exhausts exhibit exhibition exit exited exiting exits exotic expectation expectations expedition expenditure expenses experimentally experimentation experimented experimenting expertise expire expired expires expiring expiry explanations explanatory explicitly explode exploded explodes exploding exploit exploitation exploited exploiting exploits exploration explore explored explores exploring explosion explosions explosive exponential export expose exposed exposes exposing exposure expressions expressway expressways extant extensions extensively extents externally extinction extracted extracting extraction extracts extraneous extraordinarily extraordinary extras extremes extremist eyesight fabric faced faces facilitate facing factories factory factual factually faculties faculty failures faint fainter faintest fairer fairest fairness fairy faithful fake fallacious fallacy fame familiarity families famine fans fantasies fantastic fantasy farce fare farewell farmer farmers fascinate fascinated fascinates fascinating fascist fashionable fashioned fashioning fashions fat fathers fatuous faucet faulty feared fearing fears feasibility feat featured featuring fee feeble feelings fees fellow fellows female females feminist feminists fence fender fenders festival fetch fever fiction fictional fiddle fiddled fiddles fiddling fierce fifteen fifth fifty fighter fighting fights figured figuring filmed filming films filter filtered filtering filters filthy finals finance finances financially findings fined finer fines finest fining fired fires firework fireworks firing firms fished fishing fiver fizzy flagged flagging flags flame flames flaw flawed flawing flaws fleet flesh flexibility flip flipped flipping flips flood flooded flooding floods floors floppy flour flowed flower flowers flowing flows fluctuation fluctuations fluent fluffy fluid flush flushed flushes flushing flute foam focus fog fold folded folder folders folding folds follower followers fond font fonts foods fool fooled fooling foolish fools football footnote footnotes forbade forbid forbidden forbidding forbids forcibly forecast forecasting forecasts foreigner foreigners foreseeable forest forests forgave forgive forgiven forgives forgiving fork formally formation formats formatted formatting formerly formula formulation fortnight fortunate forty forum forwarded forwarding forwards fossil fought foul foundation foundations founded founding founds fountain fourteen fractions fragile fragment fragments frames framework frank frankly frantic fraud freak freaks freed freeing frees freeway freeways freeze freezes freezing frequencies frequency friction fried friendship frighten frightened frightening frightens fringe frivolous frog frogs frown frowned frowning frowns froze frozen fruit fruits frustrate frustrated frustrates frustrating frustration frying fudge fuel fulfilled fulfilling fuller fullest fume fumes functional functionality functioned functioning fundamentalist funded funding funeral funnier funniest fur furniture furry furthermore fuse fusion fuss fussy futile fuzzy galactic galaxy gang gaps garage garble garbled garbles garbling gardens gasp gate gates gateway gathered gathering gathers gay gear geared gearing gears gender gene generations generator generators generic generous genes genetic genetically genetics genius genocide genre gentle gentleman gentlemen gently genuinely geographical geography geology geometry gesture ghastly ghost giant gibberish gift gifts gig gin girlfriend girls gladly glance glasses glean gleaned gleaning gleans globally glorious glory glossy glove gloves glow glowed glowing glows glue gnome goal goals goat god gods gold golden goldfish goldfishes golf goodbye goodies goodness goody gorgeous gospel gossip govern governed governing governments governs gown grab grabbed grabbing grabs grace grade grades gradual graduated graduates graduating graduation graffiti graffito grain grammar grammatical grandfather grandmother graphical graphs grasp grass gratefully gratuitous gratuitously gravitational gravity greasy greed greedy grid grief grim grip grips groan grossly grouped grouping guarded guarding guards guest guests guidance guided guideline guidelines guides guiding guilt guilty guinea guitar gulf gullible gum guns gut guts gutter guys ha hacked hacker hackers hacking hacks hail haircut hairs hairy halls halt halted halting halts halve halves ham hammer handbook handful handicap handler hangover happier happiest happiness hardback harden hardened hardening hardens hardship hardy harmony harsh hash hassle hasten hasty hated hates hating hatred hats havoc hay hazard hazards hazy headache headers headline headlines heap heartily hearts heated heating heats heaven heavens heavier heaviest heel heels height heights helicopter helmet helpless henceforth herd heresy heritage hero heroes heroic heroin herring herrings hesitate heterosexual hexadecimal hey hided hideous hideously hierarchical hierarchy highlight highlighted highlighting highlights highway highways hilarious hills hindsight hinted hinting hip hire hired hires hiring historian historians historic historically hitherto ho hobby hog holder holders hollow holy homes homosexual homosexuality honestly honesty honey honorary hook hooked hooking hooks hopeful hopeless hopelessly horde hordes horizon horizontal horizontally horn horrendous horrendously horribly horrid horrific horrified horrifies horrify horrifying horror hospitals hostile hosts housed household houses housing hugely huh hum humane humanity humans humble humbly humorous hungry hunted hunting hunts hurt hurting hurts hut hydrogen hyphen hypocrisy hypocrite hypocritical hypothesis hypothetical hysterical icon icons id idealistic ideally ideals identically identification identified identifier identifiers identifies identifying ideological ideology idiom idiosyncratic idiot idiotic idiots idle ignorance ignorant illegally illiterate illness illogical illusion illustrate illustrated illustrates illustrating illustration illustrations imaginary imaginative imagined imagines imagining imbalance immature immense immensely imminent immoral immortal immune impair impaired impairing impairs impend impended impending impends imperative imperfect imperial impersonal implausible implementation implementations implicit implicitly import imported importing imports impractical impress impressed impresses impressing impressions impressive imprison imprisoned imprisoning imprisons improbable impulse inaccessible inaccuracies inaccuracy inaccurate inadvertently inane inappropriate incapable incarnation incentive incidence incidental incidents inclination inclusion inclusive incoherent incoming incompetence incompetent incomprehensible inconsistencies inconsistency inconvenienced inconveniences inconveniencing inconvenient incorporate incorporated incorporates incorporating incorrectly increasingly incredible incredibly increment incur incurred incurring incurs indefensible indefinite indefinitely indent independence indeterminate indexed indexes indexing indicated indicating indications indicative indicator indicators indictment indirect indirection indirectly indistinguishable induce induced induces inducing induction indulge indulged indulges indulging industries ineffective inefficiency inefficient inequality inertia inevitable inexperienced infallible infamous infant infantile infect infected infecting infection infects infelicity infer inference inferiority infinitely infinity inflation inflexible inflict influenced influences influencing influential informal informally informative infrastructure infrequent infringement ingenious ingredient ingredients inhabit inhabitant inhabitants inhabited inhabiting inhabits inherent inherently inherit inheritance inherited inheriting inherits inhibit inhibited inhibiting inhibition inhibits initiate initiated initiates initiating initiative inject injure injured injures injuries injuring injury injustice ink innocence innovation innovative insane insect insects insecure insensitive insertion insidious insight insignificant insistence insofar inspect inspected inspecting inspection inspects inspiration inspire inspired inspires inspiring installation installations instances instinct institute instruct instructed instructing instructs instrument instrumental instruments insufficient insult insulted insulting insults intact intake integrate integrated integrates integrating integration integrity intellect intellectual intense intensely intensity intensive intent intentional intentionally intentions inter interacted interacting interaction interactions interactive interactively interacts intercourse interestingly interfaced interfaces interfacing interfere interfered interference interferes interfering interim interior intermediate intermittent internally internals interpretations interpreter interrogate interrupt interrupted interrupting interruption interruptions interrupts intersection intersections intervene intervened intervenes intervening interview interviewed interviewing interviews intimate intolerance intrinsic intrinsically introductory intuitive invade invaded invades invading invalidate invaluable invasion invention inventions inventor inverse invert inverted inverting inverts invest investigated investigates investigating investigation investigations investment invoke invoked invokes invoking involvement ion irate iron ironic irony irrational irrespective irresponsible irritation island islands isolation jack jacket jackets jail jam jammed jamming jams jargon jazz jealous jeans jellies jelly jerk jest jet jointly joints joked jokes joking jolly journal journalist journalists journals journey judged judges judging juice jumped jumping junction jungle junior jury justice justifiable justifiably juvenile keeper ken kernel kettle keyboards keyed keying keystroke keystrokes keyword keywords kick kicked kicking kicks kidded kidding kidnap kidnapped kidnapping kidnaps kidney kids killer kindness kingdom kings kiss kit kitchen kits knee knees knife knight lab labs lad ladder lag lager laid lake lamp landlord landscape lane lark laser lasers lasted lasting lately laugh laughed laughing laughs laughter launch launched launches launching lavatory lawn lawyer lawyers layer layers laying lays laziness leaders leadership leaflet leaflets league leak lean leaned leaning leans leap leather lectured lecturer lecturers lecturing legend legendary legible legislation legitimate legitimately leisure lemon lending lends lengths lengthy lenient lens lenses lent lesbian lest lethal liability liaison libel liberal liberties liberty librarian lid lifestyle lifted lifting lifts lighted lighter lightest lighting lightly lightning lightninged lightnings likelihood limb limbs limitation limitations lined linguistic lining linkage lion lip lips liquid liquor lisp listened listener listening listens listings lit literal literary literate litter lively liver livest loader loans lobby locally locals locate located locates locating lodge logically logo lonely loophole loops loosely lord lords lorries losses loud louder loudest lousy loved lovely lover lovers loves loving lowered lowering lowers loyal luckily ludicrous ludicrously luggage lump lumps lunatic lunchtime lung lungs lurk lurked lurking lurks lust luxury lyric lyrics machinery madness magazine magazines magical magnificent mailbox mailed mailing mails mainframe mainframes mains mainstream maintenance maize maker makers male males malfunction malicious management managers mandate mandatory mangle mangled mangles mangling mania manifestation manifestly manifesto manipulate manipulated manipulates manipulating mankind manned manning manpower mans manually manufacture manufactured manufacturer manufacturers manufactures manufacturing mapped mapping maps margin marginal marginally margins marital marker markers marketed marketing markets married marries marrying mask masses massively masters matched matching mate mathematically mathematician mathematicians matrices matrix mature mayor maze meal meals meantime meanwhile measurement measurements meat mechanical mechanisms medicine medieval megabyte megabytes melody melt memorable memories mend mended mending mends mental mentality mentally menu menus mercury mercy merge merged merges merging merry messed messes messing metaphor metric metro metros mice microcomputer microcomputers microprocessor microwave midday mighty migrate migrated migrates migrating migration mild mildly mileage milk mill mimic mindless mined mines minimalist mining minister ministers minorities mint minus miracle miracles miraculous mirror mirrors miscellaneous misdirect misdirected misdirecting misdirects miserable miserably misery misfortune misguide misguided misguides misguiding misinterpret misinterpreted misinterpreting misinterprets misplace misplaced misplaces misplacing misprint misread misreading misreads misrepresent misrepresented misrepresenting misrepresents missile missiles mission mist mistakenly mists mixture mnemonic moan moaned moaning moans mob mobile mock moderate moderately moderation modes modest modification modifications module modules mole molecular molecule molecules momentarily moments momentum monarch monitored monitoring monitors monkey monkeys monochrome monopoly monster monsters monthly mood moon moons morality morally morals moreover moron morons mortal mortality mortals mothers motions motivate motivated motivates motivating motivation motive motives motor motors motorway motorways motto mount mountain mountains mounted mounting mounts mouse movies muck mucked mucking mucks mud muddle muddled muddles muddling mug mugs multiples multiplication multiplied multiplies multiply multiplying mum mumble mummy mundane murder murdered murderer murdering murders muscle muscles museum museums musical musician musicians mutter muttered muttering mutters mutual mutually mysteries mysteriously mystery mystic myth mythical mythology myths nail nailed nailing nails naked nameless narrative narrow narrower narrowest nastier nastiest nationally nations native natives nay neat neatly needle needles needless needlessly negate neglect neglected neglecting neglects negligible negotiable negotiate negotiated negotiates negotiating negotiation negotiations nerve nerves nest nested nesting nests nets networked networking neural neutral newcomer newcomers newer newest newly newsletter newsletters newspaper newspapers nicely nick nicked nicking nickname nicknames nicks nightmare nights nil noble node nodes noises nominal nominally nominate nominated nominates nominating nonetheless noon norm normality northern nose noses nostalgia notable notably notation noticeable noticeably notification notified notifies notifying notion notions notorious notwithstanding noun nouns novels novelty novice novices nuclear nuisance null numbered numbering numeral numerals numeric nun nuns nurse nurses nut nuts oar obeyed obeying obeys objectionable objective obligation obligatory oblige obliged obliges obliging obnoxious obscene obscured obscures obscuring obscurity observations observer observers obsess obsessed obsesses obsessing obsession obsolete obstruct obstructed obstructing obstructs obtainable occupation occurrence occurrences ocean oddly offend offended offender offenders offending offends offerings offhand officers officially officials offset offsets offsetting offspring omission omissions oneself ongoing onion onus onwards openly opera operas operational opponent opponents oppress oppressed oppresses oppressing oppression opt opted optic optical optimal optimistic optimum opting optionally opts opus opuses oral orange orbit orbital orchestra orchestral organ organic organs orient oriental orientate orientated orientates orientating orientation oriented orienting orients originals originate originated originates originating originator origins orthodox outcome outcomes outcry outdated outgoing outline outlined outlines outlining outlook outputs outrage outraged outrageous outrages outraging outright outset outstanding outweigh outweighs overcame overcome overcomes overcoming overdraft overdue overflow overhead overheads overlap overload overloaded overloading overloads overlong overlook overlooked overlooking overlooks overly overnight overprice overpriced overprices overpricing overridden override overrides overriding overrode overseas overtime overtone overtones overview overwhelm overwhelmed overwhelming overwhelms overwriting overwritten owned ownership owning owns oxygen ozone pace pacifier packaged packaging packed packets packing packs pad padded padding pads paged paging painfully painless pains paint painted painting paintings paints palace pale pan panel panels panic pant pants paperback par parade paradise paradox paragraphs parallels parameter parameters paranoia paranoid paraphrase pardon parentheses parenthesis parents parity parked parking parks parliament parochial parody parrot parse parsed parses parsing participant participants participate participated participates participating particle particles partition partitioned partitioning partitions partner partners passage passages passenger passengers passion passionate passive passport password passwords paste pat patched patches patching patent pathetic paths patience patients paused pauses pausing pavement payment payments peaceful peaks peanut peanuts peasant peasants pedal pedant pedantic pedantry pedants pedestrian pedestrians peer peers penalties penalty pence pencil pended pending pends penguin pennies penny pens peoples perceive perceived perceives perceiving percent percentage percents perception perfection performances periodic periodically periods peripheral peripherals permissible perpetual persecute persecuted persecutes persecuting persist persistent personalities personality personnel perspective persuasion perverse pet petty pharmacies pharmacy phased phases phasing phenomena phenomenons philosopher philosophers philosophical philosophies phoenix phoned phones phoning photo photocopy photograph photographic photographs photos phrased phrasing physic physically physicist physicists physics physiology piano pie pig pigeon pigs piles pill pills pilot pin pinch pinched pinches pinching pink pins pints pipeline pipes pit pitch pitfall pitfalls pity pizza pizzas plague plagued plagues plaguing plainly planes planetary planets planted planting plants plaster plastered plastering plasters plate plates platform plausible player players playground pleasantly pleasure plotted plotter plotting ploy plugged plugging plugs plural pockets poems poetic poetry poets pointer pointers poison poisoned poisoning poisons poke polar pole policeman polish polished polishes polishing polite politeness politically politician politicians politics polls pollution polynomial pompous poorer poorest poorly pope popped popping pops populace popularity populate populated populates populating populations pork pornography portability portable ported porter porters porting portion portions portray portrayed portraying portrays ports pose posed poses posing positioned positioning positively possess possessed possesses possessing possession postage postal postcard poster posters postpone postponed postpones postponing postscript postulate pot potato potatoes pour poured pouring pours poverty powder powered powering practicable practicals pragmatic praise pray prayed prayer prayers praying prays preach preached preaches preaching precaution precautions precede preceded precedence precedent precedes preceding precious precision predecessor predecessors predict predictable predicted predicting prediction predictions predicts predominantly preface preferences prefix prefixed prefixes prefixing pregnancy pregnant prejudice prejudiced prejudices prejudicing preliminary premature prematurely premise premises premium prerequisite prescribe prescribed prescribes prescribing prescription presentation presently preserved preserves preserving pressures presumed presumes presuming pretend pretended pretending pretends pretentious prevail prevalent prevention preview previewer priced pricing pride priest priests primarily primes primitives prince principal principally printouts priorities priority prison prisoner prisoners privacy privately privilege privileged privileges privileging pro probabilities probability probable procedures proceed proceeded proceeding proceedings proceeds proclaim producer producers productive productivity profession professionals professor profile profiles profit profitable profits profound programmable progressed progresses progressing prohibit prohibited prohibiting prohibits projected projecting projection proliferation prolong prolonged prolonging prolongs prominent promote promoted promotes promoting promotion prompted prompting prompts pronoun pronounce pronounced pronounces pronouncing pronunciation proofs propaganda prophet proportional proportions proposals proposition proprietary prose prosecute prosecuted prosecutes prosecuting prosecution prospective prospects prostitute prostitutes protein protocol protocols prototype proud provision provisional provisions provocative provoke provoked provokes provoking proximity pseudo psychological psychologist psychologists psychology pub publications publisher publishers pudding pulp pulse pulses pump pumped pumping pumps pun punch punched punches punching punish punished punishes punishing punishment puns punt punts pupil pupils purchased purchases purchasing purge purity purple pursue pursued pursues pursuing pursuit puzzle puzzled puzzles puzzling python qualification qualifications qualifier qualifiers qualities quantum quarters queen queens queries query quest questionable questioned questioning questionnaire queued queues quibble quieter quietest quiz quota quotas quotation quotations rabbit rabbits rabid raced races racial racing racism racist rack racket racks radar radiation radical radically radios radius rag rage raid raids rail railroad rails railway rainbow rained raining rains ram rampant rang ranged ranges ranging rank ranks rant ranted ranting rants rape rarer rarest rash rat rated rating ratio rational rationale rationally ratios rats rattle rattled rattles rattling rave raved raves raving ray razor reacted reacting reactionary reactions reactor reacts readership readings realistic realm realms rear rearrange rearranged rearranges rearranging reasoned reasoning reassure reassured reassures reassuring rebuild rebuilding rebuilds rebuilt recalled recalling recalls receipt receiver recipe recipes recipient recipients reckless reckon reckoned reckoning reckons reclaim recollection recommendations reconcile reconsider recorder recordings recovery recreational recruit recruited recruiting recruitment recruits rectangle rectangular rectified rectifies rectify rectifying recursion recursive recycle recycled recycles recycling redefine redefined redefines redefining redirect reductions redundancy referenced referencing referendum refine refined refines refining reflex reform reformat reformed reforming reforms refrain refresh refreshed refreshes refreshing refund refusal refute regain regime regional regions registration regrets regrettably regretted regretting reign reinstate reinstated reinstates reinstating reiterate rejection relations relationships relatives relativity relax relaxed relaxes relaxing relay reliability reliably relied relief relies relieve relieved relieves relieving religions relocation reluctance reluctantly relying remainder remarkable remarkably remarked remarking remedy reminder reminiscent rename renamed renames renaming rend render rendered rendering renders rending rendition rends renew renewed renewing renews rent repaired repairing repairs repeatable repent repertoire repetition repetitive rephrase replacements reporter representations representatives reproduced reproduces reproducing reproduction repulsive reputation requisite reread rereading rereads rescue researcher researchers resemblance resemble resembled resembles resembling resent reservation reservations reset resets resetting reside residence residents resides resign resignation resigned resigning resigns resist resistance resolve resolved resolves resolving resorted resorting resorts respectable respected respecting respective responded responding responds responsibilities restarted restarting restarts restaurant restaurants rested resting restrain restrained restraining restrains restriction restrictions restrictive rests resume resumed resumes resuming resurrection retail retained retaining retains retire retired retirement retires retiring retract retrieval retrieve retrieved retrieves retrieving reuse revelation revenge revenue reversed reverses reversing revert reviewed reviewing reviews revise revised revises revising revision revolt revolted revolting revolts revolution revolutionary reward rewards rewrites rewriting rewritten rewrote rhetorical rhyme rhythm ribbon rice rich richer richest ridden rides ridiculously riding rightly rigid rigorous ringed ringing rings riot rip ripped ripping rips risen rises rising risked risking risks risky ritual rituals rival rivals rivers roads robot robots robust rock rocket rocks rod rode roles rolled rolling rolls roman romance romantic roof roots rope rose rot rotate rotated rotates rotating rotation rotten roundabout rounded rounding rounds rout routed routes routinely routines routing routs rows royal royalties rub rude ruin ruined ruining ruins ruled ruler rulers ruling rung rural rushed rushes rushing rusty sabotage sack sacked sacking sacks sacred sacrifice sacrificed sacrifices sacrificing sadden saddened saddening saddens safeguard safeguards saga sail sailed sailing sails salaries salary salesman salt salvation sampled samples sampling sand sandwich sandwiches sane sang sanity sank sarcasm sarcastic satellite satellites satire satisfaction satisfactorily satisfactory sauce savings scaled scales scaling scandal scanned scanner scanning scans scarce scarcely scare scared scares scarf scaring scarlet scatter scattered scattering scatters scenario scenarios scenery scenes schedule scheduled scheduler schedules scheduling schemes scholar scholars scientifically scientist scientists scope scored scoring scotch scrapped scrapping scraps scratched scratches scratching scream screamed screaming screams screw screwed screwing screws scripts scroll scrolled scrolling scrolls scum sea seal sealed sealing seals seat seats seconded seconding secretaries secretly secrets sect sector sects secular seed seemingly segment segments seldom selective selectively selfish semantic semantics seminars sender sensation senses sensitivity sentenced sentencing sentient sentiment sentimental sentiments separated separates separating separation separator separators sequel sequential seriousness sermon servant servants servers settings seventh severity sexes sexist sexual sexuality sexually sexy shade shades shadow shake shaken shakes shaking shaky shallow shaped shapes shaping shareholder shareholders sharply shed shedding sheds sheep sheer sheets shells shelter shelve shelves shifted shifting shifts shine shined shines shining shiny shipped shipping ships shirt shock shocked shocking shocks shoe shoes shone shook shooting shoots shorten shortened shortening shortens shorthand shorts shot shots shoulder shoulders shout shouted shouting shouts shove shower showers shutdown shy sic sick sicken sickened sickening sickens sided sideways siding sigh sighted sighting sights sigma signature signatures silence silent silicon sillier silliest silver similarities similarity simplicity simplified simplifies simplify simplifying simplistic simulate simulated simulates simulating simulation sin sincere sine sinful sing singer singers singing singles sings singular singularly sinister sink sinking sinks sins sir sister situate situated situates situating sixteen sixth sixties sixty sized sizing skeleton sketch sketches skilled skin skip skipped skipping skips skirt skull sky slag slang slash slave slaves sleeping sleeps slept slice sliced slices slicing slid slide slides sliding slighter slightest slim slipped slippery slipping slips slogan slope sloppy slot slots slowed slowing slows smallish smart smash smashed smashes smashing smell smells smelly smiled smiles smiling smith smoke smoked smoker smokers smokes smoking smoothly smug snack snag snail sneak sneaked sneaking sneaks sneaky sniff snobbery snow soap sober socialism socialist socially societies sock socket sockets socks sod soil solar soldier soldiers sole soles solicitor solicitors solo song songs sons sordid sore soul souls soundtrack soup spaced spacing span spares spatial specialist species specification specifications specimen spectacular spectrum speculate speculation sped speeches speeding speeds spellings sphere spies spigot spike spill spin spiral spirits spiritual spit spits spitted spitting splendid spoil spoiling spoils spokesman sponsor sponsored sponsoring sponsors spontaneous spontaneously spoof spool sport sports spout sprang spray springing springs sprung spur spurious spy squad squared squares squaring squash squashed squashes squashing squeeze squeezed squeezes squeezing stability stack stacks stagger staggered staggering staggers stair staircase stairs stake stale stall stamp stamped stamping stamps stance standpoint star stare stared stares staring stark starred starring stars starter starters startle startled startles startling starve starved starves starving static stationary steadily steady stealing steals steam steel steep steer steered steering steers stem stems stepped stepping steps stereo stereotype stereotypes sterile sterling sticky stiff stimulate stimulated stimulates stimulating stimulation stir stirred stirring stirs stocks stole stolen stomach storm storms strain strains strangely stranger strangest strategic strategies straw stray streams streets strengthen stress stressed stresses stressing stretch stretched stretches stretching stringent strip stripped stripping strips strive stroke stronger strongest structural structured structuring struggle struggled struggles struggling studio stuffed stuffing stuffs stumble stumbled stumbles stumbling stun stunned stunning stuns stunt stupidity styles subjected subjecting subjective submission subroutine subroutines subscribe subscription subsequently subsidiary substance substances substantially substituted substitutes substituting substitution subtleties subtlety subtly subway subways succeeded succeeding succeeds succession successive successor sue sued sues sufferer sufferers suffix suicidal suicide suing suitability suite summaries summed summing sums sundry sung sunk sunlight sunny sunrise sunshine super superb superficial superficially superfluous superiority supermarket supernatural supervise supervised supervises supervising supervision supervisions supervisors supplement supplementary supplier suppliers supporter supporters suppress suppressed suppresses suppressing suppression supreme surfaces surgery surname surplus surprisingly surround surrounded surrounding surroundings surrounds surveys survival susceptible suspension suspicious suspiciously sustain sustained sustaining sustains swallow swallowed swallowing swallows swam swamp swamped swamping swamps swap swapped swapping swaps swear swearing swears sweat sweating sweats sweep sweeping sweeps sweet swept swim swimming swims swing sword swore sworn swum symbolic symmetric symmetry sympathetic sympathies sympathy symphonies symphony symptom symptoms syndicate syndrome synonym synonymous synonyms syntactic syntactically synthesis systematic tab tabs tack tacked tacking tackle tackled tackles tackling tacks tactic tactical tactics tactless tag tail tailor tailored tailoring tailors tails taker takers tale talent talented talents tales tall tame tangent tap targets tasted tasteless tastes tasting taxation taxes taxi taxpayer taxpayers teachers teams teapot tear teared tearing tears technically technological teenage teenager teenagers telephones telescope temper temperatures temple tempt temptation tempted tempting tempts tended tendencies tender tending tennis tens tense tension tentative tentatively tenth termed terminally terminate terminated terminates terminating termination terminator terming terrible terrified terrifies terrify terrifying territory terror terrorism terrorist terrorists terse textbook textbooks texts textual thanked thankful thankfully thanking thee theft theirs theme themes theological theology theorem theorems theoretically theories therapy thereabouts thereafter therein thereof theses thesis thick thickness thief thieve thieves thirst thirty thorough thoroughfare thoroughfares thou thous thread threaten threatened threatening threatens threats threshold throat throats throughput thrust thrusting thrusts thumb thy tick tidied tidies tidy tidying tiger tightly tile tiles timer timescale timetable tins tiny tip tips tiresome toad toast tobacco toe toes toggle toilet toilets tokens tolerance tolerant tolerate tolerated tolerates tolerating toll tomato tomatoes tome ton tone tones tongue tons tool tools topical tops tore torn torture toss tough tour tourist tourists tower towers towns toy toys traced traces tracing tracked tracking trade traded trades trading tradition traditionally traditions tragedy tragic trail trailed trailing trails transaction transactions transcript transform transformation transformed transforming transforms transient transit transition translations translator transmission transmissions transmit transmits transmitted transmitter transmitters transmitting transparent transported transporting transports trashcan travels tray tread treasure treaty trek tremendous tremendously trend trends trendy trials triangle triangles tribe tribes tricks tricky trifle trigger triggered triggering triggers trilogy trinity triple tripos trips triumph trivia trivially trolley troop troops troubles trouser trousers trucks trumpet truncate truncated truncates truncating trunks trusty truths tube tubes tuned tunes tuning tunnel tunnels turnround turntable tutor tutorial twentieth twin twins twist twisted twisting twists typeset typesets typesetting typewriter typically ugh umbrella unaffected unambiguous unattended unavailable unavoidable unbalanced unbearable unbelievable unbelievably unbiased uncertainty unchanged uncle uncomfortable uncommon unconnected unconscious unconvincing undefined underestimate undergo undergoes undergoing undergone underground undergrounds underlain underlay underlie underlies underline underlined underlines underlining underlying understandable undertake undertaken undertakes undertaking undertook underwent undesirable undid undo undocumented undoes undoing undone undoubtedly unduly uneasy unemployed unemployment unexpected unexpectedly unexplained unfair unfamiliar unfinished unfounded unfriendly unhealthy unhelpful unified unifies uniformly unify unifying unimportant uninteresting union unions uniquely united unites uniting unity universally universe unjustified unload unlock unlocked unlocking unlocks unlucky unnatural unobtainable unofficial unpopular unpredictable unread unreadable unrealistic unrelated unreliable unsafe unsatisfactory unseen unset unsolicited unsound unspecified unstable unsuccessful unsupported unsure unsuspecting untidy unto untrue unusable unused unusually unwelcome unwilling unwise unworkable upbringing upgrade upgraded upgrades upgrading upright ups upside upstairs upward urban urge urged urgency urgent urgently urges urging usable usefully usefulness utilities utter vacancies vacancy vacuum vain valley valued valuing valve valves vandalism vanish vanished vanishes vanishing vans variance variant variants variations varieties vat vectors vegetable vegetables vegetarian vehicle vehicles vein velocity vend vended vending vendor vends venture venue venues verb verbal verbally verbatim verbose verbs verdict verification verified verifies verify verifying versatile verse verses versus vertical vertically vessel vet viable vicar vicinity vicious victim victims victory viewed viewer viewing viewpoint viewpoints vigorously vile village villages vintage vinyl violate violation violence violent violently violin virgin virtual virtues virus viruses visited visiting visitor visitors visits visual visually vocabulary vocal voices void voltage volumes voluntarily voluntary volunteer volunteered volunteering volunteers vomit voted voter voters voting vouch vowel vulnerable wade waded wades wading waffle wage wages wake waked wakes waking wallet wander wandered wandering wanders ward warehouse warmed warming warms warnings warp warped warping warps warrant warranty wars wartime wary washed washes washing wasteful waters wave waved waves waving weak weakness weaknesses wealth wealthy weapons weary weasel weasels wed wedded wedding weds wee weekday weekends weekly weigh welfare wet wets wetting whale whales whence whereupon whichever whim whistle whistles whites wholeheartedly wholly whoop whoops wicked width wildly willingly winded winding windowing winds wines wing wings winner winners wipe wiped wipes wiping wired wires wiring wisdom wiser wisest wit witch withdrawal withdrawing withdrawn withdraws withdrew witness witnessed witnesses witnessing witty wive wives wizard woke woken wolf wombat wonderfully wondrous wont wood woods workable workings workload workshop workstation workstations worlds worldwide worm worms worship worthless wound wow wrap wrapped wrapper wrappers wrapping wraps wrath wreck wrecked wrecker wrecking wrecks wren wretched wrist writers writings wrongly wrongs yard yards yawn yearly yeti yield yields younger youngest yourselves youth zeros zone zones zoom """.split()) SCOWL35 = set(""" aback abacus abacuses abandonment abate abated abates abating abbey abbeys abbot abbots abdicate abdicated abdicates abdicating abdication abdications abdomen abdomens abdominal abduct abducted abducting abducts aberration aberrations abet abets abetted abetting abhor abhorred abhorrence abhorrent abhorring abhors abides abiding abject abjected abjecting abjects ablaze abler ables ablest ably abnormalities abnormality aboard abode aboded abodes aboding abominable abomination aboriginal aborigine aborigines abortions abortive abound abounded abounding abounds abouts aboveboard abrasive abrasives abreast abridge abridged abridges abridging abrupt abrupter abruptest abruptly abscess abscessed abscesses abscessing abscond absconded absconding absconds absences absented absentee absentees absenting absents absoluter absolutes absolutest absolve absolved absolves absolving absorbent absorbents absorption abstain abstained abstaining abstains abstention abstentions abstinence abstracted abstracter abstractest abstracting abstractions abstracts abstruse absurder absurdest absurdities absurdity absurdly abundance abundances abundant abundantly abuser abusers abyss abysses academically academies academy accede acceded accedes acceding accelerated accelerates accelerating acceleration accelerations accelerator accelerators accented accenting accentuate accentuated accentuates accentuating acceptability acceptably acceptances accessibility accessories accessory accidentals acclaim acclaimed acclaiming acclaims acclimate acclimated acclimates acclimating acclimatize acclimatized acclimatizes acclimatizing accolade accoladed accolades accolading accommodated accommodates accommodating accommodations accompaniment accompaniments accompanist accompanists accomplice accomplices accomplishment accomplishments accordion accordions accost accosted accosting accosts accountability accountable accountancy accredit accredited accrediting accredits accrue accrued accrues accruing accumulation accumulations accuser accusers aced aces ache ached aches achievable aching acidity acids acing acne acorns acoustics acquaint acquaintances acquainted acquainting acquaints acquiesce acquiesced acquiescence acquiesces acquiescing acquisitions acquit acquits acquittal acquittals acquitted acquitting acre acreage acreages acres acrid acrider acridest acrimonious acrimony acrobat acrobatic acrobatics acrobats acrylic acrylics actioned actioning actives activist activists actress actresses actualities actuality actuary acumen acupuncture acutely acuter acutes acutest ad adage adages adamant adaptable adaptations adaptive addendum addiction addictions additive additives addressee addressees adept adepter adeptest adepts adherence adherent adherents adhesion adhesive adhesives adjectives adjoin adjoined adjoining adjoins adjourn adjourned adjourning adjournment adjournments adjourns adjunct adjuncts adjustable administrations administrator administrators admirably admiral admirals admired admirer admirers admires admiring admissible admissions admittance admonish admonished admonishes admonishing admonition admonitions ado adobe adobes adolescence adolescences adolescent adolescents adoptions adorable adoration adore adored adores adoring adorn adorned adorning adornment adornments adorns adrift adroit adroiter adroitest adroitly ads adulation adulterate adulterated adulterates adulterating adulteration adulteries adultery adulthood advancement advancements advantaged advantaging adventured adventurer adventurers adventuring adverb adverbial adverbials adverbs adversaries adversary adverser adversest adversities adversity advertiser advertisers advisories aerials aerodynamic aerodynamics aerosol aerosols aerospace afar affable affabler affablest affably affectation affectations affectionate affectionately affectioned affectioning affections affidavit affidavits affiliate affiliated affiliates affiliating affiliation affiliations affinities affinity affirm affirmation affirmations affirmative affirmatives affirmed affirming affirms affix affixed affixes affixing afflict afflicted afflicting affliction afflictions afflicts affluence affluent affordable afforded affording affords affront affronted affronting affronts afield aflame afloat afoot aforesaid afresh aftereffect aftereffects afterlife afterlives aftermath aftermaths afters afterthought afterthoughts agencies agendas aggravate aggravated aggravates aggravating aggravation aggravations aggregate aggregated aggregates aggregating aggression aggressively aggressiveness aggressor aggressors aghast agile agiler agilest agility agitate agitated agitates agitating agitation agitations agitator agitators aglow agnostic agnosticism agnostics agonies agreeable agreeably agriculture aground ah ahoy ahoys aide aides ail ailed ailing ailment ailments ails aimless aimlessly airborne aired airfield airfields airier airiest airing airline airliner airliners airlines airmail airmailed airmailing airmails airports airs airstrip airstrips airtight airy aisle aisled aisles aisling ajar alarmingly alarmist alarmists alases albino albinos alcoholics alcoholism alcohols alcove alcoves ale alerted alerter alertest alerting alerts ales alga algae aliased aliasing alibi alibied alibiing alibis alienate alienated alienates alienating alienation aliened aliening alight alighted alighting alights alignments alimony alkali alkalies alkaline allay allayed allaying allays allegiance allegiances allegorical allegories allegory allergies allergy alleviated alleviates alleviating alley alleys alliances allied alligator alligators allot allotment allotments allots allotted allotting alloy alloyed alloying alloys allude alluded alludes alluding allure allured allures alluring allusion allusions allying almanac almanacs almighty almond almonds alms aloft aloof alphabeted alphabetically alphabeting alphabets alphanumeric altar altars alterable alternated alternately alternates alternating alternation alternator altitude altitudes alto altos altruism altruistic amalgamate amalgamated amalgamates amalgamating amalgamation amalgamations amass amassed amasses amassing amateurish amateurs amazement ambassadors ambidextrous ambiguously ambition ambitions ambitiously ambivalence ambivalent amble ambled ambles ambling ambulance ambulances ambush ambushed ambushes ambushing amen amenable amendments amened amening amenities amenity amens amethyst amethysts amiable amiably amicable amicably amid amids amidst amiss ammonia ammunition amnesia amnestied amnesties amnesty amnestying amoeba amoebas amok amoral amorous amorphous amounted amounting ampere amperes ampersand ampersands amphetamine amphetamines amphibian amphibians amphibious ampler amplest amplification amplifications amplified amplifiers amplifies amplify amplifying amplitude amply amps amputate amputated amputates amputating amputation amputations amulet amulets amusements amusingly anachronism anachronisms anal analgesic analgesics analogies analysts analytic analytical analytics anarchic anarchism anarchist anarchists anathema anatomical anatomies ancestored ancestoring ancestral ancestries ancestry anchor anchorage anchorages anchored anchoring anchors anchovies anchovy ancienter ancientest ancients android androids ands anew angelic angered angering angers angled angler anglers angling angrier angriest angrily angst anguished anguishes anguishing angular animate animated animates animating animation animations animosities animosity ankle ankled ankles ankling annals annex annexation annexations annexe annexed annexes annexing annihilate annihilated annihilates annihilating annihilation anniversaries annotate annotated annotates annotating annotation annotations announcer announcers annoyances annoyingly annuals annuities annuity annul annulled annulling annulment annulments annuls anoint anointed anointing anoints anomalous anon anonymity anonymously answerable ant antagonism antagonisms antagonist antagonistic antagonists ante anteater anteaters anted anteing antelope antelopes antenna antennae antennas antes anthem anthems anthill anthills anthologies anthrax anthropological anthropologist anthropologists anthropology antibiotic antibiotics antibodies antibody antic anticipations anticlimax anticlimaxes antics antidotes antifreeze anting antipathies antipathy antiquate antiquated antiquates antiquating antiqued antiques antiquing antiquities antiquity antiseptic antiseptics antitheses antithesis antler antlers antonym antonyms ants anus anuses anvil anvils anxieties anxiety anxiously anybodies anythings anyways anywheres aorta aortas apartheid apartment apartments ape aped aperture apertures apes apex apexes aphorism aphorisms apiece aping aplomb apocryphal apologetic apologetically apologetics apostle apostles apostrophes apparel apparels apparition apparitions appease appeased appeasement appeasements appeases appeasing appendage appendages appendices appendicitis appendixes appetite appetites applaud applauded applauding applauds apples appliance appliances applicability applicator applicators appointee appointees apposite appraisals appraise appraised appraises appraising appreciable appreciations appreciative apprehend apprehended apprehending apprehends apprehension apprehensions apprehensive apprentice apprenticed apprentices apprenticeship apprenticeships apprenticing approachable appropriated appropriates appropriating appropriation appropriations approvals approximated approximates approximating approximations apricot apricots apron aprons apter aptest aptitude aptitudes aptly aquamarine aquamarines aquarium aquariums aquatic aquatics aqueduct aqueducts arable arbiter arbiters arbitrate arbitrated arbitrates arbitrating arbitration arbitrator arbitrators arcades arced archaeological archaeologist archaeologists archbishop archbishops arched archer archers archery arches archest archetypal arching archipelago archipelagos architect architects architectural architectures archway archways arcing arcs ardent ardently arduous arduously arenas ares argumentative aria arias arid arider aridest aristocracies aristocracy aristocrat aristocratic aristocrats ark arks armadillo armadillos armament armaments armchair armchairs armies armistice armistices armpit armpits aroma aromas aromatic aromatics arouse aroused arouses arousing arraign arraigned arraigning arraigns arrayed arraying arrears arrivals arrogantly arsenal arsenals arsenic arson arterial arteries artery artful arthritic arthritics arthritis artichoke artichokes articulate articulated articulately articulates articulating articulation articulations artifact artifacts artifice artifices artillery artisan artisans artistically artistry artwork asbestos ascension ascensions ascent ascents ascertain ascertained ascertaining ascertains ascetic ascetics ascribe ascribed ascribes ascribing asexual ashed ashen ashing ashore ashtray ashtrays asides askance askew asparagus aspen aspens aspersion aspersions asphalt asphalted asphalting asphalts asphyxiate asphyxiated asphyxiates asphyxiating asphyxiation asphyxiations aspirant aspirants aspiration aspirations aspire aspired aspires aspirin aspiring aspirins assail assailant assailants assailed assailing assails assassin assassinate assassinated assassinates assassinating assassination assassinations assassins assaulted assaulter assaulting assaults assemblers assemblies assent assented assenting assents assertions assertive assessments assessor assessors assimilate assimilated assimilates assimilating assimilation assistants associative assortment assortments assurance assurances assureds asterisked asterisking asteroid asteroids asthma astonish astonished astonishes astonishing astonishingly astonishment astound astounded astounding astounds astray astride astringent astringents astrological astrology astronaut astronauts astronomical astute astutely astuter astutest asylum asylums asymmetry asynchronously ates atheistic athlete athletes athletic athletics atlantes atlases atmospheres atmospherics atomics atone atoned atonement atones atoning atrocious atrociously attache attachments attacker attained attaining attainment attainments attains attendances attendants attentive attentively attest attested attesting attests attic attics attire attired attires attiring attractions attractiveness attributable attribution attune attuned attunes attuning auburn auction auctioned auctioneer auctioneers auctioning auctions audacious audacity audibles audibly audios audit audited auditing audition auditioned auditioning auditions auditor auditorium auditoriums auditors auditory audits augment augmented augmenting augments august auguster augustest augusts aunts aura aural auras auspicious austere austerer austerest austerities austerity authentically authenticate authenticated authenticates authenticating authenticity authored authoring authoritarian authoritative authoritatively authorship auto autobiographical autobiographies autocracies autocracy autocrat autocratic autocrats autoed autograph autographed autographing autographs autoing automatics automation automobiled automobiling automotive autonomous autonomy autopsied autopsies autopsy autopsying autos autumnal autumns auxiliaries auxiliary avail availed availing avails avalanche avalanches avarice avaricious avenge avenged avenges avenging avenue avenues averaged averages averaging averse aversion aversions avert averted averting averts aviation aviator aviators avid avider avidest avocado avocados avoidable avoidance avow avowal avowals avowed avowing avows awaken awakened awakening awakens awakes awaking awarer awarest aways awe awed awes awesome awfuller awfullest awhile awing awkwarder awkwardest awkwardly awkwardness awning awnings awoke awoken awry axed axing axiomatic axiomatics axises axle axles aye ayes azalea azaleas azure azures babble babbled babbles babbling babe babes babied babier babiest baboon baboons babying babyish bachelor bachelors backbones backer backers backfire backfired backfires backfiring backgammon backhand backhanded backhanding backhands backings backlash backlashes backlogged backlogging backlogs backpack backpacked backpacking backpacks backside backslash backstage backtrack backtracked backtracking backtracks backwoods bacon bacterial bacterias badder baddest bade badger badgered badgering badgers badges badminton badness bagel bagels bagged baggie baggier baggies baggiest bagging baggy bail bailed bailing bails bait baited baiting baits baker bakeries bakers bakery balconies balcony bald balded balder baldest balding baldness balds bale baled bales baling balk balked balking balks ballad ballads ballast ballasted ballasting ballasts balled ballerina ballerinas ballets balling ballistics balloon ballooned ballooning balloons balloted balloting ballots ballroom ballrooms balm balmier balmiest balms balmy baloney bamboo bamboos bamboozle bamboozled bamboozles bamboozling banaler banalest bandage bandaged bandages bandaging bandanna bandannas banded bandied bandier bandies bandiest banding bandit bandits bandstand bandstands bandwagons bandy bandying banged banging bangs bani banish banished banishes banishing banister banisters banjo banjos banked banker bankers banking banknote banknotes bankruptcies bankruptcy bankrupted bankrupting bankrupts bannered bannering banners banquet banqueted banqueting banquets banter bantered bantering banters baptism baptisms barb barbarian barbarians barbaric barbarous barbecue barbecued barbecues barbecuing barbed barber barbered barbering barbers barbing barbiturate barbiturates barbs bard bards bareback bared barefoot barer bares barest bargained bargainer bargaining bargains barge barged barges barging baring baritone baritones barley barman barn barnacle barnacles barns barnyard barnyards barometer barometers baron barons barrage barraged barrages barraging barrels barren barrener barrenest barrens barrette barrettes barricade barricaded barricades barricading barrings bartender bartenders barter bartered bartering barters baseball baseballs baseline basements baser basest bashful basil basin basins bask basked basketball basketballs baskets basking basks bassoon bassoons baste basted bastes basting batched batches batching bathe bathed bathes bathing bathrooms bathtub bathtubs baton batons bats batsman battalion battalions batted batter battered battering batters batting battled battlefield battlefields battles battleship battleships battling bawdier bawdiest bawdy bawl bawled bawling bawls bayed baying bayonet bayoneted bayoneting bayonets bayou bayous bays bazaar bazaars beached beaches beaching beacon beacons bead beaded beadier beadiest beading beads beady beagle beagled beagles beagling beak beaked beaker beakers beaks beamed beaming beams beaned beaning bearable bearer bearers bearings beater beaters beautician beauticians beauties beautified beautifies beautifuler beautifulest beautify beautifying beaver beavered beavering beavers beckon beckoned beckoning beckons becomings bedbug bedbugs bedclothes bedded bedder bedding bedlam bedlams bedridden bedrock bedrocks bedrooms bedside bedsides bedspread bedspreads bedtime bedtimes bee beech beeches beefed beefier beefiest beefing beefs beefy beehive beehives beeper bees beeswax beet beetle beetled beetles beetling beets beeves befall befallen befalling befalls befell befit befits befitted befitting befriend befriended befriending befriends beggar beggared beggaring beggars begged begging beginnings begrudge begrudged begrudges begrudging begs beguile beguiled beguiles beguiling behalves behead beheaded beheading beheads beheld behinds behold beholder beholding beholds beige belated belatedly belch belched belches belching belfries belfry belie belied belies belittle belittled belittles belittling bellboy bellboys belled bellhop bellhops bellied bellies belligerent belligerents belling bellow bellowed bellowing bellows belly bellying belongings beloveds belows belted belting belts belying bemoan bemoaned bemoaning bemoans bemuse bemused bemuses bemusing benched benches benching bender benediction benedictions benefactor benefactors beneficiaries beneficiary benefited benefiting benevolence benevolences benevolent benighted benign bents bequeath bequeathed bequeathing bequeaths bequest bequests bereave bereaved bereavement bereavements bereaves bereaving bereft beret berets berried berries berry berrying berserk berth berthed berthing berths beseech beseeches beseeching beset besets besetting besiege besieged besieges besieging besought bested bestial bestiality besting bestow bestowed bestowing bestows bests betcha betray betrayal betrayals betrayed betraying betrays betrothal betrothals bettered bettering betterment betters bettor bettors beverage beverages bewared bewares bewaring bewilder bewildered bewildering bewilderment bewilders bewitch bewitched bewitches bewitching beyonds bib bibliographic bibliographies bibliography bibs bicentennial bicentennials bicker bickered bickering bickers bicycled bicycling bidden bide bides biding biennial biennials bifocals bigamist bigamists bigamous bigamy bigots bike biked bikes biking bikini bikinis bilateral bile bilingual bilinguals billboard billboards billed billfolds billiards billing billow billowed billowing billows binaries binder binders bindings bingo binned binning binomial bins biochemical biodegradable biographer biographers biographical biographies biologically bipartisan biped bipeds biplane biplanes birch birched birches birching birdcage birdcages birded birding birthdays birthed birthing birthmark birthmarks birthplace birthplaces births bisect bisected bisecting bisects bisexual bisexuals bishops bison bitch bitched bitches bitching bitings bitterer bitterest bitterly bitterness bittersweet bittersweets bizarres blab blabbed blabbing blabs blackberries blackberry blackberrying blackbird blackbirds blackboards blacked blacken blackened blackening blackens blacker blackest blackhead blackheads blacking blackjack blackjacked blackjacking blackjacks blacklist blacklisted blacklisting blacklists blackmailed blackmailer blackmailers blackmailing blackmails blackout blackouts blacksmith blacksmiths blacktop blacktopped blacktopping blacktops bladder bladders bladed blading blameless blamer blanch blanched blanches blanching blancmange bland blander blandest blanked blanker blankest blanketed blanketing blankets blanking blankly blare blared blares blaring blase blaspheme blasphemed blasphemes blasphemies blaspheming blasphemous blasphemy blaster blaze blazed blazer blazers blazes blazing bleach bleached bleaches bleaching bleak bleaker bleakest blearier bleariest bleary bleat bleated bleating bleats bled bleed bleeding bleeds blemish blemished blemishes blemishing blend blended blending blends blesseder blessedest blessings blight blighted blighting blights blimp blimps blinded blinder blindest blindfold blindfolded blindfolding blindfolds blinding blindingly blindness blinds blinked blinker blinkered blinkering blinkers blinking blinks blip blips blissed blisses blissful blissfully blissing blister blistered blistering blisters blithe blithely blither blithest blitz blitzed blitzes blitzing blizzard blizzards blobbed blobbing blobs bloc blockade blockaded blockades blockading blockage blockbuster blockbusters blockhead blockheads blocs blond blonder blondest blonds blooded bloodhound bloodhounds bloodied bloodier bloodies bloodiest blooding bloods bloodshed bloodshot bloodstream bloodthirstier bloodthirstiest bloodthirsty bloodying bloom bloomed blooming blooms blossom blossomed blossoming blossoms blot blotch blotched blotches blotching blots blotted blotter blotters blotting blouse bloused blouses blousing blowout blowouts blowtorch blowtorches blubber blubbered blubbering blubbers bludgeon bludgeoned bludgeoning bludgeons bluebell bluebells blueberries blueberry bluebird bluebirds blued bluegrass blueprint blueprinted blueprinting blueprints bluer bluest bluff bluffed bluffer bluffest bluffing bluffs bluing blunder blundered blundering blunders blunt blunted blunter bluntest blunting bluntly bluntness blunts blur blurred blurring blurs blurt blurted blurting blurts blush blushed blushes blushing bluster blustered blustering blusters boa boar boarded boarder boarders boarding boardwalk boardwalks boars boas boast boasted boastful boastfully boasting boasts boated boating bobbed bobbin bobbing bobbins bobcat bobcats bobsled bobsledded bobsledding bobsleds bode boded bodes bodice bodices bodily boding bodyguard bodyguards bodywork boggled boggling boiler boilers boisterous bolder boldest boldly boldness bolds bologna bolster bolstered bolstering bolsters bolted bolting bolts bombard bombarded bombarding bombardment bombardments bombards bomber bombers bombings bondage bonded bonding bonds boned bonfire bonfires bonier boniest boning bonnet bonnets bonuses bony boo booby booed booing bookcase bookcases bookend bookended bookending bookends bookings bookkeeper bookkeepers bookkeeping booklets bookmark bookmarked bookmarking bookmarks bookshelf bookworm bookworms boomed boomerang boomeranged boomeranging boomerangs booming booms boon boons boor boorish boors boos boosted booster boosters boosting boosts booted bootee bootees booth booths booties booting bootleg bootlegged bootlegging bootlegs bootstrap booty booze bop bordered bordering borderlines borders boringly borough boroughs bosom bosoms bossed bosser bosses bossier bossiest bossing bossy botanical botanist botanists botany botch botched botches botching bothersome bottled bottleneck bottlenecks bottling bottomed bottoming bottomless bottoms bough boughs boulder bouldered bouldering boulders boulevard boulevards bounced bounces bouncing bounded bounding boundless bounties bountiful bounty bouquet bouquets bourbon bourgeois bourgeoisie boutique boutiques bouts bovine bovines bowed bowel bowels bowing bowled bowlegged bowler bowling bowls bows boxcar boxcars boxed boxer boxers boxing boycott boycotted boycotting boycotts boyfriend boyfriends boyhood boyhoods boyish bra brace braced bracelet bracelets braces bracing brackish brag braggart braggarts bragged bragging brags braid braided braiding braids brained brainier brainiest braining brainless brainstorm brainstormed brainstorming brainstorms brainwash brainwashed brainwashes brainwashing brainy braise braised braises braising braked braking bran branched branching brandied brandies brandish brandished brandishes brandishing brandy brandying bras brash brasher brashest brassed brasses brassier brassiere brassieres brassiest brassing brassy brat brats bravado braved bravely braver bravery braves bravest braving bravo bravos brawl brawled brawling brawls brawn brawnier brawniest brawny bray brayed braying brays brazen brazened brazening brazens brazier braziers breached breaches breaching breaded breading breads breadth breadths breadwinner breadwinners breakable breakables breakdowns breakfasted breakfasting breakfasts breakneck breakpoints breakthrough breakthroughs breakwater breakwaters breast breasted breasting breasts breather breathers breathless breaths breathtaking breded bredes breding breeder breeders breezed breezes breezier breeziest breezing breezy brevity brew brewed breweries brewery brewing brews bribe bribed bribery bribes bribing bricked bricking bricklayer bricklayers bridal bridals bride bridegroom bridegrooms brides bridesmaid bridesmaids bridged bridging bridle bridled bridles bridling briefcase briefcases briefed briefer briefest briefing briefs brigades brighten brightened brightening brightens brights brilliance brilliants brim brimmed brimming brims brimstone brine brinier briniest brink brinks briny brisk brisked brisker briskest brisking briskly brisks bristle bristled bristles bristling britches brittle brittler brittlest broach broached broaches broaching broaden broadened broadening broadens broader broadest broads broadside broadsided broadsides broadsiding brocade brocaded brocades brocading broccoli brochure brochures broil broiled broiler broilers broiling broils broker brokered brokering brokers bronchitis bronco broncos bronze bronzed bronzes bronzing brooch brooches brood brooded brooding broods brook brooked brooking brooks broom brooms broth brothered brotherhood brotherhoods brothering brotherly broths brow browbeat browbeaten browbeating browbeats browned browner brownest brownie brownier brownies browniest browning browns brows bruise bruised bruises bruising brunch brunched brunches brunching brunette brunettes brunt brunted brunting brunts brushed brushes brushing brusque brusquer brusquest brutalities brutality brutally brute brutes brutish bubbled bubbles bubblier bubbliest bubbling bubbly bucked bucketed bucketing buckets bucking buckle buckled buckles buckling bud budded buddies budding buddy budge budged budges budgeted budgeting budgets budging buds buff buffalo buffaloed buffaloes buffaloing buffed buffet buffeted buffeting buffets buffing buffoon buffoons buffs bugged buggier buggies buggiest bugging buggy bugle bugled bugler buglers bugles bugling builder builders bulbed bulbing bulbous bulge bulged bulges bulging bulked bulkier bulkiest bulking bulks bulky bulldog bulldogged bulldogging bulldogs bulldoze bulldozed bulldozer bulldozers bulldozes bulldozing bulled bulletined bulletining bulletins bullfight bullfighter bullfighters bullfights bullfrog bullfrogs bullied bullier bullies bulliest bulling bullion bulls bully bullying bum bumblebee bumblebees bummed bummer bummest bumming bumped bumper bumpers bumpier bumpiest bumping bumps bumpy bums bun bunched bunches bunching bundled bundles bundling bung bungalow bungalows bungle bungled bungler bunglers bungles bungling bunion bunions bunk bunked bunker bunkers bunking bunks bunnies bunny buns buoy buoyancy buoyant buoyed buoying buoys burble burbled burbles burbling burdened burdening burdens burdensome bureau bureaucracies bureaucrat bureaucratic bureaucrats bureaus burger burgers burglar burglaries burglars burglary burgle burial burials burlap burlier burliest burly burner burners burnish burnished burnishes burnishing burp burped burping burps burr burred burring burro burros burrow burrowed burrowing burrows burrs bursar bused bushed bushel bushels bushes bushier bushiest bushing bushy busied busier busies busiest busily businessman businessmen businesswoman businesswomen busing bussed busted busting bustle bustled bustles bustling busts busybodies busybody busying butcher butchered butcheries butchering butchers butchery butler butlered butlering butlers buts butt butte butted buttercup buttercups buttered butterflied butterflies butterfly butterflying buttering buttermilk butters butterscotch buttery buttes butting buttock buttocks buttoned buttonhole buttonholed buttonholes buttonholing buttoning buttress buttressed buttresses buttressing butts buxom buxomer buxomest buzz buzzard buzzards buzzed buzzer buzzers buzzes buzzing byes bygone bygones bypassed bypasses bypassing bystander bystanders byway byways cab cabaret cabarets cabbages cabbed cabbing cabin cabinets cabins caboose cabooses cabs cacao cacaos cache cached caches caching cackle cackled cackles cackling cacti cactus cad caddied caddies cadence cadences cadet cadets cafes cafeteria cafeterias caged cages cagey cagier cagiest caging cajole cajoled cajoles cajoling caked caking calamities calamity calcium calculators calculi calendared calendaring calendars calf calibrate calibrated calibrates calibrating calibration calibrations calico calicoes callable callers calligraphy callings callous calloused callouses callousing callow callus callused calluses callusing calmed calmer calmest calming calmly calmness calms calorie calories calve calves camaraderie camel camels cameo cameoed cameoing cameos camerae camouflage camouflaged camouflages camouflaging campaigner campaigners camped camper campers campest camping campused campuses campusing canal canals canaries canary cancellation cancellations cancers candid candidacies candidacy candider candidest candidly candied candies candle candled candles candlestick candlesticks candling candy candying cane caned canes canine canines caning canister canistered canistering canisters canker cankered cankering cankers canned canneries cannery cannibal cannibalism cannibals cannier canniest canning cannon cannoned cannoning cannons canny canoe canoed canoes canon canons canopied canopies canopy canopying cantaloupe cantaloupes cantankerous canteen canteens canter cantered cantering canters canvas canvased canvases canvasing canvass canvassed canvasser canvassers canvasses canvassing canyon canyons capabler capablest capably capacitance capacities capacitor capacitors cape caped caper capered capering capers capes capillaries capillary capitalists capitulate capitulated capitulates capitulating capped capping caprice caprices capricious capriciously capsize capsized capsizes capsizing capsule capsuled capsules capsuling captained captaining captains caption captioned captioning captions captivate captivated captivates captivating captive captives captivities captivity captor captors caramel caramels carat carats caravan caravans carbohydrate carbohydrates carbons carburetor carburetors carcass carcasses carcinogenic carded cardiac cardigan cardigans cardinal cardinals carding careered careering carefree carefuller carefullest carefulness carelessly carelessness caress caressed caresses caressing caretaker caretakers cargo cargoes caribou caribous caricature caricatured caricatures caricaturing carnage carnal carnation carnations carnival carnivals carnivore carnivores carnivorous carol carols carouse caroused carouses carousing carp carped carpenter carpentered carpentering carpenters carpentry carpeted carpeting carpets carping carps carriages carriageway carriers carrion cart carted cartel cartels cartilage cartilages carting cartographer cartographers cartography carton cartons cartooned cartooning cartoonist cartoonists carts cartwheel cartwheeled cartwheeling cartwheels carve carved carves carving cascade cascaded cascades cascading cashed cashes cashew cashews cashier cashiered cashiering cashiers cashing cashmere casings casino casinos cask casket caskets casks casserole casseroled casseroles casseroling castaway castaways caste casted caster casters castes castigate castigated castigates castigating castings castled castles castling castoff castoffs castrate castrated castrates castrating casually casuals casualties casualty cataclysm cataclysmic cataclysms catapult catapulted catapulting catapults cataract cataracts catastrophe catastrophes catcall catcalled catcalling catcalls catchier catchiest catchings catchment catchy catechism catechisms categorical caterer caterers caterpillar caterpillars catfish catfishes cathedrals catholics catnap catnapped catnapping catnaps catnip catwalk catwalks caucus caucused caucuses caucusing cauliflower cauliflowers caulk caulked caulking caulks causeway causeways caustic caustics cautioned cautioning cautions cautious cautiously cavalier cavaliers cavalries cavalry caveats caved cavern caverns caves caviar caving cavities cavity cavort cavorted cavorting cavorts caw cawed cawing caws ceasefire ceaseless ceaselessly cedar cedars cede ceded cedes ceding ceilings celebrations celebrities celebrity celery celestial celibacy celibate celibates cellar cellars celled celling cellist cellists cello cellophane cellos cellulars cellulose cement cemented cementing cements cemeteries cemetery censure censured censures censuring census censused censuses censusing centennial centennials centipede centipedes centraler centralest centrals centrifuge cents ceramic cereal cereals cerebral ceremonial ceremonials ceremonies ceremonious certainer certainest certainties certificated certificates certificating certified certifies certify certifying cervical cessation cessations chafe chafed chafes chaff chaffed chaffing chaffs chafing chagrin chagrined chagrining chagrins chained chaining chainsaw chaired chairing chairmen chairperson chairpersons chalet chalets chalice chalices chalked chalkier chalkiest chalking chalks chalky challenger challengers chambers chameleon chameleons champ champagnes champed champing championed championing champions championship championships champs chanced chancellors chancing chandelier chandeliers changeable chant chanted chanting chants chapels chaperon chaperoned chaperoning chaperons chaplain chaplains chapped chapping characteristically charcoal charcoals chargeable charger chariot chariots charisma charismatic charismatics charitably charlatan charlatans charminger charmingest charred charring charted chartered chartering charters charting chasm chasms chassis chaste chasten chastened chastening chastens chaster chastest chastise chastised chastisement chastisements chastises chastising chastity chatter chatterbox chatterboxes chattered chattering chatters chattier chattiest chatty chauffeur chauffeured chauffeuring chauffeurs chauvinist chauvinists cheapen cheapened cheapening cheapens cheapness checkout checkpoint checkup checkups cheeked cheeking cheeks cheep cheeped cheeping cheeps cheered cheerfuller cheerfullest cheerfully cheerfulness cheerier cheeriest cheering cheery cheesecloth cheesed cheeses cheesing cheetah cheetahs chef cheffed cheffing chefs chemically cherish cherished cherishes cherishing cherries cherry cherub cherubim cherubs chestnuts chests chewier chewiest chewy chi chic chicer chicest chick chickened chickening chicks chide chided chides chiding chiefer chiefest chiefly chiefs chieftain chieftains childbirth childbirths childed childes childhoods childing childlike chili chilies chill chilled chiller chillest chillier chillies chilliest chilling chills chilly chime chimed chimes chiming chimney chimneys chimp chimpanzee chimpanzees chimps chin china chink chinked chinking chinks chinned chinning chins chintz chipmunk chipmunks chipped chipper chippers chipping chiropractor chiropractors chirp chirped chirping chirps chisel chiseled chiseling chisels chivalrous chivalry chlorine chloroform chloroformed chloroforming chloroforms chlorophyll chocolates choicer choicest choirs choke choked chokes choking cholera cholesterol choosier choosiest choosy chopper choppered choppering choppers choppier choppiest choppy chorals chords chore chored choreographer choreographers choreography chores choring chortle chortled chortles chortling chorused choruses chorusing chow chowder chowdered chowdering chowders chowed chowing chows christen christened christening christenings christens chrome chromed chromes chroming chromium chromosome chromosomes chronic chronically chronicle chronicled chronicles chronicling chronics chronological chronologically chronologies chronology chrysanthemum chrysanthemums chubbier chubbiest chubby chuckle chuckled chuckles chuckling chug chugged chugging chugs chum chummed chummier chummies chummiest chumming chummy chums chunkier chunkiest chunky churn churned churning churns chute chutes ciders cigar cigarettes cigars cinch cinched cinches cinching cinder cindered cindering cinders cinemas cinnamon cipher ciphered ciphering ciphers circled circling circuited circuiting circuitous circulars circulations circulatory circumcise circumcised circumcises circumcising circumcision circumcisions circumference circumferences circumflex circumstanced circumstancing circumstantial circumstantials circumvent circumvented circumventing circumvention circumvents circus circuses cistern cisterns citation citations citizenship citric citrus citruses civic civics civilians civilities civility clack clacked clacking clacks clad clairvoyance clairvoyant clairvoyants clam clamber clambered clambering clambers clammed clammier clammiest clamming clammy clamp clamped clamping clamps clams clan clandestine clang clanged clanging clangs clank clanked clanking clanks clans clap clapped clapper clappered clappering clappers clapping claps claptrap claret clarifications clarinet clarinets clashed clashing clasp clasped clasping clasps classifications classmate classmates classroom classrooms classy clatter clattered clattering clatters claustrophobia claw clawed clawing claws clay cleanlier cleanliest cleanliness cleanse cleansed cleanser cleansers cleanses cleansing clearances clearings clearness cleat cleats cleavage cleavages cleave cleaved cleaver cleavers cleaves cleaving clef clefs cleft clefted clefting clefts clemency clench clenched clenches clenching clergies clergy clergyman clergymen cleric clerical clerics clerk clerked clerking clerks cleverly cleverness cliches clicked clicking clicks clientele clienteles cliffs climactic climates climax climaxed climaxes climaxing climber climbers clime climes clinch clinched clinches clinching cling clinging clings clinically clinics clink clinked clinking clinks clipboard clipboards clippings cliques clitoris cloak cloaked cloaking cloaks clocked clocking clockwise clockwork clockworks clod clodded clodding clods clogged clogging clogs cloister cloistered cloistering cloisters closeness closeted closeting closets closures clot clothespin clothespins cloths clots clotted clotting cloudburst cloudbursts clouded cloudier cloudiest clouding cloudy clout clouted clouting clouts clove cloven clover clovers cloves clown clowned clowning clowns clubbed clubbing clubhouse clubhouses cluck clucked clucking clucks clued clueless cluing clump clumped clumping clumps clumsier clumsiest clumsily clumsiness clung clustered clustering clutch clutched clutches clutching clutter cluttered cluttering clutters coached coaches coaching coagulate coagulated coagulates coagulating coagulation coaled coalesce coalesced coalesces coalescing coaling coalition coalitions coals coarsely coarsen coarsened coarseness coarsening coarsens coarser coarsest coastal coasted coaster coasters coasting coastline coastlines coasts coated coater coating coattest coax coaxed coaxes coaxing cob cobalt cobbed cobbing cobble cobra cobras cobs cobweb cobwebs cocaine cock cocked cockeyed cockier cockiest cocking cockpit cockpits cockroach cockroaches cocks cocktail cocktails cocky cocoa cocoas coconut coconuts cocoon cocooned cocooning cocoons cod codded codding cods coefficient coefficients coerce coerced coerces coercing coercion coexist coexisted coexistence coexisting coexists coffees coffer coffers coffin coffined coffining coffins cog cogency cogent cognac cognacs cognitive cogs coherence coherently coil coiled coiling coils coinage coinages coincided coincidences coincidental coincidentally coincides coinciding coked cokes coking colander colanders colder coldest coldly coldness colds colic collaborate collaborated collaborates collaborating collaborations collaborative collaborator collaborators collage collages collapsible collarbone collarbones collared collaring collars collateral collation colleagued colleaguing collectively collectives collector collectors collegiate collide collided collides colliding collie collied collies collision collisions colloquial colloquialism colloquialisms colloquials collusion collying colonel colonels colonial colonials colonies colons colossal colt colts coma comae comas comb combatant combatants combated combating combats combed combing combs combustible combustibles combustion comeback comedian comedians comedies comelier comeliest comely comestible comestibles comet comets comforted comforting comforts comical comings commandant commandants commanded commandeer commandeered commandeering commandeers commander commanders commanding commando commandos commemorate commemorated commemorates commemorating commemoration commemorations commenced commencement commencements commences commencing commend commendable commendation commendations commended commending commends commentaries commerce commerced commerces commercialism commercials commercing commiserate commiserated commiserates commiserating commiseration commiserations commissioner commissioners commodities commodore commodores commoner commonest commonplace commonplaces commonwealth commonwealths commotion commotions commune communed communes communicable communicative communicator communing communion communions communique communiques commutative commute commuted commuter commuters commutes commuting compacted compacter compactest compacting compaction compacts companions companionship comparatives compartment compartments compass compassed compasses compassing compassionate compatibles compatriot compatriots compensated compensates compensating compensations competences competently competitions compilations complacency complemented complementing complements completer completest complexer complexes complexest complexion complexioned complexions complexities compliance compliant complied complies complimentary complimented complimenting compliments complying composites compositions compost composted composting composts composure compounded compounding compounds comprehended comprehending comprehends comprehensions comprehensively comprehensives compromised compromises compromising compulsions compulsive compulsories compunction compunctions computations comrade comrades comradeship concatenation concatenations concave concealment conceded concedes conceding conceit conceited conceits concentrations concentric conceptions conceptually concerted concerting concertos concession concessions conciliate conciliated conciliates conciliating conciliation concisely conciseness conciser concisest conclusive conclusively concoct concocted concocting concoction concoctions concocts concord concordance concourse concourses concreted concretes concreting concurred concurrence concurrences concurrency concurrent concurring concurs concussion concussions condemnations condensation condensations condescend condescended condescending condescends condiment condiments conditionally conditionals condolence condolences condominium condominiums condoms condoned condones condoning condor condors conducive conductors cone cones confection confections confederacies confederacy confederate confederated confederates confederating confederation confederations confer conferred conferrer conferring confers confessed confesses confessing confession confessions confetti confidant confidants confide confided confidences confidentially confidently confides confiding configurable confinement confinements confirmations confiscate confiscated confiscates confiscating confiscation confiscations conformed conforming conformity conforms confound confounded confounding confounds confrontation confrontations congeal congealed congealing congeals congenial conglomerate conglomerated conglomerates conglomerating congratulated congratulates congratulating congregate congregated congregates congregating congregation congregations congress congresses congressman congressmen congresswoman congresswomen congruent conical conicals conifer coniferous conifers conjectured conjectures conjecturing conjugal conjugate conjugated conjugates conjugating conjugation conjugations conjunctions conjure conjured conjures conjuring connective connectivity connectors conned connexion conning connoisseur connoisseurs connote connoted connotes connoting conquer conquered conquering conqueror conquerors conquers conquest conquests cons consciences conscientious consciouses consciousnesses consecrate consecrated consecrates consecrating consensuses consequential conservatism conservatories conservatory conserve conserved conserves conserving considerings consign consigned consigning consignment consignments consigns consistencies consolations consoled consoles consolidate consolidated consolidates consolidating consolidation consolidations consoling consomme consonant consonants consort consorted consorting consortium consorts conspicuously conspiracies conspirator conspirators conspire conspired conspires conspiring constancy constellation constellations consternation constipation constituencies constituted constituting constitutionally constitutionals constitutions constrict constricted constricting constriction constrictions constricts construe construed construes construing consul consular consulars consulate consulates consuls consultations consumable consumables consumerism consumers consummate consummated consummates consummating contagion contagions contagious containers contaminate contaminated contaminates contaminating contamination contemplation contemplative contemplatives contemporaries contemptible contemptuous contended contender contenders contending contends contented contenting contentions contentment contestant contestants contested contesting contests contextual contiguous continentals continents contingencies contingency contingent contingents contort contorted contorting contortion contortions contorts contoured contouring contours contraband contraceptive contraceptives contraction contractions contractor contractors contractual contradictions contraption contraptions contraries contrasted contrasting contrasts contravene contravenes contributory contrite controllable controversies convalesce convalesced convalescence convalescences convalescent convalescents convalesces convalescing convection convene convened convenes conveniences convening convent convented conventing conventionally convents converge converged convergence converges converging conversant conversational conversed converses conversing converters convertible convertibles convex convexed convexes convexing conveyance conveyances conveyed conveying conveys convoluted convoy convoyed convoying convoys convulse convulsed convulses convulsing convulsion convulsions convulsive coo cooed cooing cookbook cookbooks cooker cooler coolers coolest coolly coop cooped cooper cooperated cooperates cooperating cooperative cooperatives cooping coops coordinated coordinating coordinator coos cop copier copiers copious copiously copped copperhead copperheads coppers copping cops copulate copulation copyrighted copyrighting copyrights coral corals cord corded cordial cordially cordials cording cordless cordon cordoned cordoning cordons cords corduroy cored cores coring cork corked corking corks corkscrew corkscrewed corkscrewing corkscrews cornea corneas corned cornered cornering cornet cornets cornflakes cornier corniest corning cornmeal corns cornstarch corny corollary coronaries coronary coronation coronations coroner coroners corporal corporals corporations corps corpulent corpus corpuscle corpuscles corral corralled corralling corrals correcter correctest corrective correctness corrector correlated correlates correlating correlations correspondences correspondents correspondingly corridors corroborate corroborated corroborates corroborating corroboration corrode corroded corrodes corroding corrosion corrosive corrosives corrupter corruptest corruptible corruptions corsage corsages corset corseted corseting corsets cortex cosmetic cosmetics cosmonaut cosmonauts cosmopolitan cosmopolitans cosmos cosmoses costings costlier costliest costume costumed costumes costuming cot coting cots cottage cottaged cottages cottaging cotted cottoned cottoning cottons cottontail cottontails cottonwood cottonwoods couch couched couches couching cougar cougars coughed coughing coughs countable countdown countdowns countenance countenanced countenances countenancing counteract counteracted counteracting counteracts counterattack counterattacked counterattacking counterattacks counterbalance counterbalanced counterbalances counterbalancing counterclockwise countered counterfeit counterfeited counterfeiting counterfeits countering counters countersign countersigned countersigning countersigns countess countesses counties countryman countrymen countrysides coup coupon coupons coups courageous courageously couriered couriering couriers coursed courser coursing courted courteous courteously courtesies courthouse courthouses courting courtroom courtrooms courtship courtships courtyard courtyards cousins cove covenant covenanted covenanting covenants covert covertly coverts coves covet coveted coveting covetous covets coward cowardice cowardly cowards cowboy cowboys cowed cower cowered cowering cowers cowgirl cowgirls cowhide cowhides cowing cox coy coyer coyest coyote coyotes cozily coziness crab crabbed crabbier crabbiest crabbing crabby crabs cracker crackers crackle crackled crackles crackling crackpot crackpots cradle cradled cradles cradling crafted craftier craftiest craftily crafting crafts craftsman craftsmen crafty crag craggier craggiest craggy crags cram crammed cramming crams cranberries cranberry crane craned cranes craning cranium craniums crank cranked cranker crankest crankier crankiest cranking cranks cranky crasser crassest crate crated crater cratered cratering craters crates crating crave craved craves craving cravings crayfish crayfishes crayon crayoned crayoning crayons craze crazed crazes crazier crazies craziest crazily craziness crazing creak creaked creakier creakiest creaking creaks creaky creamed creamier creamiest creaming creams creamy crease creased creases creasing creations creatively creativity creators credence credential credentials creditable credited crediting creditor creditors credulous creeds creek creeks creepier creepies creepiest creeping creeps creepy cremate cremated cremates cremating cremation cremations crepe crepes crept crescendo crescendos crescent crescents crest crested crestfallen cresting crests cretin cretinous cretins crevasse crevasses crevice crevices crewed crewing crews crib cribbed cribbing cribs crickets crimed criminally criming crimson crimsoned crimsoning crimsons cringe cringed cringes cringing crinkle crinkled crinkles crinkling cripple crippled cripples crippling crises crisped crisper crispest crisping crisply crispy crisscross crisscrossed crisscrosses crisscrossing critically critique critiqued critiques critiquing croak croaked croaking croaks crochet crocheted crocheting crochets crock crockery crocks crocodile crocodiles crocus crocuses crofts cronies crony crook crooked crookeder crookedest crooking crooks croon crooned crooning croons cropped cropping croquet crossbow crossbows crosser crossest crossings crosswalk crosswalks crosswords crotch crotches crouch crouched crouches crouching crow crowbar crowbars crowed crowing crowned crowning crowns crows crucially crucified crucifies crucifix crucifixes crucifixion crucifixions crucify crucifying crudely cruder crudest crudity crueler cruelest cruelly cruels cruelties cruiser cruisers crumb crumbed crumbing crumble crumbled crumbles crumblier crumblies crumbliest crumbling crumbly crumbs crummier crummiest crummy crumple crumpled crumples crumpling crunchy crusade crusaded crusader crusaders crusades crusading crust crustacean crustaceans crusted crustier crusties crustiest crusting crusts crusty crutch crutches crux cruxes crybabies crybaby crypt crypts cub cubed cubes cubicle cubicles cubing cubs cuckoos cucumber cucumbers cuddle cuddled cuddles cuddling cued cues cuff cuffed cuffing cuffs cuing cuisine cuisines culinary cull culled culling culls culminate culminated culminates culminating culmination culminations culpable culprits cultivate cultivated cultivates cultivating cultivation cults culturally cultured culturing cunninger cunningest cunningly cupboards cupful cupfuls cupped cupping cur curable curator curators curd curdle curdled curdles curdling curds curfew curfews curio curios curiosities curiouser curiousest curl curled curling curls currant currants currencies currents curricula curried curries currying cursed curses cursing cursory curt curtail curtailed curtailing curtails curtained curtaining curter curtest curtsied curtsies curtsy curtsying curvature curvatures curved curving cushion cushioned cushioning cushions custards custodian custodians custody cutback cutbacks cuter cutes cutest cuticle cuticles cutlery cutlet cutlets cutter cutters cutthroat cutthroats cuttings cyanide cybernetics cyclic cyclone cyclones cylinders cylindrical cymbal cymbals cynicism cynics cypress cypresses cyst cysts dab dabbed dabbing dabble dabbled dabbles dabbling dabs dachshund dachshunds dad daddies daddy dads daemon daffodil daffodils dagger daggers dailies daintier dainties daintiest daintily dainty dairies dairy dais daises daisies daisy dallied dallies dally dallying dam dame dames dammed damming damneder damnedest damped dampen dampened dampening dampens damper dampest damping dampness damps dams damsel damsels dancer dancers dandelion dandelions dandier dandies dandiest dandruff dandy dangered dangering dangle dangled dangles dangling dank danker dankest dapper dapperer dapperest dappers daredevil daredevils darken darkened darkening darkens darker darkest darklier darkliest darkly darlings darn darned darning darns dart darted darting darts dashboard dashboards dastardly daub daubed daubing daubs daughters daunt daunted daunting dauntless daunts dawdle dawdled dawdles dawdling dawned dawning dawns daybreak daydream daydreamed daydreaming daydreams daze dazed dazes dazing dazzle dazzled dazzles dazzling deacon deacons deaden deadened deadening deadens deader deadest deadlier deadliest deadlined deadlines deadlining deadlock deadlocked deadlocking deadlocks deafer deafest deafness dealings dean deaned deaning deans dearer dearest dearly dears dearth dearths deathbed deathbeds deaves debase debased debasement debasements debases debasing debaucheries debauchery debilitate debilitated debilitates debilitating debilities debility debit debited debiting debits debonair debrief debriefed debriefing debriefs debris debtor debtors debts debunk debunked debunking debunks debut debutante debutantes debuted debuting debuts decadence decadent decadents decanter decanters decapitate decapitated decapitates decapitating decayed decaying decays decease deceased deceases deceasing deceit deceitful deceitfully deceits deceive deceived deceives deceiving decencies decency decenter decentest decently deception deceptions deceptive decibel decibels decidedly deciduous decimals decimate decimated decimates decimating decipher deciphered deciphering deciphers decisive decisively decked decking decks declension decoder decompose decomposed decomposes decomposing decomposition decorate decorated decorates decorating decoration decorations decorative decorator decorators decorous decorum decoy decoyed decoying decoys decree decreed decreeing decrees decrepit decried decries decry decrying dedication dedications deduct deducted deducting deductive deducts deeded deeding deepen deepened deepening deepens deeps deer deface defaced defaces defacing defamation defamatory defame defamed defames defaming defaulted defaulting defeatist defecate defecated defecates defecating defected defecting defectives defendant defendants defender defenders defensible defer deference deferential deferred deferring defers defiance defiant defiantly deficient deficit deficits defied defies defile defiled defiles defiling definable deflate deflated deflates deflating deflation deflect deflected deflecting deflection deflections deflects deform deformed deforming deformities deformity deforms defraud defrauded defrauding defrauds defrost defrosted defrosting defrosts deft defter deftest deftly defunct defuncts defying degenerated degenerates degenerating dehydrate dehydrated dehydrates dehydrating deified deifies deify deifying deign deigned deigning deigns deities deject dejected dejecting dejection dejects delectable delegate delegated delegates delegating delegation delegations deleterious deletions deli deliberated deliberates deliberating deliberation deliberations delicacies delicacy delicately delicatessen delicatessens deliciously delimit delimited delimiter delimiting delimits delinquencies delinquency delinquent delinquents delirious deliriously delirium deliriums delis deliverance deliveries deltas delude deluded deludes deluding deluge deluged deluges deluging delusions deluxe delve delved delves delving demagogue demagogues demean demeaned demeaning demeans dementia demerit demerited demeriting demerits demised demises demising democracies democrat democrats demolition demolitions demon demons demonstrably demonstrative demonstratives demonstrator demonstrators demote demoted demotes demoting demotion demotions demount demure demurely demurer demurest den denial denials denigrate denim denims denomination denominations denominators denoted denoting denounce denounced denounces denouncing dens densely denser densest densities dent dental dented denting dentistry dentists dents denunciation denunciations deodorant deodorants depart departed departing departs departures dependable dependencies dependency depict depicted depicting depiction depicts deplete depleted depletes depleting deplorable deplore deplored deplores deploring deport deportation deportations deported deporting deportment deports depose deposed deposes deposing deposited depositing deposits depot depots deprave depraved depraves depraving depravities depravity deprecate deprecated deprecates deprecating depreciate depreciated depreciates depreciating depreciation depressingly depressions deprivation deprivations deputies derail derailed derailing derailment derailments derails derelict derelicts deride derided derides deriding derision derivation derivations derivatives derrick derricks descendant descendants descent descents describable descriptor descriptors desecrate desecrated desecrates desecrating desecration desegregation deserter deserters designation designations desirability desirous desist desisted desisting desists desks desolate desolated desolates desolating desolation despaired despairing despairs desperation despicable despised despises despising despondent despot despotic despots dessert desserts destinations destinies destiny destitute destitution destroyer destroyers detachable detachment detachments detain detained detaining detains detectives detectors detention detentions detergent detergents deteriorate deteriorated deteriorates deteriorating deterioration determinable determinations determinism deterministic deterred deterrents deterring deters detest detested detesting detests dethrone dethroned dethrones dethroning detonate detonated detonates detonating detonation detonations detonator detonators detour detoured detouring detours detracted detracting detracts detriment detrimental detriments devalue devastation deviant deviate deviated deviates deviating deviations devils devolution devolve devolved devolves devolving devotee devotees devotion devotions devour devoured devouring devours devout devouter devoutest devoutly dew dexterity dexterous diabetes diabetic diabetics diabolical diagnose diagnosed diagnoses diagnosing diagonally diagonals diagrammed diagramming diameters diametrically diamond diamonds diaper diapered diapering diapers diaphragm diaphragms diaries diatribe diced dices dicing dictated dictates dictating dictation dictations dictatorial dictators dictatorships diction dieing dieseled dieseling diesels dietaries dietary dieted dieting diets differentiated differentiates differentiating differentiation diffuse diffused diffuses diffusing diffusion digested digestible digesting digestion digestions digestive digests digger digitally dignified dignifies dignify dignifying dignitaries dignitary dignities digress digressed digresses digressing digression digressions dike dikes dilapidated dilate dilated dilates dilating dilation dilemmas diligence diligent diligently dill dilled dilling dills dilute diluted dilutes diluting dilution dime dimer dimes diminish diminished diminishes diminishing diminutive diminutives dimly dimmed dimmer dimmest dimming dimple dimpled dimples dimpling dims din diners dinghies dinghy dingier dingies dingiest dingy dinned dinnered dinnering dinners dinning dinosaur dinosaurs dins diocese dioceses dioxide diphtheria diphthong diphthongs diploma diplomacy diplomas diplomat diplomata diplomatically diplomatics diplomats dipped dipping dips directer directest directness direr direst dirge dirges dirtied dirtier dirties dirtiest dirtying disabilities disability disadvantaged disadvantageous disadvantaging disagreeable disagreeably disagreements disallow disallowed disallowing disallows disambiguate disappearance disappearances disappointments disapproval disapprove disapproved disapproves disapproving disarm disarmament disarmed disarming disarms disarray disarrayed disarraying disarrays disavow disavowed disavowing disavows disband disbanded disbanding disbands disbelief disbelieve disbelieved disbelieves disbelieving disburse disbursed disbursement disbursements disburses disbursing discern discerned discernible discerning discerns discharged discharges discharging disciple disciples disciplinarian disciplinarians disciplined disciplines disciplining disclaim disclaimed disclaiming disclaims disclose disclosed discloses disclosing disclosure disclosures discomfort discomforted discomforting discomforts disconcert disconcerted disconcerting disconcerts disconsolate disconsolately discontent discontented discontenting discontents discontinuity discord discordant discorded discording discords discos discounted discounting discouragement discouragements discourse discoursed discourses discoursing discourteous discourtesies discourtesy discredit discredited discrediting discredits discreet discreeter discreetest discreetly discrepancies discretionary discriminatory discus discuses disdain disdained disdainful disdaining disdains diseased disembark disembarkation disembarked disembarking disembarks disenchantment disengage disengaged disengages disengaging disentangle disentangled disentangles disentangling disfigure disfigured disfigures disfiguring disgrace disgraced disgraceful disgraces disgracing disgruntle disgruntled disgruntles disgruntling disgustingly dishearten disheartened disheartening disheartens dished dishing dishonestly dishonesty dishwasher dishwashers disillusion disillusioned disillusioning disillusionment disillusions disincentive disinfect disinfectant disinfectants disinfected disinfecting disinfects disingenuous disinherit disinherited disinheriting disinherits disintegrate disintegrated disintegrates disintegrating disintegration disinterested disjoint disjointed disjointing disjoints disks dislocate dislocated dislocates dislocating dislocation dislocations dislodge dislodged dislodges dislodging disloyal disloyalty dismaler dismalest dismally dismantle dismantled dismantles dismantling dismay dismayed dismaying dismays dismember dismembered dismembering dismembers dismissal dismissals dismissive dismount dismounted dismounting dismounts disobedience disobedient disobey disobeyed disobeying disobeys disordered disordering disorderly disorders disown disowned disowning disowns disparage disparaged disparages disparaging disparate disparities disparity dispassionate dispassionately dispatch dispatched dispatches dispatching dispel dispelled dispelling dispels dispensaries dispensary dispensation dispensations dispense dispensed dispenser dispensers dispenses dispensing dispersal disperse dispersed disperses dispersing dispersion displace displaced displacement displacements displaces displacing displease displeased displeases displeasing displeasure disposables disposals dispositions dispossess dispossessed dispossesses dispossessing disproportionate disproportionated disproportionates disproportionating disprove disproved disproves disproving disputed disputes disputing disqualified disqualifies disqualify disqualifying disquiet disquieted disquieting disquiets disregarded disregarding disregards disrepair disreputable disrepute disrespect disrespected disrespectful disrespecting disrespects disrupted disrupting disruptions disruptive disrupts dissatisfaction dissatisfied dissatisfies dissatisfy dissatisfying dissect dissected dissecting dissection dissections dissects disseminate disseminated disseminates disseminating dissemination dissension dissensions dissent dissented dissenter dissenters dissenting dissents dissertations disservice disservices dissident dissidents dissimilarities dissimilarity dissimilars dissipate dissipated dissipates dissipating dissipation dissociate dissociated dissociates dissociating dissociation dissolute dissolutes dissolution dissolve dissolved dissolves dissolving dissonance dissonances dissuade dissuaded dissuades dissuading distanced distancing distantly distaste distastes distend distended distending distends distill distillation distillations distilled distiller distilleries distillers distillery distilling distills distincter distinctest distinctively distinguishable distorter distortions distraction distractions distraught distressingly distributions distributor distributors districts distrust distrusted distrustful distrusting distrusts disturbances disuse disused disuses disusing ditched ditches ditching dither dithered dithering dithers ditties dittoed dittoing dittos ditty diver diverge diverged divergence divergences divergent diverges diverging divers diversified diversifies diversify diversifying diversion diversions diversities divest divested divesting divests dividend dividends divined diviner divines divinest divining divinities divinity divisible divisive divisor divisors divorced divorcee divorcees divorces divorcing divulge divulged divulges divulging dizzied dizzier dizzies dizziest dizziness dizzy dizzying docile dock docked docking docks doctorate doctored doctoring doctrines documentaries dodged dodges dodging dodo doer doers doest dogged doggedly doggerel dogging doghouse doghouses dogmas dogmatic dogmatics dogwood dogwoods doilies doily doldrums doled doleful dolefuller dolefullest dolefully doles doling doll dolled dollies dolling dolls dolly dolphin dolphins domains dome domed domes domesticate domesticated domesticates domesticating domesticity domestics domicile domiciled domiciles domiciling dominance dominants domination doming dominion dominions domino dominoes donkey donkeys donor donors doodle doodled doodles doodling doored dooring doorman doormen doorstep doorstepped doorstepping doorsteps doorway doorways dope doped dopes dopey dopier dopiest doping dormant dormants dormitories dormitory dorsal dorsals dos dosed dosing dote doted dotes doting doubly doubted doubtfully doubting dough dour dourer dourest douse doused douses dousing dove doves dowdier dowdies dowdiest dowdy downcast downed downfall downfalls downgrade downgraded downgrades downgrading downhearted downhills downier downiest downing downpour downpours downs downstream downtown downward downy dowries dowry doze dozed dozes dozing drab drabber drabbest drabs draconian dragonflies dragonfly dragons drainage dramas dramatics dramatist dramatists drape draped draperies drapery drapes draping drawbridge drawbridges drawer drawers drawl drawled drawling drawls dreadfully dreamer dreamers dreamier dreamiest dreamy drearier drearies dreariest dredge dredged dredges dredging dregs drench drenched drenches drenching dresser dressers dressier dressiest dressings dressmaker dressmakers dressy dribble dribbled dribbles dribbling drier driers driest drifted drifting drifts driftwood drilled drilling drills drinkable drinker drinkers drivels driveway driveways drizzle drizzled drizzles drizzling droll droller drollest drone droned drones droning drool drooled drooling drools droop drooped drooping droops dropout dropouts droppings dross drought droughts droves drowse drowsed drowses drowsier drowsiest drowsiness drowsing drowsy drudge drudged drudgery drudges drudging drugged drugging druggist druggists drugstore drugstores drummed drummer drummers drumming drumstick drumsticks drunkard drunkards drunkenly drunkenness drunker drunkest drunks dryer dryers dryly dryness drys dualism dub dubbed dubbing dubiously dubs duchess duchesses ducked ducking duckling duct ducts dud dude duded dudes duding duds duel duels dues duet duets dugout dugouts duke duked dukes duking dulled duller dullest dulling dullness dulls dully dumbbell dumbbells dumbed dumber dumbest dumbfound dumbfounded dumbfounding dumbfounds dumbing dumbs dummies dumpier dumpies dumpiest dumpling dumpy dunce dunces dune dunes dung dunged dungeon dungeoned dungeoning dungeons dunging dungs dunk dunked dunking dunks dunno duo dupe duped dupes duping duplex duplexes duplicity durability durable duress dusk duskier duskiest dusky dusted dustier dustiest dusting dustmen dustpan dustpans dusts dutiful dutifully duvet dwarf dwarfed dwarfer dwarfest dwarfing dwarfs dwell dweller dwellers dwelling dwellings dwells dwelt dwindle dwindled dwindles dwindling dye dyed dyeing dyes dynamical dynamite dynamited dynamites dynamiting dynamo dynamos dynasties dynasty dysentery dyslexia eagerer eagerest eagerness eagles earache earaches eardrum eardrums earl earls earmark earmarked earmarking earmarks earner earners earnest earnestly earnestness earnests earnings earring earrings earshot earthed earthier earthiest earthing earthlier earthliest earthly earthquake earthquaked earthquakes earthquaking earths earthworm earthworms earthy eased easel easels eases easies easing easterlies easterly eastward easygoing eave eaves eavesdrop eavesdropped eavesdropping eavesdrops ebb ebbed ebbing ebbs ebonies ebony eccentricities eccentricity eccentrics ecclesiastical eclair eclairs eclectic eclipse eclipsed eclipses eclipsing ecologically ecologist ecologists economist economists ecosystem ecosystems ecstasies ecstasy ecstatic ecumenical eczema eddied eddies eddy eddying edged edger edgewise edgier edgiest edging edgy edible edibles edict edicts edifice edifices editorials editorship educations educator educators eel eels eerie eerier eeriest effected effecting effectual effeminate effervescent efficients effigies effigy effortless effortlessly effusive effusively egalitarian egged egging eggplant eggplants egocentric egoism egotism egotist egotists eigenvalue eighteens eighteenth eighteenths eighths eighties eightieth eightieths eights eighty ejaculate ejaculated ejaculates ejaculating ejaculation ejaculations eject ejected ejecting ejection ejections ejects eke eked ekes eking elaborated elaborately elaborates elaborating elaboration elaborations elapse elapsed elapses elapsing elastic elasticity elastics elation elbow elbowed elbowing elbows elder elders eldest elective electives elector electorates electors electrically electrician electricians electrified electrifies electrify electrifying electrocute electrocuted electrocutes electrocuting electrocution electrocutions electrode electrodes electrolysis electromagnetic electrons electrostatic elegance elegantly elegies elegy elemental elevate elevated elevates elevating elevation elevations elevens eleventh elevenths elf elicit elicited eliciting elicits eligibility elimination eliminations elites elitism elk elks ellipse ellipses ellipsis elliptic elliptical elm elms elongate elongated elongates elongating elope eloped elopement elopements elopes eloping eloquence eloquent eloquently elucidate elude eluded eludes eluding elusive elves email emailed emailing emails emanate emanated emanates emanating emancipate emancipated emancipates emancipating emancipation embalm embalmed embalming embalms embankment embankments embargo embargoed embargoes embargoing embark embarked embarking embarks embarrassments embassies embassy embellish embellished embellishes embellishing embellishment embellishments ember embers embezzle embezzled embezzlement embezzles embezzling embitter embittered embittering embitters emblem emblems embodied embodies embodiment embody embodying emboss embossed embosses embossing embrace embraced embraces embracing embroider embroidered embroideries embroidering embroiders embroidery embryo embryonic embryos emerald emeralds emergence emergencies emergent emigrant emigrants emigrate emigrated emigrates emigrating emigration emigrations eminence eminences emir emirs emissaries emissary emission emissions emits emitted emitting emotive empathy emperor emperors emphases emphatic emphatically emphysema empires employments emporium emporiums empower empowered empowering empowers empress empresses emptier emptiest emptiness emulated emulates emulating emulations emulsion emulsions enact enacted enacting enactment enactments enacts enamel enamels encapsulate encapsulated encapsulates encapsulating encase encased encases encasing enchant enchanted enchanting enchantment enchantments enchants encircle encircled encircles encircling enclosure enclosures encompass encompassed encompasses encompassing encore encored encores encoring encouragements encroach encroached encroaches encroaching encrypted encryption encumber encumbered encumbering encumbers encumbrance encumbrances encyclopedia encyclopedias endanger endangered endangering endangers endear endeared endearing endearment endearments endears endemic endemics endive endives endorse endorsed endorsement endorsements endorses endorsing endow endowed endowing endowment endowments endows endurance endure endured endures enduring endways enema enemas energetic energetically energetics energies enforcement engagement engagements engender engendered engendering engenders engined engining engrave engraved engraver engravers engraves engraving engravings engross engrossed engrosses engrossing engulf engulfed engulfing engulfs enhancements enigma enigmas enigmatic enjoyments enlargement enlargements enlist enlisted enlisting enlistment enlistments enlists enliven enlivened enlivening enlivens enmities enmity enormities enormity enrage enraged enrages enraging enrich enriched enriches enriching enrichment enrolled enrolling ensemble ensembles enshrine enshrined enshrines enshrining ensign ensigns enslave enslaved enslaves enslaving ensue ensued ensues ensuing entailed entailing entangle entangled entanglement entanglements entangles entangling enterprises enterprising entertainer entertainers entertainments enthralled enthralling enthusiasms enthusiast enthusiastically enthusiasts entice enticed enticement enticements entices enticing entomologist entomologists entomology entrails entranced entrances entrancing entrant entrants entrap entrapped entrapping entraps entreat entreated entreaties entreating entreats entreaty entree entrees entrench entrenched entrenches entrenching entropy entrust entrusted entrusting entrusts entwine entwined entwines entwining enumerate enumerated enumerates enumerating enumeration enunciate enunciated enunciates enunciating enunciation envelop enveloped enveloping envelops enviable envied envies envious enviously environmentally environs envoy envoys envying enzyme enzymes eon eons epaulet epaulets ephemeral epics epidemic epidemics epidermis epidermises epilepsy epileptic epileptics epilogue epilogued epilogues epiloguing epitaph epitaphs epithet epithets epitome epitomes epoch epochs epsilon equanimity equated equates equating equator equatorial equators equestrian equestrians equilateral equilaterals equine equines equinox equinoxes equitable equities equity equivalence equivalently equivocal eradicate eradicated eradicates eradicating eras erasers erasure erect erected erecting erection erections erects ergonomic erode eroded erodes eroding erosion erotic errand errands errant errants erratic erratically erratics erred erring erroneously errs erstwhile erudite erupt erupted erupting eruption eruptions erupts escalate escalated escalates escalating escalation escalator escalators escapade escapades escapism escort escorted escorting escorts especial espionage essayed essaying essences essentials estates esteem esteemed esteeming esteems estimations estrangement estrangements etch etched etches etching etchings eternally eternities ether ethereal ethically ethicals ethnics ethos etiquette etymological etymologies eulogies eulogy euphemism euphemisms eureka euthanasia evacuate evacuated evacuates evacuating evacuation evacuations evade evaded evades evading evaluations evangelical evangelicals evangelism evangelist evangelistic evangelists evaporate evaporated evaporates evaporating evaporation evasion evasions evasive eve evener evenest evenness eventful eventualities eventuality evergreen evergreens everlasting everlastings evermore eves evict evicted evicting eviction evictions evicts evidenced evidences evidencing evidents evocative evoke evoked evokes evoking ewe ewes exacerbate exacerbated exacerbates exacerbating exacted exacter exactest exacting exacts exaggeration exaggerations exalt exaltation exalted exalting exalts examinations examiners exampled exampling exasperate exasperated exasperates exasperating exasperation excavate excavated excavates excavating excavation excavations excel excelled excellence excellently excelling excels excerpt excerpted excerpting excerpts excesses excise excised excises excising excitable excitements exclaim exclaimed exclaiming exclaims exclamations exclusives excommunicate excommunicated excommunicates excommunicating excommunication excommunications excrement excrete excreted excretes excreting excruciating excursion excursions excusable excused excusing executioner executioners executions executives executor executors exemplary exemplified exemplifies exemplify exemplifying exempted exempting exemption exemptions exempts exert exerted exerting exertion exertions exerts exhale exhaled exhales exhaling exhaustion exhibited exhibiting exhibitions exhibits exhilarate exhilarated exhilarates exhilarating exhilaration exhort exhortation exhortations exhorted exhorting exhorts exhume exhumed exhumes exhuming exile exiled exiles exiling existences existent existential existentially exodus exoduses exonerate exonerated exonerates exonerating exoneration exorbitant exotics expandable expanse expanses expansions expansive expatriate expatriated expatriates expatriating expectancy expectant expediencies expediency expedient expedients expedite expedited expedites expediting expeditions expel expelled expelling expels expend expendable expendables expended expending expenditures expends expertly expiration expletive expletives explicable explicits explorations explorer explorers explosives exponent exponentially exponents exported exporter exporters exporting exports exposition expositions exposures expound expounded expounding expounds expressive expressively expressly expulsion expulsions exquisite extemporaneous exterior exteriors exterminate exterminated exterminates exterminating extermination exterminations externals extinct extincted extincting extinctions extincts extinguish extinguished extinguisher extinguishers extinguishes extinguishing extol extolled extolling extols extort extorted extorting extortion extortionate extorts extractions extracurricular extracurriculars extradite extradited extradites extraditing extradition extraditions extraordinaries extrapolate extrapolated extrapolates extrapolating extrapolation extrapolations extraterrestrial extraterrestrials extravagance extravagances extravagant extravagantly extremer extremest extremists extremities extremity extricate extricated extricates extricating extrovert extroverts exuberance exuberant exude exuded exudes exuding exult exultant exultation exulted exulting exults eyeball eyeballed eyeballing eyeballs eyebrow eyebrows eyed eyelash eyelashes eyelid eyelids eyesore eyesores eyewitness eyewitnesses fable fables fabricate fabricated fabricates fabricating fabrication fabrications fabrics fabulous facade facades faceless facet faceted faceting facetious facets facial facials facile facilitated facilitates facilitating facsimile facsimiled facsimileing facsimiles faction factions factored factorial factoring fad fade faded fades fading fads failings fainted fainting faintly faints fairies fairs faithed faithfully faithfulness faithfuls faithing faithless faiths faked fakes faking falcon falconry falcons fallacies fallible fallout falsehood falsehoods falsely falser falsest falsetto falsettos falsification falsifications falsified falsifies falsify falsifying falsities falsity falter faltered faltering falters famed familiars famines fanatic fanatical fanatics fancied fancier fancies fanciest fanciful fancying fanfare fanfares fang fangs fanned fanning fantasied fantastically fantasying faraway farces fared fares farewells faring farmed farming farmland farms fascination fascinations fascism fascists fashionably fasted fasten fastened fastener fasteners fastening fastenings fastens fastidious fasting fasts fatalistic fatalities fatality fatally fated fateful fates fathered fatherhood fathering fatherland fatherlands fatherly fathom fathomed fathoming fathoms fatigue fatigued fatigues fatiguing fating fats fatten fattened fattening fattens fatter fattest fattier fatties fattiest fatty faucets faulted faultier faultiest faulting faultless fauna faunas fawn fawned fawning fawns faze fazed fazes fazing fearful fearfuller fearfullest fearfully fearless fearlessly fearsome feast feasted feasting feasts feather feathered featherier featheriest feathering feathers feathery feats feces federalism federalist federalists federals federation federations feds feebler feeblest feeder feeders feeler feelers feign feigned feigning feigns feint feinted feinting feints feline felines felled feller fellest felling fellowship fellowships fells felon felonies felons felony felted felting felts feminine feminines femininity feminism fen fenced fences fencing fend fended fending fends ferment fermentation fermented fermenting ferments fern ferns ferocious ferociously ferocity ferret ferreted ferreting ferrets ferried ferries ferry ferrying fertile fertility fervent fervently fester festered festering festers festivals festive festivities festivity festoon festooned festooning festoons fetched fetches fetching fete feted fetes fetid feting fetish fetishes fetter fettered fettering fetters feud feudal feudalism feuded feuding feuds feverish feverishly fevers fez fezzes fiance fiancee fiancees fiances fiasco fiascoes fib fibbed fibber fibbers fibbing fibs fiche fickle fickler ficklest fictions fictitious fiddler fiddlers fiddly fidelity fidget fidgeted fidgeting fidgets fidgety fielded fielding fiend fiendish fiendishly fiends fiercely fierceness fiercer fiercest fierier fieriest fiery fiesta fiestas fifteens fifteenth fifteenths fifths fifties fiftieth fiftieths fig figged figging fighters figment figments figs figurative figuratively figurehead figureheads filament filaments filch filched filches filching filler fillet filleted filleting fillets fillies filly filmier filmiest filmy filth filthier filthiest fin finale finales finalist finalists finality financed financier financiers financing finch finches finely finesse finessed finesses finessing fingered fingering fingernail fingernails fingerprint fingerprinted fingerprinting fingerprints fingertip fingertips finickier finickiest finicky finner fins fir firearm firearms firecracker firecrackers firefighter firefighters fireflies firefly fireman firemen fireplace fireplaces fireproof fireproofed fireproofing fireproofs fireside firesides firewood firmed firmer firmest firming firmness firmware firring firs firsthand firsts fiscals fisher fisheries fisherman fishermen fishery fishier fishiest fishy fission fissure fissures fist fists fitful fitness fitter fittest fittings fives fixable fixation fixations fixture fixtures fizz fizzed fizzes fizzing fizzle fizzled fizzles fizzling flabbier flabbiest flabby flagpole flagpoles flagrant flagrantly flagship flagships flagstone flagstones flail flailed flailing flails flair flairs flak flake flaked flakes flakier flakiest flaking flaky flamboyance flamboyant flamboyantly flamed flaming flamingo flamingos flammable flammables flank flanked flanking flanks flannel flannels flap flapjack flapjacks flapped flapping flaps flare flared flares flaring flashback flashbacks flasher flashest flashier flashiest flashlight flashlights flashy flask flasks flatly flatness flats flatted flatten flattened flattening flattens flatter flattered flatterer flatterers flattering flatters flattery flattest flatting flaunt flaunted flaunting flaunts flawless flawlessly flea fleas fleck flecked flecking flecks fled fledged fledgling fledglings flee fleece fleeced fleeces fleecier fleeciest fleecing fleecy fleeing flees fleeted fleeter fleetest fleeting fleets fleshed fleshes fleshier fleshiest fleshing fleshy flex flexed flexes flexibly flexing flick flicked flicker flickered flickering flickers flicking flicks flier fliers fliest flightier flightiest flightless flights flighty flimsier flimsiest flimsiness flimsy flinch flinched flinches flinching fling flinging flings flint flints flippant flipper flippers flippest flirt flirtation flirtations flirtatious flirted flirting flirts flit flits flitted flitting flock flocked flocking flocks flog flogged flogging flogs flooder floodlight floodlighted floodlighting floodlights floored flooring flop flopped floppier floppies floppiest flopping flops flora floral floras florid florist florists floss flossed flosses flossing flotilla flotillas flounce flounced flounces flouncing flounder floundered floundering flounders floured flouring flourish flourished flourishes flourishing flours flout flouted flouting flouts flowered flowerier floweriest flowering flowery flu fluctuate fluctuated fluctuates fluctuating flue fluency fluently fluents flues fluff fluffed fluffier fluffiest fluffing fluffs fluids fluke fluked flukes fluking flung flunk flunked flunkies flunking flunks flunky fluorescent flurried flurries flurry flurrying flusher flushest fluster flustered flustering flusters fluted flutes fluting flutist flutists flutter fluttered fluttering flutters flux fluxed fluxes fluxing flyover flyovers foal foaled foaling foals foamed foamier foamiest foaming foams foamy focal focused focuses focusing fodder fodders foe foes fogged foggier foggiest fogging foggy foghorn foghorns fogs foible foibles foil foiled foiling foils foist foisted foisting foists foliage folklore folksier folksiest folksy follies followings folly foment fomented fomenting foments fonded fonder fondest fonding fondle fondled fondles fondling fondly fondness fonds foodstuff foodstuffs foolhardier foolhardiest foolhardy foolisher foolishest foolishly foolishness foolproof footage footballs footed foothill foothills foothold footholds footing footings footlights footnoted footnoting footpath footpaths footprint footprints foots footstep footsteps footstool footstools footwear footwork forage foraged forages foraging foray forayed foraying forays forbear forbearance forbearing forbears forbiddings forbore forborne forceful forcefully forceps forcible ford forded fording fords fore forearm forearmed forearming forearms forebode foreboded forebodes foreboding forebodings forefather forefathers forefinger forefingers forefront forefronts foregoing foregoings foregone foreground foregrounded foregrounding foregrounds forehead foreheads foreleg forelegs foreman foremen foremost forensic forensics foreplay forerunner forerunners fores foresaw foresee foreseeing foreseen foresees foreshadow foreshadowed foreshadowing foreshadows foresight foreskin foreskins forestall forestalled forestalling forestalls forested foresting forestry foretaste foretasted foretastes foretasting foretell foretelling foretells forethought foretold forewarn forewarned forewarning forewarns forewent foreword forewords forfeit forfeited forfeiting forfeits forge forged forger forgeries forgers forgery forges forgetful forgetfulness forging forgiveness forgo forgoes forgoing forgone forked forking forks forlorn forlorner forlornest formalities formality formals formations formative formidable formless formulate formulated formulates formulating formulations fornication forsake forsaken forsakes forsaking forsook forswear forswearing forswears forswore forsworn fort forte fortes forthright forthwith forties fortieth fortieths fortification fortifications fortified fortifies fortify fortifying fortitude fortnightly fortress fortressed fortresses fortressing forts fortuitous fortunes forums forwarder forwardest forwent fossils foster fostered fostering fosters fouled fouler foulest fouling fouls founder foundered foundering founders foundling foundries foundry fount fountained fountaining fountains founts fours fourteens fourteenth fourteenths fourths fowl fowled fowling fowls fox foxed foxes foxier foxiest foxing foxy foyer foyers fracas fracases fractal fractional fracture fractured fractures fracturing fragility fragmentary fragmentation fragmented fragmenting fragrance fragrances fragrant frail frailer frailest frailties frailty framed frameworks framing franc franchise franchised franchises franchising francs franked franker frankest frankfurter frankfurters franking franks frantically fraternal fraternities fraternity frauds fraudulent fraudulently fraught fraughted fraughting fraughts fray frayed fraying frays freaked freaking freckle freckled freckles freckling freedoms freehand freelance freer freest freezer freezers freight freighted freighter freighters freighting freights frenzied frenzies frenzy frequented frequenter frequentest frequenting frequents freshen freshened freshening freshens fresher freshest freshly freshman freshmen freshness freshwater fret fretful fretfully frets fretted fretting friar friars friendlier friendlies friendliest friendliness friendships frieze friezed friezes friezing frigate frigates fright frighted frighteningly frightful frightfully frighting frights frigid frigidity frill frillier frillies frilliest frills frilly fringed fringes fringing frisk frisked friskier friskiest frisking frisks frisky fritter frittered frittering fritters frivolities frivolity frizzier frizziest frizzy fro frock frocks frolic frolicked frolicking frolics frond fronds frontage frontages frontal fronted frontier frontiers fronting fronts frost frostbit frostbite frostbites frostbiting frostbitten frosted frostier frostiest frosting frosts frosty froth frothed frothier frothiest frothing froths frothy frugal frugality frugally fruited fruitful fruitfuller fruitfullest fruitier fruitiest fruiting fruition fruitless fruitlessly fruity frustrations fudged fudges fudging fuels fugitive fugitives fulcrum fulcrums fulled fulling fullness fulls fumble fumbled fumbles fumbling fumed fumigate fumigated fumigates fumigating fumigation fuming functionally fundamentalism fundamentalists fundamentals funerals fungi fungicide fungicides fungus funnel funnels funner funnest funnies funnily furies furious furiously furl furled furling furlong furlongs furlough furloughed furloughing furloughs furls furnace furnaces furnish furnished furnishes furnishing furnishings furor furors furred furrier furriest furring furrow furrowed furrowing furrows furs furthered furthering furthers furtive furtively furtiveness fury fused fuselage fuselages fuses fusing fussed fusses fussier fussiest fussing futility futures futuristic fuzz fuzzed fuzzes fuzzier fuzziest fuzzing gab gabbed gabbing gable gabled gables gabling gabs gadget gadgets gag gagged gagging gags gaiety gaily gainful gait gaits gal gala galas galaxies gale gales gall gallant gallantry gallants galled galleried galleries gallery gallerying galley galleys galling gallivant gallivanted gallivanting gallivants gallon gallons gallop galloped galloping gallops gallows galls galore galores gals gambit gambits gamble gambled gambler gamblers gambles gambling gamed gamer gamest gaming gamma gamut gamuts gander ganders ganged ganging gangling gangplank gangplanks gangrene gangrened gangrenes gangrening gangs gangster gangsters gangway gangways gaol gape gaped gapes gaping garaged garages garaging garb garbed garbing garbs gardened gardener gardeners gardenia gardenias gardening gargle gargled gargles gargling gargoyle gargoyles garish garland garlanded garlanding garlands garlic garlicked garlicking garlics garment garments garnet garnets garnish garnished garnishes garnishing garret garrets garrison garrisoned garrisoning garrisons garrulous garter garters gaseous gases gash gashed gashes gashing gasket gaskets gasped gasping gasps gassed gassing gastric gated gateways gatherings gating gaudier gaudiest gaudy gaunt gaunted gaunter gauntest gaunting gauntlet gauntlets gaunts gauze gavel gavels gawk gawked gawkier gawkies gawkiest gawking gawks gawky gayer gayest gays gaze gazed gazelle gazelles gazes gazette gazetted gazettes gazetting gazing gee geed geeing gees geese gel gelatin geld gelded gelding geldings gelds gem gems genders genealogical genealogies genealogy genera generality generals generics generosities generosity generously geneses genesis geneticist geneticists genial genially genie genies genii genital genitals geniuses genres gent gentile gentiles gentility gentled gentleness gentler gentles gentlest gentling gentries gentry gents genuineness genus geographic geographically geographies geological geologies geologist geologists geometric geometries geranium geraniums gerbil gerbils germ germicide germicides germinate germinated germinates germinating germination germs gestation gesticulate gesticulated gesticulates gesticulating gestured gestures gesturing getaway getaways geyser geysers ghastlier ghastliest ghetto ghettos ghosted ghosting ghostlier ghostliest ghostly ghosts ghoul ghouls giants gibber gibbered gibbering gibbers gibe gibed gibes gibing giddier giddiest giddiness giddy gifted gifting gigantic gigged gigging giggle giggled giggles giggling gigs gild gilded gilding gilds gill gills gilt gilts gimme gimmick gimmicks ginger gingerbread gingerly gingham ginned ginning gins giraffe giraffes girder girders girdle girdled girdles girdling girlfriends girlhood girlhoods girlish girth girths gist givens gizzard gizzards glacial glacier glaciers gladden gladdened gladdening gladdens gladder gladdest glade glades gladiator gladiators gladlier gladliest glads glamorous glanced glances glancing gland glands glandular glare glared glares glaring glassed glassier glassiest glassing glassware glassy glaze glazed glazes glazing gleam gleamed gleaming gleams glee glen glens glib glibber glibbest glibly glide glided glider gliders glides gliding glimmer glimmered glimmering glimmers glimpse glimpsed glimpses glimpsing glint glinted glinting glints glisten glistened glistening glistens glitter glittered glittering glitters gloat gloated gloating gloats globe globes globular globule globules gloom gloomier gloomiest gloomy gloried glories glorification glorified glorifies glorify glorifying gloriously glorying gloss glossaries glossary glossed glosses glossier glossies glossiest glossing gloved gloving glower glowered glowering glowers glucose glued glues gluing glum glummer glummest glums glut gluts glutted glutting glutton gluttons gluttony glycerin gnarl gnarled gnarling gnarls gnash gnashed gnashes gnashing gnat gnats gnaw gnawed gnawing gnaws gnomes gnu gnus goad goaded goading goads goaled goalie goalies goaling goalkeeper goalkeepers goatee goatees goats gob gobbed gobbing gobble gobbled gobbles gobbling goblet goblets goblin goblins gobs godchild godchildren goddess goddesses godfather godfathers godless godlier godliest godlike godly godmother godmothers godparent godparents godsend godsends goggle goggles goldener goldenest golder goldest golds goldsmith goldsmiths golfed golfer golfers golfing golfs gondola gondolas goner goners gong gonged gonging gongs gonna goo goodnight goodwill gooey goof goofed goofier goofiest goofing goofs goofy gooier gooiest goon goons goose goosed gooses goosing gopher gophers gore gored gores gorge gorged gorges gorging gorier goriest gorilla gorillas goring gory gos gosh gosling gospels gossamer gossips gouge gouged gouges gouging goulash goulashes gourd gourds gourmet gourmets gout governess governesses governmental governors gowned gowning gowns grabber graced graceful gracefuller gracefullest gracefully graceless graces gracing gracious graciously graciousness gradation gradations graded grader gradient gradients grading graduations graft grafted grafting grafts grains gram grammars grammatically gramophone grams grandchild grandchildren granddaughter granddaughters grander grandest grandeur grandfathered grandfathering grandfathers grandiose grandly grandmothers grandparent grandparents grandson grandsons grandstand grandstanded grandstanding grandstands granite grannies granny granola granular granule granules grape graped grapefruit grapefruits grapes grapevine grapevines graphed graphically graphing graphite graping grapple grappled grapples grappling grasped grasping grasps grassed grasses grasshopper grasshoppers grassier grassiest grassing grassy grate grated gratefuller gratefullest grater graters grates gratification gratifications gratified gratifies gratify gratifying grating gratings gratitude gratuities gratuity graved gravel gravels gravely graven graver graves gravest gravestone gravestones graveyard graveyards gravies graving gravitate gravitated gravitates gravitating gravitation gravy graze grazed grazes grazing grease greased greases greasier greasiest greasing greatness greats greedier greediest greedily greediness greenback greenbacks greened greener greenery greenest greenhorn greenhorns greenhouse greenhouses greening greens greet greeted greeting greetings greets gregarious gremlin gremlins grenade grenades greyhound greyhounds gridded griddle griddles griding gridiron gridirons grids griefs grievance grievances grieve grieved grieves grieving grievous grill grille grilled grilles grilling grills grimace grimaced grimaces grimacing grime grimed grimes grimier grimiest griming grimly grimmer grimmest grimy grin grinder grinders grindstone grindstones grinned grinning grins gripe griped gripes griping gripped gripping grislier grisliest grisly gristle grit grits gritted grittier grittiest gritting gritty grizzled grizzlier grizzlies grizzliest grizzly groaned groaning groans grocer groceries grocers grocery groggier groggiest groggy groin groins groom groomed grooming grooms groove grooved grooves groovier grooviest grooving groovy grope groped gropes groping grossed grosser grossest grossing grotesque grotesques grotto grottoes grouch grouched grouches grouchier grouchiest grouching grouchy grounded grounding groundless groundwork grouper groupers groupings grouse groused grouses grousing grove grovel grovels groves grower growers growl growled growling growls growths grub grubbed grubbier grubbiest grubbing grubby grubs grudge grudged grudges grudging gruel gruels gruesome gruesomer gruesomest gruff gruffed gruffer gruffest gruffing gruffly gruffs grumble grumbled grumbles grumbling grumpier grumpiest grumpy grunt grunted grunting grunts guarantor guarantors guardian guardians gubernatorial guerrilla guerrillas guessable guesswork guested guesting guffaw guffawed guffawing guffaws guidebook guidebooks guild guilds guile guiled guiles guiling guillotine guillotined guillotines guillotining guiltier guiltiest guiltily guiltless guise guises guitarist guitars gulch gulches gulfs gull gulled gullet gullets gullies gulling gulls gully gulp gulped gulping gulps gumdrop gumdrops gummed gummier gummiest gumming gummy gumption gums gunfire gunman gunmen gunned gunner gunners gunning gunpowder gunshot gunshots guppies guppy gurgle gurgled gurgles gurgling guru gurus gush gushed gusher gushers gushes gushing gust gusted gustier gustiest gusting gusts gusty gutted guttered guttering gutters gutting guyed guying guzzle guzzled guzzles guzzling gym gymnasium gymnasiums gymnast gymnastics gymnasts gyms gyrate gyrated gyrates gyrating gyration gyrations gyroscope gyroscopes habitable habitat habitation habitations habitats habitual habitually habituals hackney hackneyed hackneying hackneys hacksaw hacksawed hacksawing hacksaws haddock haddocks haded hades hading hag haggard hagged hagging haggle haggled haggles haggling hags hailed hailing hails hailstone hailstones haircuts haircutting hairdo hairdos hairdresser hairdressers haired hairier hairiest hairline hairlines hale haled haler hales halest halfway halibut halibuts haling hallelujah hallelujahs hallmark hallmarked hallmarking hallmarks hallucination hallucinations hallway hallways halo haloed haloing halon halos halter haltered haltering halters halved halving hamburger hamburgers hamlet hamlets hammed hammered hammering hammers hamming hammock hammocks hamper hampered hampering hampers hams hamster hamsters hamstring hamstringing hamstrings hamstrung handbag handbagged handbagging handbags handbooks handcuff handcuffed handcuffing handcuffs handedness handfuls handicapped handicapping handicaps handicraft handicrafts handier handiest handiwork handkerchief handkerchiefs handlebar handlebars handlers handmade handout handouts handrail handrails handshake handsome handsomer handsomest handwriting hangar hangars hanger hangers hangings hangout hangouts hangovers hanker hankered hankering hankers haphazard hapless happenings harangue harangued harangues haranguing harass harassed harasses harassing harassment hardier hardiest hardliner hardliners hardships hardwood hardwoods hare harebrained hared harem harems hares haring hark harked harking harks harlot harlots harmed harmfully harming harmlessly harmonic harmonica harmonicas harmonies harmonious harms harness harnessed harnesses harnessing harp harped harping harpist harpists harpoon harpooned harpooning harpoons harps harpsichord harpsichords harried harries harrow harrowed harrowing harrows harry harrying harsher harshest harshly harshness hart harts harvest harvested harvester harvesters harvesting harvests hashed hashes hashing hassled hassles hassling haste hasted hastened hastening hastens hastes hastier hastiest hastily hasting hatch hatched hatches hatchet hatchets hatching hateful hatefully hatreds hatted hatting haughtier haughtiest haughtily haughtiness haughty haul hauled hauling hauls haunt haunted haunting haunts haven havens haves hawk hawked hawking hawks hayed haying hays haystack haystacks haywire hazarded hazarding hazardous haze hazed hazel hazels hazes hazier haziest hazing headaches headfirst headier headiest headings headland headlands headlight headlights headlined headlining headlong headmaster headphone headphones headquarter headquarters headrest headrests headroom headstone headstones headstrong headway heady heal healed healer healers healing heals healthful healthier healthiest heaped heaping heaps hearings hearsay hearse hearsed hearses hearsing heartache heartaches heartbeat heartbeats heartbreak heartbreaking heartbreaks heartbroke heartbroken heartburn hearted hearten heartened heartening heartens heartfelt hearth hearths heartier hearties heartiest hearting heartless hearty heatedly heater heaters heath heathen heathens heather heave heaved heavenlier heavenliest heavenly heaves heavies heaviness heaving heavyweight heavyweights heckle heckled heckler hecklers heckles heckling hectic hectics hedge hedged hedgehog hedgehogs hedges hedging heed heeded heeding heedless heeds heeled heeling heftier heftiest hefty heifer heifers heighten heightened heightening heightens heinous heir heirloom heirlooms heirs helicoptered helicoptering helicopters heliport heliports helium helling hellish hellos hells helm helmeted helmeting helmets helms helper helpers helpfully helpings helplessly hem hemisphere hemispheres hemlock hemlocks hemmed hemming hemophilia hemorrhage hemorrhaged hemorrhages hemorrhaging hemp hems hen hences henchman henchmen hens hepatitis herald heralded heralding heralds herb herbivorous herbs herded herding herds hereabouts hereafter hereafters hereditary heredity herein heresies heretic heretical heretics herewith heritages hermaphrodite hermit hermits hernia hernias heroine heroins heroism heron herons herpes hers hes hesitancy hesitant hesitated hesitates hesitating hesitation hesitations heterogeneous heterosexuality heterosexuals heuristic hew hewed hewing hews hexagon hexagonal hexagons heyday heydays hi hiatus hiatuses hibernate hibernated hibernates hibernating hibernation hick hickories hickory hicks hideaway hideaways hierarchies hieroglyphic hieroglyphics highbrow highbrows highland highlands highs hijack hijacked hijacking hijacks hike hiked hiker hikers hikes hiking hilarity hillbillies hillbilly hillier hilliest hillside hillsides hilly hilt hilts hims hind hinder hindered hindering hinders hindrance hindrances hinds hinge hinged hinges hinging hinterland hinterlands hipped hipper hippest hippie hippier hippies hippiest hipping hippopotamus hippopotamuses hips hiss hissed hisses hissing histogram histories hitch hitched hitches hitchhike hitchhiked hitchhiker hitchhikers hitchhikes hitchhiking hitching hither hive hived hives hiving hoard hoarded hoarder hoarders hoarding hoards hoarse hoarseness hoarser hoarsest hoax hoaxed hoaxes hoaxing hobbies hobbit hobble hobbled hobbles hobbling hobbyhorse hobbyhorses hobgoblin hobgoblins hobnob hobnobbed hobnobbing hobnobs hobo hoboed hoboing hobos hock hocked hockey hocking hocks hodgepodge hodgepodges hoe hoed hoeing hoes hogged hogging hogs hoist hoisted hoisting hoists holdup holdups holed holidayed holidaying holier holiest holiness holing holler hollered hollering hollers hollies hollowed hollower hollowest hollowing hollows holly holocaust holocausts holster holstered holstering holsters homage homaged homages homaging homed homeland homelands homeless homelier homeliest homely homemade homesick homesickness homespun homestead homesteaded homesteading homesteads homeward homework homey homeys homicidal homicide homicides homier homiest homing homogeneous homonym homonyms homophobic homosexuals hone honed honer hones honester honestest honeycomb honeycombed honeycombing honeycombs honeyed honeying honeymoon honeymooned honeymooning honeymoons honeys honeysuckle honeysuckles honing honk honked honking honks honoraries hood hooded hooding hoodlum hoodlums hoods hoodwink hoodwinked hoodwinking hoodwinks hoof hoofed hoofing hoofs hoop hooped hooping hoops hooray hoorayed hooraying hoorays hoot hooted hooter hooting hoots hooves hop hopefuls hopped hopper hopping hops hopscotch hopscotched hopscotches hopscotching horded hording horizons horizontals hormone hormones horned hornet hornets hornier horniest horns horny horoscope horoscopes horribles horrors horseback horsed horseman horseplay horsepower horseradish horseradishes horseshoe horseshoed horseshoeing horseshoes horsing horticultural horticulture hose hosed hoses hosiery hosing hospitable hospitality hostage hostages hosted hostel hosteled hosteling hostels hostess hostessed hostesses hostessing hostiles hostility hosting hotbed hotbeds hotels hothead hotheaded hotheads hotly hotter hottest hound hounded hounding hounds hourglass hourglasses hourlies hourly houseboat houseboats households housekeeper housekeepers housewarming housewarmings housewife housewives housework housings hove hovel hovels hover hovered hovering hovers howl howled howling howls hows hub hubbub hubbubs hubs huddle huddled huddles huddling hue hued hues huff huffed huffier huffiest huffing huffs huffy hug huger hugest hugged hugger hugging hugs hulk hulking hulks hull hullabaloo hullabaloos hulled hulling hulls humanely humaner humanest humanism humanist humanitarian humanitarians humanities humanly humbled humbler humbles humblest humbling humbug humdrum humid humidified humidifies humidify humidifying humidity humiliate humiliated humiliates humiliating humiliation humiliations humility hummed humming hummingbird hummingbirds humorist humorists humorously hump humped humping humps hums hunch hunchback hunchbacks hunched hunches hunching hundredth hundredths hunger hungered hungering hungers hungrier hungriest hungrily hunk hunks hunter hunters hurdle hurdled hurdles hurdling hurl hurled hurling hurls hurricane hurricanes hurried hurriedly hurries hurrying hurtful hurtle hurtled hurtles hurtling husbanded husbanding husbands hush hushed hushes hushing husk husked huskier huskies huskiest huskily huskiness husking husks husky hustle hustled hustler hustlers hustles hustling hutch hutched hutches hutching huts hyacinth hyacinths hybrid hybrids hydrant hydrants hydraulic hydraulicked hydraulicking hydraulics hydroelectric hydroplane hydroplaned hydroplanes hydroplaning hyena hyenas hygiene hygienic hygienics hymn hymnal hymnals hymned hymning hymns hyperbole hypertension hyphenate hyphenated hyphenates hyphenating hyphenation hyphened hyphening hyphens hypnosis hypnotic hypnotics hypnotism hypnotist hypnotists hypochondria hypochondriac hypochondriacs hypocrisies hypocrites hypotenuse hypotenuses hypotheses hysteria hysteric hysterically hysterics iceberg icebergs icebreaker icebreakers iced ices icicle icicles icier iciest icing icings icy idealist idealists identifiable identities ideologically ideologies idiocies idiocy idiomatic idioms idiosyncrasies idiosyncrasy idled idler idles idlest idling idly idol idols idyllic ifs igloo igloos ignite ignited ignites igniting ignition ignitions ignorants iguana iguanas ilk illegals illegible illegibly illegitimate illicit illiteracy illiterates illnesses ills illuminate illuminated illuminates illuminating illumination illuminations illusions illusory illustrative illustrator illustrators illustrious imaged imagery imaginable imaginations imaging imbalances imbecile imbeciles imitate imitated imitates imitating imitation imitations imitative imitator imitators immaculate immaculately immaterial immatures immaturity immeasurable immeasurably immenser immensest immensities immensity immerse immersed immerses immersing immersion immersions immigrant immigrants immigrate immigrated immigrates immigrating immigration imminently immobile immoralities immorality immortality immortals immovable immunity imp impacted impacting impacts impairment impairments impale impaled impales impaling impart imparted impartial impartiality impartially imparting imparts impassable impasse impasses impassioned impassive impatience impatiences impatient impatiently impeach impeached impeaches impeaching impeccable impeccables impedance impede impeded impedes impediment impediments impeding impel impelled impelling impels impenetrable imperatives imperceptible imperceptibly imperfection imperfections imperfectly imperfects imperialism imperialist imperials imperil imperils impersonally impersonate impersonated impersonates impersonating impersonation impersonations impertinence impertinent impertinents impervious impetuous impetuously impetus impetuses impinge impinged impinges impinging impish implacable implant implanted implanting implants implementable implementer implicate implicated implicates implicating implore implored implores imploring impolite importation importations imposition impositions impossibilities impossibility impossibles impossibly impostor impostors impotence impotent impound impounded impounding impounds impoverish impoverished impoverishes impoverishing imprecise impregnable impregnate impregnated impregnates impregnating impressionable impressively imprint imprinted imprinting imprints imprisonment imprisonments improbabilities improbability improbably impromptu impromptus improper improperly improprieties impropriety improvisation improvisations improvise improvised improvises improvising imps impudence impudent impulsed impulses impulsing impulsive impulsively impunity impure impurer impurest impurities impurity inabilities inaction inactive inactivity inadequacies inadequacy inadequately inadequates inadmissible inadvertent inadvisable inalienable inaner inanest inanimate inapplicable inarticulate inarticulates inasmuch inaudible inaugural inaugurals inaugurate inaugurated inaugurates inaugurating inauguration inaugurations inauspicious inborn inbred inbreds inbreed inbreeding inbreeds inbuilt incalculable incandescence incandescent incandescents incantation incantations incapacitate incapacitated incapacitates incapacitating incapacity incarcerate incarcerated incarcerates incarcerating incarceration incarcerations incarnate incarnated incarnates incarnating incarnations incendiaries incendiary incense incensed incenses incensing incentives inception inceptions incessant incessantly incest incestuous inched inching incidences incidentals incinerate incinerated incinerates incinerating incinerator incinerators incision incisions incisive incisor incisors incite incited incitement incitements incites inciting inclinations inclusions incognito incognitos incoherence incoherently incomes incomparable incompatibilities incompatibility incompatibles incompatibly incompetents inconceivable inconclusive incongruities incongruity incongruous inconsequential inconsiderable inconsiderate inconsolable inconspicuous inconveniently incorporation incorrigible incredulity incredulous incremental incremented incrementing increments incriminate incriminated incriminates incriminating incubate incubated incubates incubating incubation incubator incubators incumbent incumbents incurable incurables indebted indecencies indecency indecent indecenter indecentest indecision indecisive indeeds indefinable indefinites indelible indelibly indelicate indentation indentations indented indenting indents independents indescribable indescribables indestructible indicatives indict indicted indicting indictments indicts indifference indifferent indigenous indigestible indigestibles indigestion indignant indignantly indignation indignities indignity indigo indiscreet indiscretion indiscretions indiscriminate indiscriminately indispensable indispensables indisposed indisputable indistinct individualism individualist individualists individuality indivisible indoctrinate indoctrinated indoctrinates indoctrinating indoctrination indolence indolent indomitable indoor indoors inducement inducements induct inducted inducting inductions inducts indulgence indulgences indulgent industrialist industrialists industrious inedible ineffectual inefficiencies inefficiently inefficients inelegant ineligible ineligibles inept ineptitude inequalities inert inertial inerts inescapable inexact inexcusable inexhaustible inexorable inexorably inexpensive inexperience inexplicable inexplicably inextricably infamies infamy infancy infantries infantry infants infatuation infatuations infections infectious infelicities inferences inferiors inferno infernos inferred inferring infers infertile infest infestation infestations infested infesting infests infidel infidelities infidelity infidels infield infields infiltrate infiltrated infiltrates infiltrating infiltration infinitesimal infinitesimals infinities infinitive infinitives infirm infirmaries infirmary infirmities infirmity infix inflame inflamed inflames inflaming inflammable inflammation inflammations inflammatory inflatable inflate inflated inflates inflating inflationary inflection inflections inflicted inflicting inflicts influenza influx influxes informality informant informants informational informer informers infraction infractions infrared infrequently infringe infringed infringements infringes infringing infuriate infuriated infuriates infuriating infuse infused infuses infusing infusion infusions ingeniously ingenuity ingest ingested ingesting ingests ingrain ingrained ingraining ingrains ingratiate ingratiated ingratiates ingratiating ingratitude inhale inhaled inhaler inhalers inhales inhaling inheritances inhibitions inhospitable inhuman inhumane inhumanities inhumanity initiation initiations initiatives initiator initiators injected injecting injection injections injects injunction injunctions injurious injustices inked inkier inkiest inking inkling inks inky inlaid inland inlay inlaying inlays inlet inlets inmate inmates inn innards innate inned innermost inners inning innings innkeeper innkeepers innocenter innocentest innocently innocents innocuous innovations inns innuendo innuendoed innuendoing innuendos innumerable inoculate inoculated inoculates inoculating inoculation inoculations inoffensive inoperative inopportune inordinate inquest inquests inquisition inquisitions inquisitive ins insanely insaner insanest insanity insatiable inscribe inscribed inscribes inscribing inscription inscriptions inscrutable insecticide insecticides insecurities insecurity insensitivity inseparable inseparables insertions insider insiders insides insights insignia insignias insignificance insincere insincerely insincerity insinuate insinuated insinuates insinuating insinuation insinuations insipid insistent insolence insolent insoluble insolubles insolvency insolvent insolvents insomnia inspections inspector inspectors inspirations instability instanced instancing instantaneous instantaneously instants instep insteps instigate instigated instigates instigating instigation instill instilled instilling instills instinctive instincts instituted institutes instituting institutional instructive instructor instructors instrumentals instrumented instrumenting insubordinate insubordination insubstantial insufferable insufficiently insular insulate insulated insulates insulating insulation insulator insulators insulin insurances insure insured insurer insurers insures insurgent insurgents insuring insurmountable insurrection insurrections intakes intangible intangibles integrals intellects intellectually intellectuals intelligently intelligible intelligibly intenser intensest intensified intensifies intensify intensifying intensities intensives intents intercede interceded intercedes interceding intercept intercepted intercepting interception interceptions intercepts interchange interchangeable interchanged interchanges interchanging intercom intercoms interconnect intercontinental interdependence interdependent interiors interject interjected interjecting interjection interjections interjects interlock interlocked interlocking interlocks interloper interlopers interlude interluded interludes interluding intermarriage intermarriages intermarried intermarries intermarry intermarrying intermediaries intermediary intermediates interment interments interminable interminably intermingle intermingled intermingles intermingling intermission intermissions intermittently intern internationally internationals interned interning interns interplanetary interplay interpolation interpose interposed interposes interposing interpreters interracial interred interring interrogated interrogates interrogating interrogation interrogations interrogator interrogators inters intersect intersected intersecting intersects intersperse interspersed intersperses interspersing interstate interstates interstellar intertwine intertwined intertwines intertwining interventions interviewer interviewers interweave interweaves interweaving interwove interwoven intestinal intestine intestines inti intimacies intimacy intimated intimately intimates intimating intimation intimations intimidate intimidated intimidates intimidating intimidation intolerable intolerably intolerant intonation intonations intoxicate intoxicated intoxicates intoxicating intoxication intractable intramural intransitive intransitives intravenous intravenouses intrepid intricacies intricacy intricate intrigue intrigued intrigues intriguing introductions introspective introvert introverts intrude intruded intruder intruders intrudes intruding intrusion intrusions intrusive intrusives intuition intuitions intuitively inundate inundated inundates inundating inundation inundations invader invaders invalidated invalidates invalidating invalided invaliding invalids invariable invariables invariant invasions invective inventive inventoried inventories inventors inventory inventorying inversely inverses inversion inversions invertebrate invertebrates invested investigator investigators investing investments investor investors invests inveterate invigorate invigorated invigorates invigorating invincible invisibility invisibly invitations invocation invocations invoice invoiced invoices invoicing involuntarily involuntary involvements invulnerable inward inwardly inwards iodine ions iota iotas irascible irater iratest ire ired ires iridescence iridescent iring iris irises irk irked irking irks ironed ironically ironies ironing irons irradiate irradiated irradiates irradiating irrationally irrationals irreconcilable irrefutable irregular irregularities irregularity irregulars irrelevance irrelevances irreparable irreplaceable irrepressible irreproachable irresistible irresponsibility irretrievable irretrievably irreverence irreverent irreversible irrevocable irrevocably irrigate irrigated irrigates irrigating irrigation irritability irritable irritably irritant irritants irritations islander islanders isle isles isthmus isthmuses italic italics itch itched itches itchier itchiest itching itchy iterate iteration iterations iterative itinerant itinerants itineraries itinerary ivies ivories ivory ivy jab jabbed jabber jabbered jabbering jabbers jabbing jabs jackal jackals jackass jackasses jackdaw jacked jacking jackknife jackknifed jackknifes jackknifing jackknives jackpot jackpots jacks jade jaded jades jading jagged jaggeder jaggedest jaguar jaguars jailed jailer jailers jailing jails jalopies jalopy jamb jambed jambing jamboree jamborees jambs jangle jangled jangles jangling janitor janitors jar jarred jarring jars jaundice jaundiced jaundices jaundicing jaunt jaunted jauntier jaunties jauntiest jauntily jaunting jaunts jaunty javelin javelins jaw jawbone jawboned jawbones jawboning jawed jawing jaws jay jays jaywalk jaywalked jaywalker jaywalkers jaywalking jaywalks jazzed jazzes jazzing jealousies jealously jealousy jeer jeered jeering jeers jell jelled jellied jelling jells jellyfish jellyfishes jellying jeopardy jerked jerkier jerkiest jerking jerks jerky jersey jerseys jested jester jesters jesting jests jets jetted jetties jetting jettison jettisoned jettisoning jettisons jetty jewel jewelries jewelry jewels jiffies jiffy jig jigged jigging jiggle jiggled jiggles jiggling jigs jigsaw jigsawed jigsawing jigsaws jilt jilted jilting jilts jingle jingled jingles jingling jinx jinxed jinxes jinxing jitterier jitteriest jitters jittery jobbed jobbing jockey jockeyed jockeying jockeys jocular jog jogged jogger joggers jogging jogs jointed jointing joker jokers jollied jollier jollies jolliest jollying jolt jolted jolting jolts jostle jostled jostles jostling jot jots jotted jotting journalism journeyed journeying journeys jovial jovially joyed joyful joyfuller joyfullest joyfully joying joyous joyously joys joystick jubilant jubilation jubilee jubilees judicial judicially judiciaries judiciary judicious judiciously judo jug jugged juggernaut jugging juggle juggled juggler jugglers juggles juggling jugs jugular jugulars juiced juices juicier juiciest juicing juicy jumble jumbled jumbles jumbling jumbo jumbos jumper jumpers jumpier jumpiest jumpy junctions juncture junctures jungles juniors juniper junipers junked junket junketed junketing junkets junkie junkier junkies junkiest junking junks junta juntas juries jurisdiction juror jurors juster justest justices justifications justly jut jute juts jutted jutting juveniles juxtapose juxtaposed juxtaposes juxtaposing juxtaposition juxtapositions kaleidoscope kaleidoscopes kangaroo kangarooed kangarooing kangaroos karat karate karats kayak kayaked kayaking kayaks keel keeled keeling keels keened keener keenest keening keenly keens keepers keepsake keepsakes keg kegged kegging kegs kelp kennel kennels kerchief kerchiefed kerchiefing kerchiefs kernels kerosene ketchup kettles keyboarded keyboarding keyhole keyholes keynote keynoted keynotes keynoting keystone keystones khaki khakis kickback kickbacks kickoff kickoffs kidnapper kidnappers kidneys killers killings kiln kilned kilning kilns kilo kilobyte kilobytes kilos kilowatt kilowatts kilt kilts kimono kimonos kin kinda kinder kindergarten kindergartens kindest kindle kindled kindles kindlier kindliest kindling kindnesses kindred kinfolk kingdoms kingfisher kingfishers kink kinked kinkier kinkiest kinking kinks kinky kins kinship kiosk kiosks kipper kissed kisses kissing kitchened kitchenette kitchenettes kitchening kitchens kite kited kites kiting kitten kittens kitties kitty kiwi kiwis knack knacked knacker knacking knacks knapsack knapsacks knead kneaded kneading kneads kneecap kneecapped kneecapping kneecaps kneed kneeing kneel kneeling kneels knelt knickers knifed knifes knifing knighted knighthood knighthoods knighting knights knit knits knitted knitting knives knob knobs knocker knockers knockout knockouts knoll knolls knot knots knotted knottier knottiest knotting knotty knowinger knowingest knowingly knowings knowledgeable knuckle knuckled knuckles knuckling koala koalas kosher koshered koshering koshers kowtow kowtowed kowtowing kowtows kudos laboratories laborious laboriously labyrinth labyrinths lace laced lacerate lacerated lacerates lacerating laceration lacerations laces lacier laciest lacing lacquer lacquered lacquering lacquers lacrosse lacy laddered laddering ladders lade laded laden lades lading ladle ladled ladles ladling lads ladybug ladybugs ladylike laggard laggards lagged lagging lagoon lagoons lags lair lairs laked lakes laking lamb lambda lambed lambing lambs lame lamed lament lamentable lamentation lamentations lamented lamenting laments lamer lames lamest laming lampoon lampooned lampooning lampoons lamps lance lanced lances lancing lander landings landladies landlady landlocked landlords landmark landmarks landowner landowners landscaped landscapes landscaping landslid landslide landslides landsliding lanes languid languish languished languishes languishing languor languorous languors lankier lankiest lanky lantern lanterns lap lapel lapels lapped lapping laps lapse lapsed lapses lapsing larcenies larceny lard larded larding lards larges larked larking larks larva larvae larynges laryngitis larynx lascivious lash lashed lashes lashing lass lasses lastly latch latched latches latching latent latents lateral lateraled lateraling laterals latex lath lathe lathed lather lathered lathering lathers lathes lathing laths latitude latitudes latrine latrines lattice lattices laud laudable lauded lauding lauds laughable laughingstock laughingstocks launcher launchers launder laundered laundering launders laundries laundry laureate laureated laureates laureating laurel laurels lava lavatories lavender lavendered lavendering lavenders lavish lavished lavisher lavishes lavishest lavishing lawful lawless lawmaker lawmakers lawns lawsuit lawsuits lax laxative laxatives laxer laxes laxest laxity layered layering layman laymen layouts lazied lazier lazies laziest lazying leaden leafed leafier leafiest leafing leafleted leafleting leafs leafy leagued leagues leaguing leakage leakages leaked leaking leaks leaky leaner leanest leaped leapfrog leapfrogged leapfrogging leapfrogs leaping leaps lease leased leases leash leashed leashes leashing leasing leathery lectern lecterns ledge ledger ledgered ledgering ledgers ledges lee leech leeched leeches leeching leek leeks leer leered leerier leeriest leering leers leery leeway lefter leftest leftmost lefts legacies legacy legalistic legality legals legends legged legging leggings legibility legibly legion legions legislate legislated legislates legislating legislative legislator legislators legislature legislatures legitimacy legitimated legitimates legitimating legume legumes leisurely lemme lemonade lemoned lemoning lemons lengthen lengthened lengthening lengthens lengthier lengthiest lengthwise leniency lenients lentil lentils leopard leopards leotard leotards leper lepers leprosy lesbians lesion lesions lessen lessened lessening lessens letdown letdowns lethals lethargic lethargy lettered letterhead letterheads lettering lettuce lettuces letup letups levee levees lever leverage leveraged leverages leveraging levered levering levers levied levies levity levy levying lewd lewder lewdest lexical lexicon lexicons liabilities liaisons liar liars libels liberalism liberally liberals liberate liberated liberates liberating liberation libertarian librarians libretto lice lichen lichens lick licked licking licks licorice licorices lids lieu lieutenant lieutenants lifeboat lifeboats lifeforms lifeguard lifeguards lifeless lifelike lifeline lifelines lifelong lifespan lifestyles lifetimes ligament ligaments ligature ligatures lighten lightened lightening lightens lighters lighthouse lighthouses lightness lightweight lightweights likable likelier likeliest likelihoods liken likened likeness likenesses likening likens liker likest lilac lilacs lilies lilt lilted lilting lilts lily limber limbered limberer limberest limbering limbers limbo lime limed limelight limelighted limelighting limelights limerick limericks limes limestone liming limitless limousine limousines limp limped limper limpest limping limps linchpin linchpins lineage lineages linearly linefeed linen liner liners linger lingered lingerie lingering lingers lingo lingoes linguist linguistics linguists liniment liniments linings linker linoleum lint lints lioness lionesses lions lipstick lipsticked lipsticking lipsticks liquefied liquefies liquefy liquefying liqueur liqueured liqueuring liqueurs liquidate liquidated liquidates liquidating liquidation liquidations liquids liquored liquoring liquors lisped lisping lisps listeners listless litanies litany literacy literals literates lithe lither lithest lithium litigation litterbug litterbugs littered littering litters littler littlest liturgical liturgies liturgy livable livelier liveliest livelihood livelihoods liveliness liven livened livening livens livers livestock livid livings lizard lizards llama llamas loadable loaf loafed loafer loafers loafing loafs loam loaned loaning loath loathe loathed loather loathes loathing loathings loathsome loaves lob lobbed lobbied lobbies lobbing lobbying lobbyist lobbyists lobe lobed lobes lobing lobotomy lobs lobster lobstered lobstering lobsters locale localed locales localing localities locality locker lockers locket lockets locksmith locksmiths locomotion locomotive locomotives locust locusts lodged lodger lodgers lodges lodging lodgings loft lofted loftier loftiest loftiness lofting lofts lofty logarithm logarithmic logger logician loin loincloth loincloths loins loiter loitered loiterer loiterers loitering loiters loll lolled lolling lollipop lollipops lolls lone lonelier loneliest loneliness lonesome lonesomes longed longevity longhand longing longings longish longitude longitudes longitudinal longs longshoreman longshoremen lookout lookouts loom loomed looming looms loon loonier loonies looniest loons loony looped loopholes looping loosed loosen loosened loosening loosens looser looses loosest loosing loot looted looting loots lop lope loped lopes loping lopped lopping lops lopsided lorded lording lore loser losers lotion lotions lotteries lottery lotus lotuses loudlier loudliest loudness loudspeaker loudspeakers lounge lounged lounges lounging louse loused louses lousier lousiest lousing lovable lovelier lovelies loveliest loveliness lovingly lovings lowdown lowed lowing lowlier lowliest lowly lows loyaler loyalest loyalties loyalty lozenge lozenges lubricant lubricants lubricate lubricated lubricates lubricating lubrication lucid lucked luckier luckiest lucking lucks lucrative lug lugged lugging lugs lukewarm lull lullabies lullaby lulled lulling lulls lumber lumbered lumbering lumberjack lumberjacks lumbers luminaries luminary luminous lumped lumpier lumpiest lumping lumpy lunacies lunacy lunar lunatics lunched luncheon luncheoned luncheoning luncheons lunches lunching lunge lunged lunges lunging lurch lurched lurches lurching lure lured lures lurid luring luscious lush lusher lushes lushest lusted lustier lustiest lusting lustrous lusts lusty lute lutes luxuriant luxuriate luxuriated luxuriates luxuriating luxuries luxurious lye lymph lymphatic lymphatics lynch lynched lynches lynching lyre lyres lyrical m ma macabre macaroni mace maced maces machete machetes machined machining machinist machinists macho macing mackerel mackerels macroscopic madam madame madams madcap madcaps madden maddened maddening maddens madder maddest madhouse madhouses madly madman madmen maelstrom maelstroms magenta maggot maggots magically magician magicians magicked magicking magics magistrate magistrates magnanimity magnanimous magnanimously magnate magnates magnesium magnet magnetics magnetism magnets magnificence magnified magnifies magnify magnifying magnitudes magnolia magnolias magnum magpie magpies mahoganies mahogany maid maiden maidens maids mailboxes mailman mailmen maim maimed maiming maims mainland mainlands mainline mainstay mainstays maintainability maintainable maintainer maintainers maizes majestic majestically majesties majesty majored majoring majorities majors makeshift makeshifts makeup makeups maladies maladjusted malady malaria malevolence malevolent malformed malice maliced malices malicing maliciously malign malignancies malignancy malignant malignants maligned maligning maligns mall mallard mallards malleable malled mallet mallets malling malls malnutrition malpractice malpractices malt malted malting maltreat maltreated maltreating maltreats malts mama mamas mammal mammalian mammals mammoth mammoths manacle manacled manacles manacling manageable managerial mandated mandates mandating mandible mandibles mandolin mandolins mane manes mange manged manger mangers manges mangier mangiest manging mango mangoes mangrove mangroves mangy manhandle manhandled manhandles manhandling manhole manholes manhood maniac maniacal maniacs manias manic manicure manicured manicures manicuring manicurist manicurists manifest manifestations manifested manifesting manifestoed manifestoing manifestos manifests manifold manifolded manifolding manifolds manipulations manlier manliest manliness manly mannequin mannequins mannerism mannerisms manners mannish manor manors mansion mansions manslaughter mantel mantelpiece mantelpieces mantels mantle mantled mantles mantling manure manured manures manuring manuscript manuscripts maple maples mapper mappings mar marathon marathons marble marbled marbles marbling marched marcher marches marching mare mares margarine marigold marigolds marijuana marina marinas marinate marinated marinates marinating marine mariner mariners marines marionette marionettes maritime markedly marketable marketplace marketplaces markings marksman marksmen marmalade maroon marooned marooning maroons marquee marquees marred marriages marring marrow marrowed marrowing marrows mars marsh marshal marshaled marshaling marshals marshes marshier marshiest marshmallow marshmallows marshy marsupial marsupials mart marted martial martin marting marts martyr martyrdom martyred martyring martyrs marvel marvels mas mascara mascaraed mascaraing mascaras mascot mascots masculine masculines mash mashed mashes mashing masked masking masks masochist masochists mason masonry masons masquerade masqueraded masquerades masquerading massacre massacred massacres massacring massage massaged massages massaging massed massing mast mastered masterful mastering masterly mastermind masterminded masterminding masterminds masterpiece masterpieces mastery masticate masticated masticates masticating masts masturbation mat matador matadors matchbook matchbooks matchless matchmaker matchmakers mated materialism materialist materialistic materialists maternal maternity mates math matinee matinees mating matriarch matriarchal matriarchs matriculate matriculated matriculates matriculating matriculation matrimonial matrimony matron matronly matrons mats matte matted mattered mattering mattes matting mattress mattresses matured maturer matures maturest maturing maturities maturity maudlin maul mauled mauling mauls mausoleum mausoleums mauve maverick mavericked mavericking mavericks maxim maximal maxims maximums maybes mayhem mayonnaise mayors mazes meadow meadows mealed mealier mealies mealiest mealing mealy meander meandered meandering meanders meaner meanest measles measlier measliest measly measurable meats mechanically medal medallion medallions medals meddle meddled meddler meddlers meddles meddlesome meddling median medias mediate mediated mediates mediating mediation mediator mediators medically medicals medicate medicated medicates medicating medication medications medicinal medicinals medicines mediocre mediocrities mediocrity meditate meditated meditates meditating meditation meditations medley medleys meek meeker meekest meekly meekness meeter megalomaniac megaphone megaphoned megaphones megaphoning megaton megatons melancholy mellow mellowed mellower mellowest mellowing mellows melodic melodics melodies melodious melodrama melodramas melodramatic melodramatics melon melons melted melting melts memberships membrane membranes memento mementos memo memoir memoirs memorably memorandum memorandums memorial memorials memos menace menaced menaces menacing menagerie menageries menial menials menopause menstrual menstruate menstruated menstruates menstruating menstruation mentalities menthol mentor mentored mentoring mentors mercantile mercenaries mercenary merchandise merchandised merchandises merchandising merchant merchanted merchanting merchants mercies merciful mercifully merciless mercilessly mered merer meres merest merger mergers meridian meridians mering meringue meringues merited meriting mermaid mermaids merrier merriest merrily merriment mes mesdames mesh meshed meshes meshing messaged messaging messenger messengers messier messiest metabolic metabolism metabolisms metallic metallurgy metals metamorphose metamorphoses metamorphosis metaphorical metaphorically metaphors metaphysical metaphysics mete meted meteor meteoric meteorite meteorites meteorologist meteorologists meteorology meteors metes methodical methodology meticulous meting metropolis metropolises metropolitan mettle mew mewed mewing mews mezzanine mezzanines microbe microbes microbiology microcode microfiche microfilm microfilmed microfilming microfilms microorganism microorganisms microphone microphones microscope microscopes microscopic microsecond microseconds microwaved microwaves microwaving middleman middlemen middles midget midgets midriff midriffs midst midstream midsummer midway midways midwife midwifed midwifes midwifing midwives mien miens mightier mightiest migraine migraines migrant migrants migrations migratory mike miked mikes miking milder mildest mildew mildewed mildewing mildews mileages milestone milestones militancy militant militants militarily militate militated militates militating militia militias milked milker milkier milkiest milking milkman milkmen milks milky milled miller millers milliner milliners millinery milling millionaire millionaires millionth millionths millisecond milliseconds mills mime mimed mimes mimicked mimicking mimicries mimicry mimics miming mince minced mincemeat minces mincing mindbogglingly mindedness mindful mindlessly minefield miner mineral minerals miners mingle mingled mingles mingling miniature miniatured miniatures miniaturing minibus minibuses minicomputer minimalism minimally minimals minimums minion minions ministered ministerial ministering ministries ministry mink minks minnow minnows minored minoring minors minstrel minstrels minted minting mints minuet minuets minuscule minuscules minuses minuted minuter minutest minuting miraculously mirage mirages mire mired mires miring mirrored mirroring mirth misadventure misadventures misapprehension misappropriate misappropriated misappropriates misappropriating misappropriation misappropriations misbehave misbehaved misbehaves misbehaving miscarriage miscarriages miscarried miscarries miscarry miscarrying miscellany mischief mischiefed mischiefing mischiefs mischievous misconception misconceptions misconduct misconducted misconducting misconducts misconstrue misconstrued misconstrues misconstruing misdeed misdeeds misdirection miser miserables miseries miserly misers misfit misfits misfitted misfitting misfortunes misgiving misgivings mishap mishapped mishapping mishaps misinform misinformation misinformed misinforming misinforms misinterpretation misjudge misjudged misjudges misjudging mislaid mislay mislaying mislays mismanagement mismatch mismatched mismatches mismatching misnomer misnomered misnomering misnomers misprinted misprinting misprints misquote misquoted misquotes misquoting misrepresentation misrepresentations misshapen missionaries missionary missioned missioning missions missive missives misspell misspelled misspelling misspellings misspells misted mistier mistiest misting mistletoe mistress mistresses mistrust mistrusted mistrusting mistrusts misty mistype mistyping misunderstandings misused misuses misusing mite mites mitigate mitigated mitigates mitigating mitt mitten mittens mitts mixer mixers mixtures mnemonics moat moated moating moats mobbed mobbing mobiles mobility mobs moccasin moccasins mocked mockeries mockery mocking mockingbird mockingbirds mocks modal moder moderated moderates moderating moderator moderators moderner modernest modernity moderns modester modestest modestly modesty modicum modicums modifier modifiers modular modulate modulated modulates modulating modulation modulations mohair moist moisten moistened moistening moistens moister moistest moisture molar molars molasses moles molest molested molesting molests mollified mollifies mollify mollifying mollusk mollusks molt molted molten molting molts mom momentary momentous moms monarchies monarchs monarchy monasteries monastery monastic monastics monetarism monetary mongoose mongrel mongrels monies monk monkeyed monkeying monks monogamous monogamy monogram monogrammed monogramming monograms monolithic monologue monologued monologues monologuing monopolies monorail monorails monosyllable monosyllables monotonically monotonous monotony monsoon monsoons monstrosities monstrosity monstrous monthlies monument monumental monuments moo moodier moodiest moodily moods moody mooed mooing moonbeam moonbeams mooned mooning moonlight moonlighted moonlighting moonlights moor moored mooring moorings moors moos moose moot mooted mooter mooting moots mop mope moped mopes moping mopped mopping mops morale moralist moralists moralities moralled moralling morass morasses moratorium moratoriums morbid morgue morgues morn morned morns moronic morose morphine morphology morsel morsels mortally mortar mortared mortaring mortars mortgage mortgaged mortgages mortgaging mortification mortified mortifies mortify mortifying mortuaries mortuary mosaic mosaics mosque mosques mosquito mosquitoes moss mosses mossier mossies mossiest mossy motel motels moth mothball mothballed mothballing mothballs mothered motherhood mothering motherly moths motif motifs motioned motioning motionless motivations motley motleys motlier motliest motorbike motorbikes motorcade motorcades motorcycle motorcycled motorcycles motorcycling motored motoring motorist motorists mottoes mound mounded mounding mounds mountaineer mountaineered mountaineering mountaineers mountainous mourn mourned mourner mourners mournful mournfuller mournfullest mourning mourns moused mouses mousier mousiest mousing mousse moussed mousses moussing mousy mouthed mouthful mouthfuls mouthing mouthpiece mouthpieces mouths movable movables mover movers mow mowed mower mowers mowing mows ms mu mucous mucus muddied muddier muddies muddiest muddy muddying muff muffed muffin muffing muffins muffle muffled muffler mufflers muffles muffling muffs mugged mugger muggers muggier muggiest mugginess mugging muggy mulch mulched mulches mulching mule muled mules muling mull mulled mulling mulls multinational multinationals multiplications multiplicative multiplicities multiplicity multiprocessing multitasking multitude multitudes mumbled mumbles mumbling mummies mummified mummifies mummify mummifying mumps mums munch munched munches munching mundanes municipal municipalities municipality municipals mural murals murderers murderous murkier murkiest murky murmur murmured murmuring murmurs muscled muscling muscular muse mused muses mush mushed mushes mushier mushiest mushing mushroom mushroomed mushrooming mushrooms mushy musically musicals musicked musicking musics musing musk musked musket muskets musking musks muss mussed mussel mussels musses mussing mustang mustangs mustard muster mustered mustering musters mustier mustiest musts musty mutant mutants mutate mutated mutates mutating mutation mutations mute muted mutely muter mutes mutest mutilate mutilated mutilates mutilating mutilation mutilations muting mutinied mutinies mutinous mutiny mutinying mutt mutton mutts muzzle muzzled muzzles muzzling myopic myopics myriad myriads mys mysteried mysterying mystical mysticism mystics mystified mystifies mystify mystifying mythological mythologies nab nabbed nabbing nabs nag nagged nagging nags naively naiver naives naivest naivete naivety nakeder nakedest nakedness namesake namesakes nap napalm napalmed napalming napalms nape napes napkin napkins napped nappies napping nappy naps narcotic narcotics narrate narrated narrates narrating narration narrations narratives narrator narrators narrowed narrowing narrowly narrowness narrows nasal nasals nastily nastiness nationalism nationalist nationalistic nationalists nationalities nationality nationals nationwide nativities nativity nattier nattiest natty naturalist naturalists naturalness naturals natured natures naturing naughtier naughties naughtiest naughtily naughtiness nausea nauseate nauseated nauseates nauseating nauseous nautical naval navel navels navies navigable navigate navigated navigates navigating navigation navigator navigators navy nays neared nearing nearlier nearliest nears nearsighted nearsightedness neater neatest neatness nebula nebulae nebulous necessaries necessitate necessitated necessitates necessitating necessities necked neckerchief neckerchiefs necking necklace necklaces neckline necklines necks necktie neckties necrophilia nectar nectarine nectarines nee needier neediest needled needlework needling needy negated negates negating negation negations negatived negatively negatives negativing neglectful negligee negligees negligence negligent negligently negotiator negotiators neigh neighed neighing neighs neon neophyte neophytes nephew nephews nepotism nerved nerving nervously nervousness nestle nestled nestles nestling nether netted netting nettle nettled nettles nettling neurologist neurologists neurology neuron neurons neuroses neurosis neurotic neurotics neuter neutered neutering neuters neutrality neutrals neutron neutrons newbie newbies newborn newborns newed newfangled newing newsagents newscast newscaster newscasters newscasting newscasts newsed newses newsier newsiest newsing newspapered newspapering newsprint newsstand newsstands newsy newt newton newts nibble nibbled nibbles nibbling niceties nicety niche niches nickel nickels nicknamed nicknaming nicotine niece nieces niftier niftiest nifty nigh nightclub nightclubbed nightclubbing nightclubs nightfall nightgown nightgowns nightingale nightingales nightly nightmares nightmarish nighttime nilled nilling nils nimble nimbler nimblest nimbly nincompoop nincompoops nines nineteen nineteens nineteenth nineteenths nineties ninetieth ninetieths ninety ninnies ninny ninth ninths nip nipped nippier nippiest nipping nipple nippled nipples nippling nippy nips nit nitrate nitrated nitrates nitrating nitrogen nits nitwit nitwits nobility nobleman noblemen nobler nobles noblest noblewoman noblewomen nobly nobodies nocturnal nod nodded nodding nods noes noised noiseless noiselessly noisier noisiest noisily noisiness noising nomad nomadic nomads nomenclature nomenclatures nomination nominations nominative nominatives nominee nominees non nonchalance nonchalant nonchalantly noncommittal nonconformist nonconformists nondescript nonentities nonentity nones nonfiction nonflammable nonpartisan nonpartisans nonprofit nonprofits nonresident nonresidents nonsensical nonstandard nonstop nontrivial nonviolence noodle noodled noodles noodling nook nooks nooned nooning noons noose nooses normed norming norms northeast northeasterly northeastern northerlies northerly northward northwest northwestern nosebleed nosebleeds nosed nosing nostalgic nostalgics nostril nostrils notables notations notch notched notches notching notebook notebooks noteworthy nothingness nothings noticeboard noticeboards notifications notional notoriety notoriously nougat nougats nourish nourished nourishes nourishing nourishment nova novelist novelists novelties noxious nozzle nozzles nuance nuances nuclei nucleus nude nuder nudes nudest nudge nudged nudges nudging nudity nugget nuggets nuisances nullified nullifies nullify nullifying nulls numbed numbing numbness numbs numerate numerator numerators numerically nuptial nuptials nursed nursemaid nursemaids nurseries nursery nursing nurture nurtured nurtures nurturing nutcracker nutcrackers nutmeg nutmegged nutmegging nutmegs nutrient nutrients nutriment nutriments nutrition nutritional nutritious nutshell nutshells nutted nuttier nuttiest nutting nutty nuzzle nuzzled nuzzles nuzzling nylon nymph nymphs oaf oafs oak oaks oared oaring oars oases oasis oath oaths oatmeal obedience obedient obediently obelisk obelisks obese obesity obfuscation obituaries obituary objectively objectives objectivity objector objectors obligate obligated obligates obligating obligations oblique obliques obliterate obliterated obliterates obliterating obliteration oblivion oblivious oblong oblongs oboe oboes obscener obscenest obscenities obscenity obscurer obscurest obscurities observable observance observances observant observatories observatory obsessions obsessive obsolescence obsolescent obsoleted obsoletes obsoleting obstacle obstacles obstetrician obstetricians obstetrics obstinacy obstinate obstruction obstructions obstructive obtrusive obtuse obtuser obtusest occasioned occasioning occupancy occupant occupants occupational occupations oceanic oceanography oceans octagon octagonal octagons octal octave octaves octopus octopuses ocular oculars odder oddest oddities oddity ode odes odious odometer odometers offbeat offbeats offed offensiveness offensives officiate officiated officiates officiating officious offing offings offload offs offshoot offshoots offshore offstage offstages oftener oftenest ogle ogled ogles ogling ogre ogres ohm ohms ohs oiled oilier oiliest oiling oils oily ointment ointments okay okays okra okras olden oldened oldening oldens olfactory olive olives omega omelet omelets omen omens ominous ominously omnibus omnipotence omnipotent omnipresent omniscient oncoming onerous onioned onioning onions onliest onlooker onlookers onomatopoeia onrush onrushes onset onsets onsetting onslaught onslaughts onuses onward oodles ooze oozed oozes oozing opal opals opaque opaqued opaquer opaques opaquest opaquing opener openers openest openings openness operand operands operatic operatics operative operatives ophthalmologist ophthalmologists ophthalmology opinionated opium opossum opossums opportune opportunist opportunists opposites oppressive oppressor oppressors optician opticians optics optima optimism optimist optimists optimums optionals optioned optioning optometrist optometrists opulent oracle oracled oracles oracling orals oranges orangutan orangutans oration orations orator oratories orators oratory orbitals orbited orbiting orbits orchard orchards orchestras orchestrate orchestrated orchestrates orchestrating orchestration orchestrations orchid orchids ordain ordained ordaining ordains ordeal ordeals orderlies orderly ordinance ordinances ordinarier ordinaries ordinariest ordinarily ordination ordinations ore ores organics organism organisms organist organists orgasm orgies orgy orientations orifice originality originators ornament ornamental ornamented ornamenting ornaments ornate ornately ornithologist ornithologists ornithology orphan orphanage orphanages orphaned orphaning orphans orthodontist orthodontists orthodoxes orthogonal orthogonality orthography oscillate oscillated oscillates oscillating oscillation oscillations oscilloscope osmosis ostensible ostensibly ostentation ostentatious ostrich ostriches otter ottered ottering otters ouch ounce ounces oust ousted ouster ousters ousting ousts outbound outbreak outbreaking outbreaks outbroke outbroken outburst outbursting outbursts outcast outcasting outcasts outclass outclassed outclasses outclassing outcries outdid outdistance outdistanced outdistances outdistancing outdo outdoes outdoing outdone outdoor outdoors outed outermost outers outfield outfields outfit outfits outfitted outfitting outgoings outgrew outgrow outgrowing outgrown outgrows outgrowth outgrowths outhouse outhouses outing outings outlaid outlandish outlast outlasted outlasting outlasts outlaw outlawed outlawing outlaws outlay outlaying outlays outlet outlets outlive outlived outlives outliving outlooked outlooking outlooks outlying outmoded outnumber outnumbered outnumbering outnumbers outpatient outpatients outpost outposts outputted outputting outrageously outran outrun outrunning outruns outs outsets outsetting outshine outshines outshining outshone outsider outsiders outsides outskirt outskirts outsmart outsmarted outsmarting outsmarts outspoken outstandingly outstation outstations outstrip outstripped outstripping outstrips outward outwardly outwards outweighed outweighing outwit outwits outwitted outwitting ova oval ovals ovaries ovary ovation ovations oven ovens overalls overate overbear overbearing overbears overblown overboard overbore overborne overburden overburdened overburdening overburdens overcast overcasting overcasts overcharge overcharged overcharges overcharging overcoat overcoats overcrowd overcrowded overcrowding overcrowds overdid overdo overdoes overdoing overdone overdose overdosed overdoses overdosing overdraw overdrawing overdrawn overdraws overdrew overeat overeaten overeating overeats overestimate overestimated overestimates overestimating overflowed overflowing overflows overgrew overgrow overgrowing overgrown overgrows overhand overhands overhang overhanging overhangs overhaul overhauled overhauling overhauls overhear overheard overhearing overhears overheat overheated overheating overheats overhung overkill overlaid overlain overland overlands overlapped overlapping overlaps overlay overlaying overlays overlie overlies overlying overnights overpass overpasses overpopulation overpower overpowered overpowering overpowers overprint overprinted overprinting overprints overran overrate overrated overrates overrating overreact overreacted overreacting overreacts overrule overruled overrules overruling overrun overrunning overruns overs oversampling oversaw oversee overseeing overseen overseer overseers oversees overshadow overshadowed overshadowing overshadows overshoot overshooting overshoots overshot oversight oversights oversimplification oversleep oversleeping oversleeps overslept overstate overstated overstates overstating overstep overstepped overstepping oversteps overt overtake overtaken overtakes overtaking overthrew overthrow overthrowing overthrown overthrows overtimes overtly overtook overture overtures overturn overturned overturning overturns overuse overused overuses overusing overweight overwhelmingly overwork overworked overworking overworks overwrite overwrites overwrought ovum owl owls ox oxen oxes oxidation oxide oxides oyster oysters pa paced pacemaker pacemakers paces pacific pacified pacifiers pacifies pacifism pacifist pacifists pacify pacifying pacing packer packers pact pacts paddies paddle paddled paddles paddling paddock paddocked paddocking paddocks paddy padlock padlocked padlocking padlocks pagan pagans pageant pageantry pageants pager pagination pagoda pagodas pail pails pained painfuller painfullest paining painlessly painstaking painter paired pairing pal palaces palatable palate palates palatial paled paleontologist paleontologists paleontology paler pales palest palette palettes paling pall pallbearer pallbearers palled pallid palling pallor palls palm palmed palming palms palomino palominos palpable palpably pals paltrier paltriest paltry pamper pampered pampering pampers pamphlet pamphlets panacea panaceas pancake pancaked pancakes pancaking pancreas pancreases pancreatic panda pandas pandemonium pander pandered pandering panders pane panes pang panged panging pangs panhandle panhandled panhandler panhandlers panhandles panhandling panicked panickier panickiest panicking panicky panics panned panning panorama panoramas panoramic pans pansies pansy panted panther panthers pantie panties panting pantomime pantomimed pantomimes pantomiming pantries pantry pap papa papacies papacy papal papas papaya papayas paperbacked paperbacking paperbacks papered papering paperweight paperweights paperwork paprika papyri papyrus parable parabled parables parabling parachute parachuted parachutes parachuting paraded parades paradigm parading paradises paradoxes paradoxical paradoxically paraffin paragon paragons paragraphed paragraphing parakeet parakeets paralysis paralytic paralytics paramount paranoids paraphernalia paraphrased paraphrases paraphrasing paraplegic paraplegics parasite parasites parasitic parasol parasols paratrooper paratroopers parcel parcels parch parched parches parching parchment parchments pardonable pardoned pardoning pardons pare pared parentage parental parented parenthetical parenthood parenting pares paring parish parishes parishioner parishioners parka parkas parkway parkways parliamentary parliaments parodied parodies parodying parole paroled paroles paroling parred parring parroted parroting parrots pars parsec parsecs parser parsley parsnip parsnips parson parsonage parsonages parsons partake partaken partakes partaking parted partiality partials participation participle participles particulars partied parting partings partisan partisans partnered partnering partnership partnerships partook partridge partridges partying pas passable passageway passageways passbook passbooks passe passer passionated passionately passionates passionating passioned passioning passions passively passives passports pasta pastas pasted pastel pastels pastes pastiche pastier pasties pastiest pastime pastimes pasting pastor pastoral pastorals pastors pastries pastry pasts pasture pastured pastures pasturing pasty patchwork patchworks patchy pate patented patenting patently patents paternal paternalism paternity pates pathetically pathological pathologist pathologists pathology pathos pathway pathways patienter patientest patiently patio patios patriarch patriarchal patriarchs patrimonies patrimony patriot patriotic patriotism patriots patrol patrolled patrolling patrols patron patronage patronages patrons pats patted patter pattered pattering patterned patterning patters patties patting patty paucity paunch paunched paunches paunchier paunchiest paunching paunchy pauper paupers pave paved pavemented pavementing pavements paves pavilion pavilions paving paw pawed pawing pawn pawnbroker pawnbrokers pawned pawning pawns paws payable payer payers payload payoff payoffs payroll payrolls pea peaceable peacefuller peacefullest peacefully peacemaker peacemakers peaces peach peaches peacock peacocks peaked peaking peal pealed pealing peals pear pearl pearled pearling pearls pears peas peat pebble pebbled pebbles pebbling pecan pecans peck pecked pecking pecks peculiarities peculiarity peculiarly pedagogy pedals peddle peddled peddler peddlers peddles peddling pedestal pedestals pediatricians pediatrics pedigree pedigrees peek peeked peeking peeks peel peeled peeling peels peep peeped peeping peeps peered peering peerless peeve peeved peeves peeving peevish peg pegged pegging pegs pelican pelicans pellet pelleted pelleting pellets pelt pelted pelting pelts pelvic pelvics pelvis pelvises penal penance penanced penances penancing penchant pencils pendant pendants pendulum pendulums penetrate penetrated penetrates penetrating penetration penetrations penguins penicillin peninsula peninsulas penis penises penitence penitent penitentiaries penitentiary penitents penknife penknives penmanship pennant pennants penned penniless penning pension pensioned pensioner pensioners pensioning pensions pensive pensively pentagon pentagonal pentagonals pentagons penthouse penthoused penthouses penthousing penultimate peon peonies peons peony peopled peopling pep pepped pepper peppered peppering peppermint peppermints peppers pepping peps percentages perceptible perceptions perceptive perch perchance perched perches perching percolate percolated percolates percolating percolation percolator percolators percussion peremptory perennial perennials peres perfected perfecter perfectest perfecting perfectionist perfectionists perfections perfects perforate perforated perforates perforating perforation perforations performer performers perfume perfumed perfumes perfuming perfunctorily perfunctory perhapses peril perilous perilously perils perimeter perimeters periodical periodicals peripheries periphery periscope periscoped periscopes periscoping perish perishable perishables perished perishes perishing perjure perjured perjures perjuries perjuring perjury perk perked perkier perkiest perking perks perky permanence permanents permeate permeated permeates permeating permissions permissive permutation permutations pernicious peroxide peroxided peroxides peroxiding perpendicular perpendiculars perpetrate perpetrated perpetrates perpetrating perpetrator perpetrators perpetually perpetuals perpetuate perpetuated perpetuates perpetuating perplex perplexed perplexes perplexing perplexities perplexity persecution persecutions persecutor persecutors perseverance persevere persevered perseveres persevering persisted persistence persistently persisting persists persona personable personals personification personifications personified personifies personify personifying perspectives perspiration perspire perspired perspires perspiring persuasions persuasive persuasively pert pertain pertained pertaining pertains perter pertest pertinent pertinents perts perturb perturbed perturbing perturbs perusal perusals peruse perused peruses perusing pervade pervaded pervades pervading pervasive perversion perversions pervert perverted perverting perverts peskier peskiest pesky pessimism pessimist pessimistic pessimists pest pester pestered pestering pesters pesticide pesticides pestilence pestilences pests petal petals peter petered petering peters petite petites petition petitioned petitioning petitions petrified petrifies petrify petrifying petroleum pets petted petticoat petticoats pettier petties pettiest pettiness petting petulant petunia petunias pew pews pewter pewters phantom phantoms pharmaceutical pharmaceuticals pharmacist pharmacists pheasant pheasants phenomenal phenomenally phenomenas philanthropic philanthropies philanthropist philanthropists philanthropy phlegm phlegmatic phobia phobias phonetic phonetics phonics phonied phonier phonies phoniest phonograph phonographs phony phonying phosphor phosphorescence phosphorescent phosphorus photocopied photocopier photocopiers photocopies photocopying photoed photogenic photographed photographer photographers photographing photography photoing photon photons photosynthesis phototypesetter phraseology physicals physician physicians physiological physique physiques pianist pianists pianos piccolo piccolos pickax pickaxed pickaxes pickaxing picket picketed picketing pickets pickier pickiest pickle pickled pickles pickling pickpocket pickpockets pickup pickups picky picnic picnicked picnicking picnics pictorial pictorials pictured picturesque picturing piddle piddled piddles piddling pieced piecemeal piecework piecing pier pierce pierced pierces piercing piers pies piety pigeoned pigeonhole pigeonholed pigeonholes pigeonholing pigeoning pigeons pigged pigging piggish piggyback piggybacked piggybacking piggybacks pigheaded pigment pigments pigpen pigpens pigtail pigtails pike piked pikes piking piled pilfer pilfered pilfering pilfers pilgrim pilgrimage pilgrimages pilgrims piling pillage pillaged pillages pillaging pillar pillars pillow pillowcase pillowcases pillowed pillowing pillows piloted piloting pilots pimple pimples pimplier pimpliest pimply pincushion pincushions pine pineapple pineapples pined pines pining pinion pinioned pinioning pinions pinked pinker pinkest pinking pinks pinnacle pinnacles pinned pinning pinpoint pinpointed pinpointing pinpoints pioneer pioneered pioneering pioneers pious piped pipelines piping pique piqued piques piquing piracy piranha piranhas pirate pirated pirates pirating pirouette pirouetted pirouettes pirouetting pis pistachio pistachios pistol pistols piston pistons pitched pitcher pitchers pitches pitchfork pitchforked pitchforking pitchforks pitching piteous piteously pithier pithiest pithy pitied pities pitiful pitifuller pitifullest pitifully pitiless pits pittance pittances pitted pitting pitying pivot pivotal pivoted pivoting pivots pixie pixies placard placarded placarding placards placate placated placates placating placement placenta placentas placid placidly plagiarism plagiarisms plagiarist plagiarists plaice plaid plaided plaiding plaids plainer plainest plains plaintiff plaintiffs plaintive planar planed planetarium planetariums planing plank planked planking planks plankton planner planners plantain plantains plantation plantations planter planters plaque plaques plasma plastics plateau plateaued plateauing plateaus plated platformed platforming platforms plating platinum platitude platitudes platoon platooned platooning platoons platter platters plausibility plausibly playable playback playful playfully playfulness playgrounds playhouse playhouses playmate playmates playpen playpens plaything playthings playwright playwrights plaza plazas plead pleaded pleading pleads pleas pleasanter pleasantest pleasantries pleasantry pleasings pleasurable pleasured pleasures pleasuring pleat pleated pleating pleats pledge pledged pledges pledging plentiful plentifully plethora pliable pliant plied pliers plies plight plighted plighting plights plod plodded plodding plods plop plopped plopping plops plotters ploys pluck plucked plucking plucks plucky plum plumage plumb plumbed plumber plumbers plumbing plumbs plume plumed plumes pluming plummet plummeted plummeting plummets plump plumped plumper plumpest plumping plumps plums plunder plundered plundering plunders plunge plunged plunger plungers plunges plunging plurality plurals pluses plush plusher plushest plussed plussing plutonium ply plying plywood pneumatic pneumonia poach poached poacher poachers poaches poaching pocketbook pocketbooks pocketed pocketing pockmark pockmarked pockmarking pockmarks pod podded podding podium podiums pods poetical poignancy poignant poinsettia poinsettias pointedly pointlessly poise poised poises poising poisonous poked poker pokers pokes pokier pokiest poking poky polarity polars poled polemic polemics poles policed policemen polices policewoman policewomen policing poling polio polios politely politer politest polka polkaed polkaing polkas polled pollen pollinate pollinated pollinates pollinating pollination polling pollster pollsters pollutant pollutants pollute polluted pollutes polluting polo polygamous polygamy polygon polygons polynomials polyp polyps polytechnic pomegranate pomegranates pomp poncho ponchos pond ponder pondered pondering ponderous ponders ponds ponies pontoon pontooned pontooning pontoons pony poodle poodles pooled pooling pools poop pooped pooping poops popcorn poplar poplars poppies poppy populaces popularly populars populous porcelain porch porches porcupine porcupines pore pored pores poring pornographic porous porpoise porpoised porpoises porpoising porridge portables portal portals portend portended portending portends portent portents portered portering portfolio portfolios porthole portholes portico porticoes portioned portioning portlier portliest portly portrait portraits portrayal portrayals posies positional positiver positives positivest positivism possessions possessive possessives possessor possessors possibler possibles possiblest possum possums postbox postcards postcode posterior posteriors posterity postgraduate postgraduates posthumous posthumously postman postmark postmarked postmarking postmarks postmasters postmen postponement postponements postscripts postulated postulates postulating posture postured postures posturing posy potassium potency potent pothole potholed potholes potholing potion potions pots potted potter pottered potteries pottering potters pottery potting pouch pouched pouches pouching poultry pounce pounced pounces pouncing pounded pounding pout pouted pouting pouts powdered powdering powders powdery powerfully powerhouse powerhouses powerless powwow powwowed powwowing powwows practicalities practicality practitioner practitioners pragmatics pragmatism prairie prairies praised praises praiseworthy praising pram prance pranced prances prancing prank pranks prattle prattled prattles prattling prawn prawned prawning prawns preacher preachers preamble preambled preambles preambling precarious precariously precautionary precedents precinct precincts precipice precipices precipitate precipitated precipitates precipitating precipitation precipitations precipitous precis precised preciser precises precisest precising preclude precluded precludes precluding precocious preconceive preconceived preconceives preconceiving preconception preconceptions precursor precursors predator predators predatory predefined predestination predicament predicaments predicate predicated predicates predicating predictably predictor predisposition predispositions predominance predominant predominate predominated predominates predominating preeminence preeminent preempt preempted preempting preempts preen preened preening preens prefab prefabbed prefabbing prefabs prefaced prefaces prefacing prefect preferential pregnancies prehistoric prejudicial preliminaries prelude preludes premeditation premier premiere premiered premieres premiering premiers premised premising premiums premonition premonitions prenatal preoccupied preoccupies preoccupy preoccupying prepaid preparations preparatory prepay prepaying prepays preponderance preponderances preposition prepositional prepositioned prepositioning prepositions preposterous prerequisites prerogative prerogatives prescriptions presences presentable presentations presenter preservation preservative preservatives preside presided presidencies presidency presidential presidents presides presiding pressings pressured pressuring prestige prestigious presto presumption presumptions presumptuous presuppose presupposed presupposes presupposing pretender pretenders pretentiously pretentiousness pretext pretexted pretexting pretexts prettied prettier pretties prettiest prettying pretzel pretzels prevailed prevailing prevails prevalence prevalents preventable preventive preventives previewed previewers previewing previews prey preyed preying preys priceless prick pricked pricking prickle prickled prickles pricklier prickliest prickling prickly pricks prided prides priding pried prier pries priestess priestesses priesthood priesthoods prim primal primaries primate primates primed primer primers primeval priming primly primmer primmest primp primped primping primps primrose primrosed primroses primrosing princes princess princesses principalities principality principals principled principling printable printings priors prism prisms prisoned prisoning prisons privater privates privatest privation privations privier privies priviest privy probabilistic probables probation probe probed probes probing problematic procedural procession processional processionals processioned processioning processions proclaimed proclaiming proclaims proclamation proclamations procrastinate procrastinated procrastinates procrastinating procrastination procure procured procurement procures procuring prod prodded prodding prodigal prodigals prodigies prodigious prodigy prods productions profane profaned profanes profaning profanities profanity profess professed professes professing professionally professions professors proffer proffered proffering proffers proficiency proficient proficiently proficients profiled profiling profited profiteer profiteered profiteering profiteers profiting profounder profoundest profoundly profundities profundity profuse profusely profusion profusions progeny prognoses prognosis progression progressions progressive progressively progressives prohibition prohibitions prohibitive prohibitively projectile projectiles projections projector projectors proletarian proletarians proletariat proliferate proliferated proliferates proliferating prolific prologue prologues prom promenade promenaded promenades promenading prominence prominently promiscuity promiscuous promontories promontory promotions prompter promptest promptness proms promulgate promulgated promulgates promulgating prong prongs pronouncement pronouncements pronouns pronunciations proofed proofing proofread proofreading proofreads prop propagate propagated propagates propagating propagation propel propelled propeller propellers propelling propels propensities propensity properer properest prophecies prophecy prophesied prophesies prophesy prophesying prophetic prophets proponent proponents proportionality proportionally proportionals proportionate proportioned proportioning propositional propositioned propositioning propositions propped propping proprietaries proprietor proprietors propriety props propulsion pros prosecutions prosecutor prosecutors proses prospected prospecting prospectives prospector prospectors prospectus prospectuses prosper prospered prospering prosperity prosperous prospers prostituted prostituting prostitution prostrate prostrated prostrates prostrating protagonist protagonists protections protective protectives protector protectors protege proteges proteins protestant protested protesting protests proton protons prototypes protract protracted protracting protractor protractors protracts protrude protruded protrudes protruding protrusion protrusions prouder proudest proudly provable provably provenance proverb proverbial proverbs providence provider province provinces provincial provincials provisionally provisioned provisioning proviso provisos provocation provocations prow prowess prowl prowled prowler prowlers prowling prowls prows proxies proxy prude prudence prudent prudes prudish prune pruned prunes pruning pry prying psalm psalms pseudonym pseudonyms psych psyche psyched psychedelic psychedelics psyches psychiatric psychiatrist psychiatrists psychiatry psychic psychics psyching psychoanalysis psychoanalyst psychoanalysts psychologically psychologies psychopath psychopaths psychoses psychosis psychotherapies psychotherapy psychotic psychs puberty puck pucked pucker puckered puckering puckers pucking pucks puddings puddle puddled puddles puddling pudgier pudgiest pudgy pueblo pueblos puff puffed puffer puffier puffiest puffing puffs puffy pugnacious puke puked pukes puking pulley pulleys pullover pullovers pulmonary pulped pulping pulpit pulpits pulps pulsate pulsated pulsates pulsating pulsation pulsations pulsed pulsing puma pumas pumice pumices pummel pummels pumpernickel pumpkin pumpkins punchline punctual punctuality punctuate punctuated punctuates punctuating punctured punctures puncturing pundit pundits pungent punier puniest punishable punishments punitive punk punker punkest punks punned punning punted punter punters punting puny pup pupped puppet puppets puppied puppies pupping puppy puppying pups purchaser purchasers pured puree pureed pureeing purees purer purest purgatory purged purges purging purification purified purifies purify purifying puring puritanical purpler purples purplest purport purported purporting purports purposed purposeful purposing purr purred purring purrs purse pursed purses pursing pursuits purveyor pus pusher pushers pushier pushiest pushover pushovers pushy puss pusses pussier pussies pussiest pussy putative putrid putter puttered puttering putters puttied putties putty puttying pyramid pyramided pyramiding pyramids pyre pyres pythons qua quack quacked quacking quacks quadrangle quadrangles quadrant quadrants quadratic quadrilateral quadrilaterals quadruped quadrupeds quadruple quadrupled quadruples quadruplet quadruplets quadrupling quagmire quagmired quagmires quagmiring quail quailed quailing quails quaint quainter quaintest quake quaked quakes quaking qualitative qualm qualms quandaries quandary quantifier quantify quantitative quarantine quarantined quarantines quarantining quark quarrel quarrels quarrelsome quarried quarries quarry quarrying quart quarterback quarterbacked quarterbacking quarterbacks quartered quartering quarterlies quarterly quartet quartets quarts quartz quash quashed quashes quashing quaver quavered quavering quavers quay quays queasier queasiest queasy queened queening queenlier queenliest queenly queer queered queerer queerest queering queers quell quelled quelling quells quench quenched quenches quenching queried querying quested questing questionnaires quests quibbled quibbles quibbling quiche quicken quickened quickening quickens quicksand quicksands quieted quieting quiets quill quills quilt quilted quilting quilts quinine quintessence quintessences quintet quintets quintuplet quintuplets quip quipped quipping quips quirk quirked quirking quirks quirky quited quites quiting quitter quitters quiver quivered quivering quivers quizzed quizzes quizzical quizzing quorum quorums quotient quotients rabbi rabbis rabbited rabbiting rabble rabbles rabies raccoon raccoons racer racetrack racetracks racially racier raciest racists racked racketed racketeer racketeered racketeering racketeers racketing rackets racking racy radars radial radials radiance radiant radiate radiated radiates radiating radiations radiator radiators radicals radii radioactive radioactivity radioed radioing radish radishes radium raffle raffled raffles raffling raft rafted rafter rafters rafting rafts ragamuffin ragamuffins raged rages ragged raggeder raggedest ragging raging rags ragtime raided raider raiders raiding railed railing railroaded railroading railroads railways rainbows raincoat raincoats raindrop raindrops rainfall rainfalls rainier rainiest rainstorm rainstorms rainwater rainy raisin raisins rake raked rakes raking rallied rallies rally rallying ramble rambled rambler ramblers rambles rambling ramification ramifications rammed ramming ramp rampage rampaged rampages rampaging ramps ramrod ramrodded ramrodding ramrods rams ramshackle ranch ranched rancher ranchers ranches ranching rancid rancorous randomness ranger rangers ranked ranker rankest ranking rankle rankled rankles rankling ransack ransacked ransacking ransacks ransom ransomed ransoming ransoms rap raped rapes rapider rapidest rapidity rapids raping rapist rapists rapped rapping rapport rapports raps rapt rapture raptures rapturous rared rares raring rarities rarity rascal rascals rasher rashes rashest rashly rasp raspberries raspberry rasped rasping rasps raster ratification ratified ratifies ratify ratifying ratings ration rationales rationality rationals rationed rationing rations ratted ratting rattler rattlers rattlesnake rattlesnakes ratty raucous raucously ravage ravaged ravages ravaging ravel ravels raven ravened ravening ravenous ravenously ravens ravine ravined ravines ravings ravining ravish ravished ravishes ravishing rawer rawest rayon rays raze razed razes razing razors reactionaries reactive reactors readability readied readier readies readiest readiness readjust readjusted readjusting readjusts readying realer realest realism realist realistically realists realities reallied reallies reallocate reallocated reallocates reallocating reallying realty ream reamed reaming reams reap reaped reaper reapers reaping reappear reappeared reappearing reappears reaps reared rearing rearrangement rearrangements rears reassurance reassurances rebate rebated rebates rebating rebel rebelled rebelling rebellion rebellions rebellious rebels rebind rebinding rebinds rebirth rebirths reborn rebound rebounded rebounding rebounds rebuff rebuffed rebuffing rebuffs rebuke rebuked rebukes rebuking rebut rebuts rebuttal rebuttals rebutted rebutting recalcitrant recant recanted recanting recants recap recapped recapping recaps recapture recaptured recaptures recapturing recede receded recedes receding receipted receipting receipts receivers recenter recentest receptacle receptacles receptionist receptionists receptions receptive recess recessed recesses recessing recession recessions recharge rechargeable recharged recharges recharging reciprocal reciprocals reciprocate reciprocated reciprocates reciprocating recital recitals recitation recitations recite recited recites reciting recklessly recklessness reclaimed reclaiming reclaims reclamation recline reclined reclines reclining recluse recluses recoil recoiled recoiling recoils recollect recollected recollecting recollections recollects recompense recompensed recompenses recompensing recompile recompiled recompiling reconciled reconciles reconciliation reconciliations reconciling recondition reconditioned reconditioning reconditions reconfigure reconfigured reconnaissance reconnaissances reconnect reconnected reconnecting reconnects reconsidered reconsidering reconsiders reconstruct reconstructed reconstructing reconstruction reconstructions reconstructs recorders recount recounted recounting recounts recoup recouped recouping recoups recourse recoverable recoveries recreate recreated recreates recreating recreation recreations rectal rectangles rector rectors rectum rectums recuperate recuperated recuperates recuperating recuperation recur recurred recurrence recurrences recurrent recurring recurs recursively redden reddened reddening reddens redder reddest redeem redeemable redeemed redeeming redeems redefinition redemption redesign redesigned redesigning redesigns redhead redheads redid redirected redirecting redirection redirects rediscover rediscovered rediscovering rediscovers redistribute redistributed redistributes redistributing redistribution redo redoes redoing redone redraft redraw redress redressed redresses redressing reds redundancies reed reeds reef reefed reefing reefs reek reeked reeking reeks reel reelect reelected reelecting reelects reeled reeling reels referee refereed refereeing referees referendums refill refilled refilling refills refinement refinements refineries refinery reflections reflective reflector reflectors reflexes reflexive reflexives reformation reformations reformatted reformatting reformer reformers refraction refrained refraining refrains refreshment refreshments refrigerate refrigerated refrigerates refrigerating refrigeration refrigerator refrigerators refuel refuels refuge refugee refugees refuges refunded refunding refunds refurbish refurbished refurbishes refurbishing refurbishment refusals refutation refuted refutes refuting regained regaining regains regal regale regaled regales regalia regaling regals regatta regattas regenerate regenerated regenerates regenerating regeneration regent regents regimen regimens regiment regimental regimentals regimented regimenting regiments regimes registrar registrars registrations registries registry regress regressed regresses regressing regression regressions regretful regrettable regularity regulars regulate regulated regulates regulating regurgitate regurgitated regurgitates regurgitating rehabilitate rehabilitated rehabilitates rehabilitating rehabilitation rehash rehashed rehashes rehashing rehearsal rehearsals rehearse rehearsed rehearses rehearsing reigned reigning reigns reimburse reimbursed reimbursement reimbursements reimburses reimbursing rein reincarnate reincarnated reincarnates reincarnating reincarnation reincarnations reindeer reined reinforce reinforced reinforcement reinforcements reinforces reinforcing reining reins reinstatement reiterated reiterates reiterating reiteration reiterations rejections rejoice rejoiced rejoices rejoicing rejoin rejoinder rejoinders rejoined rejoining rejoins rejuvenate rejuvenated rejuvenates rejuvenating rejuvenation relaid relapse relapsed relapses relapsing relational relativistic relaxation relaxations relayed relaying relays releasable relegate relegated relegates relegating relent relented relenting relentless relentlessly relents reliables reliance reliant relic relics reliefs religiously relinquish relinquished relinquishes relinquishing relish relished relishes relishing relive relived relives reliving reload reloaded reloading reloads relocatable relocate relocated relocates relocating remade remainders remake remakes remaking remedial remedied remedies remedying remembrance remembrances reminders reminisce reminisced reminiscence reminiscences reminisces reminiscing remiss remission remissions remit remits remittance remittances remitted remitting remnant remnants remodel remodels remorse remorseful remorseless remoter remotes remotest removable removables removals remunerate remunerated remunerates remunerating remuneration remunerations renaissance rendezvous rendezvoused rendezvouses rendezvousing renditioned renditioning renditions renegade renegaded renegades renegading renege reneged reneges reneging renewable renewal renewals renounce renounced renounces renouncing renovate renovated renovates renovating renovation renovations renown renowned renowning renowns rental rentals rented renting rents renunciation renunciations reopen reopened reopening reopens repaid reparation repatriate repatriated repatriates repatriating repay repaying repayment repayments repays repeal repealed repealing repeals repel repelled repellent repellents repelling repels repentance repentant repentants repented repenting repents repercussion repercussions repertoires repetitions repetitious replay replenish replenished replenishes replenishing replete repleted repletes repleting replica replicas replicate replicated replicates replicating replication reportedly reporters repose reposed reposes reposing repositories repository reprehensible repress repressed represses repressing repression repressions repressive reprieve reprieved reprieves reprieving reprimand reprimanded reprimanding reprimands reprint reprinted reprinting reprints reprisal reprisals reproach reproached reproaches reproaching reproductions reproductive reprogrammed reprogramming reprove reproved reproves reproving reptile reptiles republic republican republicans republics repudiate repudiated repudiates repudiating repudiation repudiations repugnance repugnant repulse repulsed repulses repulsing repulsion reputable reputations repute reputed reputedly reputes reputing requiem requisites requisition requisitioned requisitioning requisitions reroute rerouted reroutes rerouting resale reschedule rescheduled reschedules rescheduling rescind rescinded rescinding rescinds rescued rescuer rescuers rescues rescuing researched researches researching resemblances resented resentful resenting resentment resentments resents reservoir reservoirs reshuffle resided residences residential residing residual residuals residue residues resignations resilience resilient resin resins resistances resistant resisted resisting resistor resistors resists resolute resolutely resoluter resolutes resolutest resolutions resolver resonance resonances resonant resound resounded resounding resounds resourceful resourcefulness respectability respectables respectably respectful respectfully respiration respirator respirators respiratory respite respites resplendent responsibly responsive restful restfuller restfullest restitution restive restless restlessly restlessness restoration restorations restraint restraints restrictives restructure restructured restructures restructuring resubmit resubmits resubmitted resubmitting resultant resultants resumption resumptions resurface resurfaced resurfaces resurfacing resurgence resurgences resurrect resurrected resurrecting resurrections resurrects resuscitate resuscitated resuscitates resuscitating resuscitation retailed retailer retailers retailing retails retainer retainers retaliate retaliated retaliates retaliating retaliation retaliations retard retarded retarding retards retch retched retches retching retention rethink reticence reticent retina retinas retirements retort retorted retorting retorts retrace retraced retraces retracing retracted retracting retraction retractions retracts retreat retreated retreating retreats retribution retributions retries retrievals retriever retrievers retroactive retrograde retrospect retrospected retrospecting retrospective retrospectively retrospectives retrospects retry returnable returnables retype reunion reunions reunite reunited reunites reuniting reused reuses reusing rev revamp revamped revamping revamps revel revelations revelries revelry revels revenged revengeful revenges revenging revenues reverberate reverberated reverberates reverberating reverberation reverberations revere revered reverence reverenced reverences reverencing reverent reverently reveres reverie reveries revering reversal reversals reversible reversion reverted reverting reverts reviewer reviewers revile reviled reviles reviling revisions revisit revisited revisiting revisits revival revivals revive revived revives reviving revoke revoked revokes revoking revolutionaries revolutions revolve revolved revolver revolvers revolves revolving revs revue revues revulsion revved revving rewarded rewarding rewind rework rhapsodies rhapsody rhetoric rheumatism rhino rhinoceros rhinoceroses rhinos rhododendron rhododendrons rhubarb rhubarbs rhymed rhymes rhyming rhythmic rhythms rib ribbed ribbing ribbons ribs riced rices riches richly richness ricing ricketier ricketiest rickety rickshaw rickshaws ricochet ricocheted ricocheting ricochets riddance riddle riddled riddles riddling rider riders ridge ridged ridges ridging ridicule ridiculed ridicules ridiculing rife rifer rifest rifle rifled rifles rifling rift rifted rifting rifts rig rigged rigging righted righteous righteously righteousness righter rightest rightful rightfully righting rightmost rightness rigidity rigidly rigorously rigs rile riled riles riling rim rimmed rimming rims rind rinded rinding rinds ringleader ringleaders ringlet ringlets ringworm rink rinked rinking rinks rinse rinsed rinses rinsing rioted rioter rioters rioting riotous riots ripe riped ripen ripened ripeness ripening ripens riper ripes ripest riping riposte ripper ripple rippled ripples rippling riser risers riskier riskiest risque rite rites rivalries rivalry rive rives rivet riveted riveting rivets roach roaches roadblock roadblocked roadblocking roadblocks roadside roadsides roam roamed roaming roams roar roared roaring roars roast roasted roasting roasts rob robbed robber robberies robbers robbery robbing robe robed robes robin robing robins robs robuster robustest robustness rocked rocker rockers rocketed rocketing rockets rockier rockiest rocking rocky roded rodent rodents rodeo rodeos rodes roding rods roe roes rogue rogues roguish roller rollers romanced romances romancing romantically romantics romp romped romping romps roofed roofing roofs rook rooked rookie rookier rookies rookiest rooking rooks roomed roomier roomiest rooming roommate roommates roomy roost roosted rooster roosters roosting roosts rooted rooter rooting roped ropes roping rosaries rosary rosemary roses rosier rosiest roster rostered rostering rosters rostrum rostrums rosy rotaries rotary rotations rote roted rotes roting rotisserie rotisseries rotor rotors rots rotted rottener rottenest rottens rotting rotund rotunda rotundas rotunded rotunding rotunds rouge rouged rouges roughage roughed roughen roughened roughening roughens rougher roughest roughhouse roughhoused roughhouses roughhousing roughing roughness roughs rouging roulette roundabouts rounder roundest roundness rouse roused rouses rousing router rowboat rowboats rowdier rowdies rowdiest rowdiness rowdy rowed rowing royally royals royalty rubbed rubbers rubbing rubbished rubbishes rubbishing rubble rubbled rubbles rubbling rubied rubier rubies rubiest rubric rubs ruby rubying rucksack ruckus ruckuses rudder rudders ruddied ruddier ruddies ruddiest ruddy ruddying rudely rudeness ruder rudest rudimentary rue rued rueful rues ruff ruffed ruffian ruffianed ruffianing ruffians ruffing ruffle ruffled ruffles ruffling ruffs rug rugby rugged ruggeder ruggedest rugging rugs ruing ruinous rulered rulering rulings rum rumble rumbled rumbles rumbling ruminate ruminated ruminates ruminating rummage rummaged rummages rummaging rummer rummest rummy rump rumped rumping rumple rumpled rumples rumpling rumps rums runaway runaways rundown rundowns rune runes rungs runner runners runnier runniest runny runt runts runway runways rupture ruptured ruptures rupturing ruse ruses rust rusted rustic rustics rustier rustiest rusting rustle rustled rustler rustlers rustles rustling rusts rut ruthless ruthlessly ruthlessness ruts rutted rutting rye sabbatical sabotaged sabotages sabotaging saboteur saboteurs sac sacrament sacramented sacramenting sacraments sacrificial sacrilege sacrileges sacrilegious sacs sadder saddest saddle saddled saddles saddling sades sadism sadist sadistic sadists sadness safari safaried safariing safaris safeguarded safeguarding safekeeping safekeepings safes safetied safeties safetying saffron saffrons sag sagas sage sagebrush sager sages sagest sagged sagger sagging sags sailboat sailboats sailor sailors saintlier saintliest saintly saints salad salads salami salamis salaried salarying salesmen salespeople salesperson saleswoman saleswomen salient salients saliva salivate salivated salivates salivating sallow sallower sallowest sally salmon salmons salon salons saloon saloons salted salter saltest saltier salties saltiest salting salts salty salutation salutations salute saluted salutes saluting salvage salvaged salvages salvaging salve salved salves salving sameness sames sampler sanatorium sanatoriums sanctified sanctifies sanctify sanctifying sanctimonious sanction sanctioned sanctioning sanctions sanctity sanctuaries sanctuary sandal sandals sandbag sandbagged sandbagging sandbags sanded sandier sandiest sanding sandman sandmen sandpaper sandpapered sandpapering sandpapers sands sandstone sandstorm sandstorms sandwiched sandwiching sandy saned saner sanes sanest sangs saning sanitaries sanitarium sanitariums sanitary sanitation sanserif sap sapling sapped sapphire sapphires sapping saps sarcasms sarcastically sardine sardined sardines sardining sari saris sash sashes sassier sassiest sassy satanic satchel satchels satellited satelliting satin satined satining satins satires satirical satirist satirists satisfactions saturate saturated saturates saturating saturation sauced saucepan saucepans saucer saucers sauces saucier sauciest saucing saucy sauerkraut sauna saunaed saunaing saunas saunter sauntered sauntering saunters sausage sausages saute sauteed sauteing sautes savage savaged savagely savager savageries savagery savages savagest savaging saver savvied savvier savvies savviest savvy savvying sawdust sawdusted sawdusting sawdusts sawed sawing saws saxophone saxophones sayings scab scabbed scabbing scabs scaffold scaffolding scaffolds scalar scalars scald scalded scalding scalds scalier scaliest scallop scalloped scalloping scallops scalp scalped scalpel scalpels scalping scalps scaly scamper scampered scampering scampers scandalous scandals scanners scant scanted scanter scantest scantier scanties scantiest scanting scants scanty scapegoat scapegoated scapegoating scapegoats scar scarcer scarcest scarcity scarecrow scarecrows scarfed scarfing scarfs scarier scariest scarleted scarleting scarlets scarred scarring scars scarves scary scathing scatterbrain scatterbrained scatterbrains scavenger scavengers scened scenic scening scent scented scenting scents schemed schemer schemers scheming schizophrenia schizophrenic scholarly scholarship scholarships scholastic schoolboy schoolboys schoolchild schoolchildren schooled schooling schoolteacher schoolteachers schooner schooners scissor scissors scoff scoffed scoffing scoffs scold scolded scolding scolds scoop scooped scooping scoops scoot scooted scooter scooters scooting scoots scoped scopes scoping scorch scorched scorches scorching scorer scorn scorned scornful scorning scorns scorpion scorpions scotchs scoundrel scoundrels scour scoured scourge scourged scourges scourging scouring scours scout scouted scouting scouts scowl scowled scowling scowls scrabble scram scramble scrambled scrambles scrambling scrammed scramming scrams scrapbook scrapbooks scrape scraped scrapes scraping scratchier scratchiest scratchy scrawl scrawled scrawling scrawls scrawnier scrawniest scrawny screech screeched screeches screeching screened screening screwdriver screwdrivers screwier screwiest screwy scribble scribbled scribbles scribbling scribe scribes scripted scripting scripture scriptures scriptwriter scriptwriters scrounge scrounged scrounges scrounging scrub scrubbed scrubbing scrubs scruff scruffier scruffiest scruffs scruffy scruple scrupled scruples scrupling scrupulous scrupulously scrutiny scuff scuffed scuffing scuffle scuffled scuffles scuffling scuffs sculptor sculptors sculpture sculptured sculptures sculpturing scummed scumming scums scurried scurries scurrilous scurry scurrying scuttle scuttled scuttles scuttling scythe scythed scythes scything seafaring seafood seam seaman seamed seamen seaming seams seamstress seamstresses seaport seaports sear searchlight searchlights seared searing sears seas seashell seashells seashore seashores seasick seasickness seaside seasides seasonable seasonal seasoned seasoning seasonings seasons seated seating seaweed secede seceded secedes seceding secession seclude secluded secludes secluding seclusion secondaries secondarily secrecy secretarial secrete secreted secreter secretes secretest secreting secretion secretions secretive sectioned sectioning sectors secured securely securer secures securest securing securities sedan sedans sedate sedated sedater sedates sedatest sedating sedative sedatives sedentary sediment sedimentary sediments seduce seduced seduces seducing seduction seductions seductive seeded seedier seediest seeding seedling seeds seedy seep seepage seeped seeping seeps seer seesaw seesawed seesawing seesaws seethe seethed seethes seething segmentation segmented segmenting segregate segregated segregates segregating segregation seize seized seizes seizing seizure seizures selections selector selectors selfishness seller sellers selves semantically semblance semblances semen semester semesters semicircle semicircles semicolon semicolons semiconductor semiconductors semifinal semifinals seminaries seminary senate senates senator senators senile senility seniority seniors sensational sensationalism sensations sensed senseless sensibilities sensibility sensibler sensibles sensiblest sensing sensitives sensitivities sensor sensors sensory sensual sensuality sensuous sentience sentimentality sentries sentry separations sequels sequenced sequencer sequencing sequentially sequin sequining sequins serenade serenaded serenades serenading serene serened serener serenes serenest serening serenity sergeant sergeants serials sermoned sermoning sermons serpent serpented serpenting serpents serum serums servanted servanting serviceable serviced serviceman servicemen servicing serviette serviettes servile serviles servitude setback setbacks settable setter setters settlement settlements settler settlers sevens seventeen seventeens seventeenth seventeenths sevenths seventies seventy sever severance severances severed severer severest severing severs sew sewage sewed sewer sewers sewing sewn sews sexed sexing sexism shabbier shabbiest shabbily shabby shack shackle shackled shackles shackling shacks shaded shadier shadiest shading shadowed shadowier shadowiest shadowing shadows shadowy shady shaft shafted shafting shafts shaggier shaggiest shaggy shakier shakiest shallower shallowest shallows sham shamble shambles shamed shameful shamefully shameless shames shaming shammed shamming shampoo shampooed shampooing shampoos shamrock shamrocks shams shanties shanty shapelier shapeliest shapely shark sharked sharking sharks sharped sharpen sharpened sharpener sharpeners sharpening sharpens sharper sharpest sharping sharpness sharps shatter shattered shattering shatters shave shaved shaver shavers shaves shaving shawl shawled shawling shawls sheaf shear sheared shearing shears sheath sheathe sheathed sheathes sheathing sheaths sheave sheaves sheen sheepish sheepishly sheered sheerer sheerest sheering sheers sheik sheiks shelled sheller shellfish shellfishes shelling sheltered sheltering shelters shelved shelving shepherd shepherded shepherding shepherds sherbet sherbets sheriff sheriffs sherries sherry shes shied shield shielded shielding shields shies shiftier shiftiest shiftless shifty shimmer shimmered shimmering shimmers shin shingle shingled shingles shingling shinier shiniest shinned shinning shins shipment shipments shipshape shipwreck shipwrecked shipwrecking shipwrecks shire shirk shirked shirking shirks shirted shirting shirts shiver shivered shivering shivers shoal shoaled shoaling shoals shod shoddier shoddiest shoddy shoeing shoelace shoelaces shoestring shoestrings shoo shooed shooing shoos shopkeeper shopkeepers shoplifter shoplifters shopper shoppers shore shored shores shoring shortages shortcoming shortcomings shorted shortenings shortfall shorting shortlist shortness shotgun shotgunned shotgunning shotguns shouldered shouldering shouldest shoved shovel shovels shoves shoving showcase showcased showcases showcasing showdown showdowns showered showering showier showiest showings showman showmen showy shrank shrapnel shred shredded shredding shreds shrew shrewd shrewder shrewdest shrewdness shrewed shrewing shrews shriek shrieked shrieking shrieks shrill shrilled shriller shrillest shrilling shrills shrimp shrimped shrimping shrimps shrine shrines shrink shrinkage shrinking shrinks shrivel shrivels shroud shrouded shrouding shrouds shrub shrubbed shrubberies shrubbery shrubbing shrubs shrug shrugged shrugging shrugs shrunk shrunken shuck shucked shucking shucks shudder shuddered shuddering shudders shuffle shuffled shuffles shuffling shun shunned shunning shuns shunt shunted shunting shunts shutter shuttered shuttering shutters shuttle shuttled shuttles shuttling shyer shyest shying shyness sibling siblings sicked sickenings sicker sickest sicking sickle sickled sickles sicklier sickliest sickling sickly sickness sicknesses sicks sics sideline sidelined sidelines sidelining sidelong sideshow sideshows sidestep sidestepped sidestepping sidesteps sidetrack sidetracked sidetracking sidetracks sidewalk sidewalks sidings sidle sidled sidles sidling siege sieges sierra siesta siestas sieve sieved sieves sieving sift sifted sifting sifts sighed sighing sighs sightless signer signified signifies signify signifying signpost signposted signposting signposts silenced silences silencing silenter silentest silently silents silhouette silhouetted silhouettes silhouetting silk silken silkened silkening silkens silks sill sillies silliness sills silo silos silt silted silting silts silvered silverier silveriest silvering silvers silversmith silversmiths silverware silvery simile similes simmer simmered simmering simmers simpled simples simplex simplification simpling simulations simulator sincerer sincerest sincerity sinew sinews sinewy singe singed singeing singes singled singling singly singularity singulars sinned sinner sinners sinning sinus sinuses sip sipped sipping sips sire sired siren sirens sires siring sirloin sirloins sirred sirring sirs sissier sissies sissiest sissy sistered sisterhood sisterhoods sistering sisterly sisters sited siting sitter sitters sixes sixpence sixpences sixteens sixteenth sixteenths sixths sixtieth sixtieths sizable sizer sizzle sizzled sizzles sizzling skate skateboard skateboarded skateboarding skateboards skated skater skaters skates skating skein skeined skeining skeins skeletons sketched sketchier sketchiest sketching sketchy skew skewed skewer skewered skewering skewers skewing skews ski skid skidded skidding skids skied skies skiing skillet skillets skillful skim skimmed skimming skimp skimped skimpier skimpiest skimping skimps skimpy skims skinflint skinflints skinned skinnier skinniest skinning skinny skins skipper skippered skippering skippers skirmish skirmished skirmishes skirmishing skirted skirting skirts skis skit skited skiting skits skittish skulk skulked skulking skulks skulls skunk skunked skunking skunks skying skylight skylights skyline skylines skyrocket skyrocketed skyrocketing skyrockets skyscraper skyscrapers slab slabbed slabbing slabs slack slacked slacken slackened slackening slackens slacker slackest slacking slacks slain slake slaked slakes slaking slam slammed slamming slams slander slandered slandering slanders slant slanted slanting slants slap slapped slapping slaps slapstick slashed slashes slashing slat slate slated slates slating slats slaughter slaughtered slaughtering slaughters slaved slavery slaving slavish slay slaying slays sleazier sleaziest sleazy sled sledded sledding sledgehammer sleds sleek sleeked sleeker sleekest sleeking sleeks sleeper sleepers sleepier sleepiest sleepless sleepy sleet sleeted sleeting sleets sleeve sleeveless sleeves sleigh sleighed sleighing sleighs slender slenderer slenderest slew slewed slewing slews slick slicked slicker slickest slicking slicks slided slier sliest slighted slighting slights slime slimier slimiest slimmed slimmer slimmest slimming slims slimy sling slinging slings slingshot slingshots slink slinking slinks slipper slipperier slipperiest slippers slipshod slit slither slithered slithering slithers slits slitted slitter slitting sliver slivered slivering slivers slob slobber slobbered slobbering slobbers slobs slog slogans slogged slogging slogs slop sloped slopes sloping slopped sloppier sloppiest slopping slops slosh sloshed sloshes sloshing sloth slothed slothful slothing sloths slotted slotting slouch slouched slouches slouching slovenlier slovenliest slovenly slowness sludge sludged sludges sludging slug slugged slugging sluggish slugs sluice sluiced sluices sluicing slum slumber slumbered slumbering slumbers slummed slummer slumming slump slumped slumping slumps slums slung slunk slur slurred slurring slurs slush slut sluts sly slyness smack smacked smacking smacks smalled smalling smallpox smalls smarted smarter smartest smarting smartly smarts smattering smatterings smear smeared smearing smears smelled smellier smelliest smelling smelt smelted smelting smelts smidgen smidgens smirk smirked smirking smirks smite smites smithereens smiths smiting smitten smock smocked smocking smocks smog smokestack smokestacks smokier smokies smokiest smoky smoldered smolders smoothed smoother smoothest smoothing smoothness smooths smote smother smothered smothering smothers smudge smudged smudges smudging smugged smugger smuggest smugging smuggle smuggled smuggler smugglers smuggles smuggling smugly smugs smut smuts snacked snacking snacks snagged snagging snags snailed snailing snails snake snaked snakes snaking snap snapped snappier snappiest snapping snappy snaps snapshot snapshots snare snared snares snaring snarl snarled snarling snarls snatch snatched snatches snatching sneaker sneakers sneakier sneakiest sneer sneered sneering sneers sneeze sneezed sneezes sneezing snicker snickered snickering snickers snide snider snides snidest sniffed sniffing sniffle sniffled sniffles sniffling sniffs snip snipe sniped sniper snipers snipes sniping snipped snippet snippets snipping snips snitch snitched snitches snitching snob snobbish snobs snooker snoop snooped snooping snoops snootier snootiest snooty snooze snoozed snoozes snoozing snore snored snores snoring snorkel snorkeled snorkeling snorkels snort snorted snorting snorts snot snots snotted snotting snout snouted snouting snouts snowball snowballed snowballing snowballs snowdrift snowdrifts snowed snowfall snowfalls snowflake snowflakes snowier snowiest snowing snowplow snowplowed snowplowing snowplows snows snowstorm snowstorms snowy snub snubbed snubbing snubs snuff snuffed snuffer snuffing snuffs snug snugged snugger snuggest snugging snuggle snuggled snuggles snuggling snugly snugs soak soaked soaking soaks soaped soapier soapiest soaping soaps soapy soar soared soaring soars sob sobbed sobbing sobered soberer soberest sobering sobers sobriety sobs soccer sociable sociables socialists socials sociological sociologist sociologists sociology socked socking soda sodas sodded sodden sodding sodium sodomy sods sofa sofas softball softballs soften softened softening softens softer softest softly softness soggier soggiest soggy soiled soiling soils sojourn sojourned sojourning sojourns solace solaced solaces solacing solder soldered soldering solders soldiered soldiering soled solemn solemner solemnest solemnity solemnly solicit solicited soliciting solicitous solicits solidarity solider solidest solidified solidifies solidify solidifying solidity solidly solids soling solitaire solitaires solitaries solitary solitude soloed soloing soloist soloists solos soluble solubles solvent solvents somber somebodies someday someones somersault somersaulted somersaulting somersaults somethings somewhats somewheres sonata sonatas sonic sonics sonnet sonnets sonorous soot soothe soothed soother soothes soothest soothing sootier sootiest sooty sop sophistication sophistry sophomore sophomores sopped sopping soprano sopranos sops sorcerer sorcerers sorceress sorceresses sorcery sored sorely sorer sores sorest soring sororities sorority sorrier sorriest sorrow sorrowed sorrowful sorrowing sorrows sorta souffle souffles sounder soundest soundly soundproof soundproofed soundproofing soundproofs souped souping soups sour sourced sourcing soured sourer sourest souring sours southeast southeastern southerlies southerly southerner southerners southerns southpaw southpaws southward southwest southwestern souvenir souvenirs sovereign sovereigns sovereignty sow sowed sowing sown sows spa spacecraft spacecrafts spaceship spaceships spacial spacious spade spaded spades spading spaghetti spangle spangled spangles spangling spaniel spanielled spanielling spaniels spank spanked spanking spankings spanks spanned spanner spanners spanning spans spar spared sparer sparest sparing spark sparked sparking sparkle sparkled sparkler sparklers sparkles sparkling sparks sparred sparrer sparring sparrow sparrows spars sparse sparsely sparser sparsest spas spasm spasmed spasming spasmodic spasms spat spate spats spatted spatter spattered spattering spatters spatting spatula spatulas spawn spawned spawning spawns spay spayed spaying spays spear speared spearhead spearheaded spearheading spearheads spearing spearmint spears specialer specialists specials specifics specifier specimens specious speck specked specking specks spectacle spectacles spectacularly spectaculars spectator spectators spectra speculated speculates speculating speculations speculative speculator speculators speeched speeching speechless speedboat speedboats speedier speediest speedometer speedometers speedy spellbind spellbinding spellbinds spellbound speller spendthrift spendthrifts sperm sperms spew spewed spewing spews spheres spherical sphinx sphinxes spice spiced spices spicier spiciest spicing spicy spider spiders spied spigots spiked spikes spiking spilling spills spinach spinal spinals spindlier spindliest spindly spine spineless spines spinning spins spinster spinsters spirals spire spires spirited spiriting spiritually spirituals spited spiteful spitefuller spitefullest spites spiting spittle splash splashed splashes splashing splat splatter splattered splattering splatters spleen spleens splendider splendidest splendidly splice spliced splices splicing splint splinted splinter splintered splintering splinters splinting splints splurge splurged splurges splurging spokes spokesmen spokespeople spokesperson spokespersons spokeswoman spokeswomen sponge sponged sponges spongier spongiest sponging spongy sponsorship spontaneity spoofed spoofing spoofs spook spooked spookier spookiest spooking spooks spooky spooled spooling spools spoon spooned spoonful spoonfuls spooning spoons sporadic spore spores sporran sported sporting sportsmanship spotless spotlight spotlighted spotlighting spotlights spottier spottiest spotty spouse spouses spouted spouting spouts sprain sprained spraining sprains sprangs sprawl sprawled sprawling sprawls sprayed spraying sprays spreadsheet spreadsheets spree spreed spreeing sprees sprier spriest sprig sprigs springboard springboards springier springiest springtime springy sprinkle sprinkled sprinkler sprinklers sprinkles sprinkling sprinklings sprint sprinted sprinter sprinters sprinting sprints sprout sprouted sprouting sprouts spruce spruced sprucer spruces sprucest sprucing spry spud spuds spun spunk spunked spunking spunks spurn spurned spurning spurns spurred spurring spurs spurt spurted spurting spurts sputter sputtered sputtering sputters spying squabble squabbled squabbles squabbling squadded squadding squadron squadrons squads squalid squalider squalidest squall squalled squalling squalls squalor squander squandered squandering squanders squarely squarer squarest squat squats squatted squatter squattest squatting squawk squawked squawking squawks squeak squeaked squeakier squeakiest squeaking squeaks squeaky squeal squealed squealing squeals squeamish squelch squelched squelches squelching squid squidded squidding squids squint squinted squinter squintest squinting squints squire squired squires squiring squirm squirmed squirming squirms squirrel squirrels squirt squirted squirting squirts stab stabbed stabbing stabled stabler stables stablest stabling stabs stacked stacking stadium stadiums staffed staffing staffs stag stagecoach stagecoaches staged staging stagnant stagnate stagnated stagnates stagnating stagnation stags staid staider staidest stain stained staining stains staircases stairway stairways staked stakes staking staled stalemate stalemated stalemates stalemating staler stales stalest staling stalk stalked stalking stalks stalled stalling stallion stallions stalls stalwart stalwarts stamina stammer stammered stammering stammers stampede stampeded stampedes stampeding stances stanch stanched stancher stanches stanchest stanching standby standbys standings standoff standoffs standpoints standstill standstills stank stanks stanza stanzas staple stapled stapler staplers staples stapling starboard starch starched starches starchier starchiest starching starchy stardom starfish starfishes starked starker starkest starking starks starlight starrier starriest starry startlingly starvation statelier stateliest stately stater statesman statesmanship statesmen stationed stationery stationing statistically statistician statisticians statue statues stature statures statuses statute statutes statutory staunch staunched stauncher staunches staunchest staunching staunchly stave staved staving steadfast steadied steadier steadies steadiest steadying steak steaks stealth stealthier stealthiest stealthily stealthy steamed steamier steamies steamiest steaming steamroller steamrollered steamrollering steamrollers steams steamy steeled steeling steels steeped steeper steepest steeping steeple steeples steeps stellar stemmed stemming stench stenched stenches stenching stencil stencils stenographer stenographers stenography stepladder stepladders stereos stereotyped stereotyping stern sterned sterner sternest sterning sternly sternness sterns stethoscope stethoscopes stew steward stewarded stewardess stewardesses stewarding stewards stewed stewing stews sticker stickers stickied stickier stickies stickiest stickler sticklers stickying stiffed stiffen stiffened stiffening stiffens stiffer stiffest stiffing stiffly stiffness stiffs stifle stifled stifles stifling stigma stigmas stigmata stillborn stillborns stilled stiller stillest stilling stillness stills stilted stimulant stimulants stimuli stimulus sting stinger stingers stingier stingiest stinginess stinging stings stingy stink stinking stinks stint stinted stinting stints stipulate stipulated stipulates stipulating stipulation stipulations stirrup stirrups stitch stitched stitches stitching stockade stockaded stockades stockading stockbroker stockbrokers stocked stockholder stockholders stockier stockiest stocking stockings stockpile stockpiled stockpiles stockpiling stocky stockyard stockyards stodgier stodgiest stodgy stoical stoke stoked stokes stoking stoles stolid stolider stolidest stolidly stomached stomaching stomachs stomp stomped stomping stomps stoned stonier stoniest stoning stony stool stools stoop stooped stooping stoops stopgap stopgaps stopover stopovers stoppage stoppages stopper stoppered stoppering stoppers stopwatch stopwatches storehouse storehouses storekeeper storekeepers storeroom storerooms stork storks stormed stormier stormiest storming stormy stout stouter stoutest stove stoves stow stowaway stowaways stowed stowing stows straddle straddled straddles straddling straggle straggled straggler stragglers straggles straggling straighted straighten straightened straightening straightens straighter straightest straightforwardly straightforwards straighting straights strained strainer strainers straining strait straited straiting straitjacket straitjacketed straitjacketing straitjackets straits strand stranded stranding strands strangeness strangered strangering strangers strangle strangled strangles strangling strangulation strap strapped strapping straps strata stratagem stratagems strategics stratified stratifies stratify stratifying stratosphere stratospheres stratum strawberries strawberry strawed strawing straws strayed straying strays streak streaked streaking streaks streamed streamer streamers streaming streamline streamlined streamlines streamlining streetcar streetcars strengthened strengthening strengthens strengths strenuous strenuously stressful stretcher stretchers strew strewed strewing strewn strews stricken stricter strictest strictness stridden stride strides striding strife striker strikers strikings stringier stringiest stringing stringy stripe striped stripes striping stripper striven strives striving strode stroked strokes stroking stroll strolled stroller strollers strolling strolls stronghold strongholds strove structuralist strum strummed strumming strums strung strut struts strutted strutting stub stubbed stubbier stubbies stubbiest stubbing stubble stubborn stubborned stubborner stubbornest stubborning stubborns stubby stubs stud studded studding studentship studios studious studs stuffier stuffiest stuffy stump stumped stumping stumps stung stunk stunted stunting stunts stupefied stupefies stupefy stupefying stupendous stupider stupidest stupidities stupidly stupids stupor stupors sturdier sturdiest sturdy stutter stuttered stuttering stutters styled styling stylish stylistic stylus suave suaver suavest sub subbed subbing subcommittee subcommittees subconscious subconsciously subdivide subdivided subdivides subdividing subdivision subdivisions subdue subdued subdues subduing subgroup subjectives subjugate subjugated subjugates subjugating subjunctive sublet sublets subletting sublime sublimed sublimer sublimes sublimest subliming submarine submarines submerge submerged submerges submerging submersion submissions submissive subnormal subordinate subordinated subordinates subordinating subprogram subs subscribed subscriber subscribers subscribes subscribing subscript subscriptions subscripts subsection subsections subsequents subservient subservients subsets subside subsided subsides subsidiaries subsidies subsiding subsidy subsist subsisted subsistence subsisting subsists substandard substantiate substantiated substantiates substantiating substitutions subsystem subterfuge subterfuges subterranean subtler subtlest subtract subtracted subtracting subtraction subtractions subtracts suburb suburban suburbans suburbs subversive subversives subvert subverted subverting subverts successes successions successively successors succinct succincter succinctest succinctly succulent succulents succumb succumbed succumbing succumbs suck sucked sucker suckered suckering suckers sucking suckle suckled suckles suckling sucks suction suctioned suctioning suctions suds suede sufferings sufficed suffices sufficing suffixed suffixes suffixing suffocate suffocated suffocates suffocating suffocation suffrage sugared sugarier sugariest sugaring sugars sugary suggester suggestive suicides suitcase suitcases suites suitor suitors sulk sulked sulkier sulkies sulkiest sulking sulks sulky sullen sullener sullenest sultan sultans sultrier sultriest sultry summarily summered summering summers summit summits summon summoned summoning summons summonsed summonses summonsing sumptuous sunbathe sunbathed sunbathes sunbathing sunburn sunburned sunburning sunburns sundae sundaes sundial sundials sundown sundowns sundries sunflower sunflowers sunglasses sunken sunks sunlit sunned sunnier sunnies sunniest sunning sunrises sunrising suns sunscreen sunscreens sunset sunsets sunsetting suntan suntanned suntanning suntans sunup sup superber superbest superbly supercomputer supercomputers supered superficials superhuman superimpose superimposed superimposes superimposing supering superintendent superintendents superiors superlative superlatives supermarkets supernaturals supers superscript superscripts supersede superseded supersedes superseding supersonic supersonics superstar superstars superstition superstitions superstitious superstructure superstructures supervisory supper suppers supplant supplanted supplanting supplants supple supplemented supplementing supplements suppler supplest supportive supposition suppositions supremacy supremely supremer supremest surcharge surcharged surcharges surcharging surer surest surf surfaced surfacing surfboard surfboarded surfboarding surfboards surfed surfing surfs surge surged surgeon surgeons surgeries surges surgical surging surlier surliest surly surmise surmised surmises surmising surmount surmounted surmounting surmounts surnames surpass surpassed surpasses surpassing surpluses surplussed surplussing surreal surrender surrendered surrendering surrenders surreptitious surveillance surveyed surveying surveyor surveyors survivals survivor survivors suspender suspenders suspense suspensions suspicions sustainable sustenance swab swabbed swabbing swabs swagger swaggered swaggerer swaggering swaggers swampier swampiest swampy swan swans swarm swarmed swarming swarms swarthier swarthiest swarthy swat swathe swathed swathes swathing swats swatted swatting sway swayed swaying sways sweater sweaters sweaty sweeper sweepers sweepings sweepstakes sweeten sweetened sweetening sweetens sweeter sweetest sweetheart sweethearts sweetly sweetness sweets swell swelled sweller swellest swelling swellings swells swerve swerved swerves swerving swift swifted swifter swiftest swifting swiftly swifts swig swigged swigging swigs swill swilled swilling swills swindle swindled swindler swindlers swindles swindling swine swines swinging swings swipe swiped swipes swiping swirl swirled swirling swirls swish swished swisher swishes swishest swishing switchable switchboard switchboards switcher swivel swivels swollen swoon swooned swooning swoons swoop swooped swooping swoops sworded swordfish swordfishes swording swords swung syllable syllables syllabus syllabuses symbolics symbolism symmetrical sympathetically sympathetics symphonic symptomatic synagogue synagogues synapse synapses synchronous syndicated syndicates syndicating syndromes synopses synopsis syntheses synthetic synthetics syphilis syphilises syringe syringed syringes syringing syrup systematically systematics tabbed tabbies tabbing tabby tabernacle tabernacles tablecloth tablecloths tabled tablespoon tablespoonful tablespoonfuls tablespoons tablet tablets tabling tabloid tabloids taboo tabooed tabooing taboos tabulate tabulated tabulates tabulating tabulation tacit tacitly taciturn tackier tackies tackiest tacky taco tacos tact tactful tactfully tactlessly tadpole tadpoles tagged tagging tags tailed tailgate tailgated tailgates tailgating tailing taillight taillights tailspin tailspins taint tainted tainting taints takeoff takeoffs takeover talc talisman talismans talkative talker talkers taller tallest tallied tallies tallow tally tallying talon talons tambourine tambourines tamed tamely tameness tamer tames tamest taming tamper tampered tampering tampers tan tandem tandems tang tangential tangents tangerine tangerines tangible tangibles tangle tangled tangles tangling tango tangoed tangoing tangos tangs tankard tankards tanked tanker tankers tanking tanned tanner tannest tanning tans tantamount tantrum tantrums taped taper tapered tapering tapers tapestries tapestry taping tapped tapping taps tar tarantula tarantulas tardier tardies tardiest tardiness tardy targeted targeting tariff tariffs tarnish tarnished tarnishes tarnishing tarpaulin tarpaulins tarred tarried tarrier tarries tarriest tarring tarry tarrying tars tart tartan tartans tartar tartars tarted tarter tartest tarting tarts tasked tasking tassel tasteful tastefully tastier tastiest tasty tattle tattled tattles tattling tattoo tattooed tattooing tattoos tatty taunt taunted taunting taunts taut tauted tauter tautest tauting tautology tauts tavern taverns tawdrier tawdriest tawdry tawnier tawniest tawny taxable taxed taxicab taxicabs taxied taxiing taxing taxis teachings teacup teacups teaed teaing teak teaks teamed teaming teammate teammates teamster teamsters teamwork teapots teardrop teardrops tearful teas tease teased teases teasing teaspoon teaspoons teat teats technicalities technicality technicals technician technicians technologically technologies tediously tedium tee teed teeing teem teemed teeming teems teen teens tees teeter teetered teetering teeters teethe teethed teethes teething teetotal telecommunications telegram telegrams telegraph telegraphed telegraphing telegraphs telepathic telepathy telephoned telephoning telescoped telescopes telescoping teletype televise televised televises televising televisions teller tellered tellering tellers telltale telltales temperament temperamental temperaments temperance temperate temperated temperates temperating tempered tempering tempers tempest tempests tempestuous template temples tempo temporal temporaries tempos temptations tenable tenacious tenacity tenancies tenancy tenant tenanted tenanting tenants tendered tenderer tenderest tendering tenderly tenderness tenders tendon tendons tendril tendrils tenement tenements tenet tenets tenor tenors tensed tenser tenses tensest tensing tensions tensors tent tentacle tentacles tentatives tented tenths tenting tents tenuous tenure tenured tenures tenuring tepee tepees tepid terminators termini terminologies terminus termite termites termly terrace terraced terraces terracing terrain terrains terrestrial terrestrials terrier terriers terrific territorial territorials territories terrors tersely terseness terser tersest testable testament testaments tester testers testes testicle testicles testified testifies testify testifying testimonial testimonials testimonies testimony testis tetanus tether tethered tethering tethers textile textiles textually texture textures thankfuller thankfullest thankless thatch thatched thatcher thatches thatching thaw thawed thawing thaws theatrical thefts theist theists thence theologian theologians theologies theoretic theorist theorists therapeutic therapies therapist therapists thereon thereupon thermal thermals thermodynamics thermometer thermometers thermostat thermostats thesauri thesaurus thesauruses theta thicken thickened thickening thickens thicker thickest thicket thickets thickly thicknesses thigh thighs thimble thimbled thimbles thimbling thinker thinkers thinly thinned thinner thinnest thinning thins thirded thirding thirds thirsted thirstier thirstiest thirsting thirsts thirsty thirteen thirteens thirteenth thirteenths thirties thirtieth thirtieths thistle thistles thong thongs thorn thornier thorniest thorns thorny thoroughbred thoroughbreds thorougher thoroughest thoughtful thoughtfully thoughtfulness thoughtless thoughtlessly thousandth thousandths thrash thrashed thrashes thrashing threadbare threaded threading threads threes thresh threshed thresher threshers threshes threshing thresholds thrice thrift thriftier thriftiest thrifts thrifty thrill thrilled thriller thrillers thrilling thrills thrive thrived thrives thriving throb throbbed throbbing throbs throne thrones throng thronged thronging throngs throttle throttled throttles throttling throwaway throwback throwbacks thud thudded thudding thuds thug thugs thumbed thumbing thumbs thumbtack thumbtacks thump thumped thumping thumps thunder thunderbolt thunderbolts thundered thundering thunderous thunders thunderstorm thunderstorms thunderstruck thwart thwarted thwarting thwarts thyme thyroid thyroids tiara tiaras ticked ticketed ticketing ticking tickle tickled tickles tickling ticklish ticks tidal tidbit tidbits tide tided tides tidier tidiest tiding tier tiers tiff tiffed tiffing tiffs tigers tighten tightened tightening tightens tighter tightest tightness tightrope tightropes tights tightwad tightwads tilde tiled tiling tilled tilling tills tilt tilted tilting tilts timber timbers timekeeper timekeepers timeless timelier timeliest timely timers timescales timetabled timetables timetabling timezone timid timider timidest timidity timidly timings tinder ting tinge tinged tingeing tinges tinging tingle tingled tingles tingling tings tinier tiniest tinker tinkered tinkering tinkers tinkle tinkled tinkles tinkling tinned tinnier tinnies tinniest tinning tinny tinsel tinsels tint tinted tinting tints tipped tipping tipsier tipsiest tipsy tiptoe tiptoed tiptoeing tiptoes tirade tirades tireder tiredest tireless tissue tissues tit titillate titillated titillates titillating titled titling tits titted titter tittered tittering titters titting toads toadstool toadstools toasted toaster toasters toasting toasts tobaccos toboggan tobogganed tobogganing toboggans toddle toddled toddler toddlers toddles toddling toed toeing toenail toenails toffee toffees toga togas toil toiled toileted toileting toiling toils tolerable tolerably tolerances tolled tolling tolls tomahawk tomahawked tomahawking tomahawks tomb tombed tombing tomboy tomboys tombs tombstone tombstones tomcat tomcats tomes tomorrows tonal toned tong tongs tongued tongues tonguing tonic tonics toning tonnage tonnages tonne tonnes tonsil tonsillitis tonsils tooled tooling toolkit toot tooted toothache toothaches toothbrush toothbrushes toothpaste toothpastes toothpick toothpicks tooting toots topaz topazes topographies topography topology topped topping topple toppled topples toppling torch torched torches torching torment tormented tormenting tormentor tormentors torments tornado tornadoes torpedo torpedoed torpedoes torpedoing torque torrent torrential torrents torrid torrider torridest torso torsos tortilla tortillas tortoise tortoises tortuous tortured tortures torturing tossed tosses tossing tot totalitarian totalitarianism totalitarians totalities totality totals tote toted totem totems totes toting tots totted totter tottered tottering totters totting toucan toucans touchdown touchdowns touchier touchiest touchings touchy toughed toughen toughened toughening toughens tougher toughest toughing toughness toughs toupee toupees toured touring tournament tournaments tourniquet tourniquets tours tousle tousled tousles tousling tout touted touting touts tow towed towel towels towered towering towing townspeople tows toxic toxin toxins toyed toying tract traction tractor tractors tracts trademark trademarked trademarking trademarks trader traders traditionalist trafficked trafficking traffics tragedies tragically tragics trailer trailered trailering trailers trainee trainees trainer trainers trait traitor traitorous traitors traits tramp tramped tramping trample trampled tramples trampling trampoline trampolined trampolines trampolining tramps trance trances tranquil tranquiler tranquilest transact transacted transacting transacts transatlantic transcend transcended transcending transcends transcontinental transcribe transcribed transcribes transcribing transcription transcriptions transcripts transferable transformations transformer transformers transfusion transfusions transgress transgressed transgresses transgressing transgression transgressions transients transistor transistors transited transiting transitional transitioned transitioning transitions transitive transitives transitory transits translators transliteration translucent transparencies transparency transparently transpire transpired transpires transpiring transplant transplanted transplanting transplants transportable transportation transpose transposed transposes transposing transverse transversed transverses transversing trapdoor trapeze trapezed trapezes trapezing trapezoid trapezoids trapper trappers trappings trashed trashes trashier trashiest trashing trashy trauma traumas traumatic traverse traversed traverses traversing travestied travesties travesty travestying trawl trawled trawler trawlers trawling trawls trays treacheries treacherous treachery treacle treading treadmill treadmills treads treason treasured treasurer treasurers treasures treasuries treasuring treasury treaties treatise treatises treatments treble trebled trebles trebling treed treeing trekked trekking treks trellis trellised trellises trellising tremble trembled trembles trembling tremor tremors trench trenched trenches trenching trended trendier trendies trendiest trending trepidation trespass trespassed trespasser trespassers trespasses trespassing trestle trestles trialled trialling triangular tribal tribulation tribulations tribunal tribunals tributaries tributary tribute tributes tricked trickery trickier trickiest tricking trickle trickled trickles trickling trickster tricksters tricycle tricycled tricycles tricycling trifled trifles trifling trigonometry trill trilled trilling trillion trillions trills trilogies trim trimester trimesters trimmed trimmer trimmest trimming trims trinket trinkets trio trios tripe tripled triples triplet triplets triplicate triplicated triplicates triplicating tripling tripod tripods tripped tripping trite triter trites tritest triumphant triumphed triumphing triumphs triviality trod trodden trodes troll trolled trolleys trolling trolls trombone trombones trooped trooper troopers trooping trophied trophies trophy trophying tropical tropicals trot trots trotted trotting troubled troublemaker troublemakers troublesome troubling trough troughs trounce trounced trounces trouncing troupe trouped troupes trouping trout trouts trowel trowels truancy truant truanted truanting truants truce truces trucked trucking trudge trudged trudges trudging trued truer trues truest truffle truffles truing truism truisms trump trumped trumpeted trumpeting trumpets trumping trumps truncation trunked trunking trustee trustees trustful trustier trusties trustiest trustworthier trustworthiest trustworthy truthful truthfully truthfulness tryings tryout tryouts tub tuba tubae tubas tubed tuberculosis tubing tubs tubular tuck tucked tucking tucks tuft tufted tufting tufts tug tugged tugging tugs tuition tulip tulips tumble tumbled tumbler tumblers tumbles tumbling tummies tummy tumult tumulted tumulting tumults tumultuous tuna tunas tundra tundras tuneful tuner tuners tunic tunics turban turbans turbine turbines turbulence turbulent tureen tureens turf turfed turfing turfs turgid turkey turkeys turmoil turmoiled turmoiling turmoils turnaround turner turnip turniped turniping turnips turnout turnouts turnover turnovers turnpike turnpikes turnstile turnstiles turntables turpentine turquoise turquoises turret turrets turtle turtleneck turtlenecks turtles tusk tusks tussle tussled tussles tussling tutored tutorials tutoring tutors tuxedo tuxedos twang twanged twanging twangs tweak tweaked tweaking tweaks twee tweed tweet tweeted tweeting tweets tweezers twelfth twelfths twelves twenties twentieths twiddle twiddled twiddles twiddling twig twigged twigging twigs twilight twine twined twines twinge twinged twinges twinging twining twinkle twinkled twinkles twinkling twinned twinning twirl twirled twirling twirls twister twisters twitch twitched twitches twitching twitter twittered twittering twitters twos tycoon tycoons typeface typescript typesetter typewriters typhoid typhoon typhoons typhus typified typifies typify typifying typist typists typographic typographical tyrannical tyrannies tyranny tyrant tyrants ubiquitous udder udders uglied uglier uglies ugliest ugliness uglying ulcer ulcered ulcering ulcers ulterior ultimated ultimates ultimating ultimatum ultimatums ultra ultrasonic ultrasonics ultraviolet umbrellaed umbrellaing umbrellas umpire umpired umpires umpiring umpteen unacceptably unaccepted unaccountable unaccountably unadulterated unaltered unambiguously unanimity unanimous unanimously unanswerable unanswered unarmed unassigned unassuming unattached unattainable unattractive unawares unbearably unbeatable unbecoming unbeliever unbelievers unblock unblocked unblocking unblocks unborn unbreakable unbroken unburden unburdened unburdening unburdens uncannier uncanniest uncanny unceasing uncertainties unchallenged uncharitable unchristian unclean uncleaner uncleanest uncled uncles uncling uncomfortably uncommoner uncommonest uncompromising unconcerned unconditional unconditionally unconfirmed unconsciously unconstitutional uncontrollable uncontrolled uncontroversial unconventional unconvinced uncountable uncouth uncover uncovered uncovering uncovers uncultured uncut undamaged undaunted undecidable undecided undecideds undemocratic undeniable undeniably underbrush underbrushed underbrushes underbrushing undercover undercurrent undercurrents undercut undercuts undercutting underdog underdogs underestimated underestimates underestimating underflow underfoot undergarment undergarments undergrowth underhanded underlays undermine undermined undermines undermining underneaths undernourished underpants underpass underpasses underprivileged underrate underrated underrates underrating underscore underscored underscores underscoring undershirt undershirts underside undersides understandably understandings understate understated understatement understatements understates understating understudied understudies understudy understudying undertaker undertakers undertakings undertone undertones undertow undertows underwater underwear underweight underworld underworlds underwrite underwrites underwriting underwritten underwrote undeserved undesirables undetected undeveloped undisturbed undoings undoubted undress undressed undresses undressing undue undying unearth unearthed unearthing unearthly unearths uneasier uneasiest uneasily uneasiness uneconomic uneconomical uneducated unemployable unenlightened unequal unequals unequivocal unerring unethical uneven unevener unevenest unevenly uneventful unfailing unfairer unfairest unfairly unfaithful unfasten unfastened unfastening unfastens unfeasible unfeeling unfilled unfit unfits unfitted unfitting unfold unfolded unfolding unfolds unforeseen unforgettable unforgivable unfortunates unfriendlier unfriendliest unfunny unfurl unfurled unfurling unfurls ungainlier ungainliest ungainly ungodlier ungodliest ungodly ungrammatical ungrateful unhappier unhappiest unhappily unhappiness unhealthier unhealthiest unheard unhook unhooked unhooking unhooks unicorn unicorns unicycle unidentified unification uniformed uniformer uniformest uniforming uniformity uniforms unilateral unilaterally unimaginative unimpressed uninformative uninformed uninhibited uninitiated uninspired uninspiring unintelligent unintelligible unintended unintentional unintentionally uninterested uniqueness uniquer uniquest unison unities universals universes unjust unjustifiable unjustly unkempt unkind unkinder unkindest unkindlier unkindliest unkindly unknowns unlawful unleash unleashed unleashes unleashing unlikelier unlikeliest unlikes unloaded unloading unloads unluckier unluckiest unman unmanned unmanning unmans unmarked unmarried unmask unmasked unmasking unmasks unmistakable unmistakably unmitigated unmodified unmoved unnamed unnerve unnerved unnerves unnerving unnoticed unoccupied unoriginal unorthodox unpack unpacked unpacking unpacks unpaid unpick unpleasantly unpleasantness unpopularity unprecedented unprepared unprincipled unprintable unprivileged unprotected unproven unprovoked unpublished unqualified unquestionable unquestionably unravel unravels unreal unreasonably unrelenting unreliability unremarkable unrepeatable unrepresentative unreservedly unresolved unrest unrested unresting unrestricted unrests unruffled unrulier unruliest unruly unsafer unsafest unsaid unsanitary unsatisfied unsay unsaying unsays unscathed unscheduled unscientific unscrew unscrewed unscrewing unscrews unscrupulous unseasonable unseat unseated unseating unseats unseemlier unseemliest unseemly unsettle unsettled unsettles unsettling unsightlier unsightliest unsightly unsigned unskilled unsolved unsophisticated unsounder unsoundest unspeakable unstabler unstablest unstructured unstuck unsubstantiated unsuccessfully unsuited unsung unsupportable untangle untangled untangles untangling untenable unthinkable untidier untidiest untie untied unties untiled untiles untiling untiring untold untouched untrained untruer untruest untrustworthy untying unveil unveiled unveiling unveils unwarranted unwary unwashed unwell unwieldier unwieldiest unwieldy unwillingness unwind unwinding unwinds unwiser unwisest unwittingly unworthy unwound unwrap unwrapped unwrapping unwraps unwritten upbeat upbeats upbringings upend upended upending upends upheaval upheavals upheld uphill uphills uphold upholding upholds upholster upholstered upholsterer upholsterers upholstering upholsters upholstery upkeep uplift uplifted uplifting uplifts upload upped uppermost uppers upping uprights uprising uprisings uproar uproars uproot uprooted uprooting uproots upshot upshots upstanding upstart upstarted upstarting upstarts upstream upstreamed upstreaming upstreams uptake uptight uptown upturn upturned upturning upturns upwardly uranium urbane urbaner urbanest urchin urchins urinate urinated urinates urinating urine urn urned urning urns usages uselessly uselessness usher ushered ushering ushers usurp usurped usurping usurps utensil utensils uteri uterus utilitarian utilitarianism utmost utterance utterances uttered utterer utterest uttering utters vacant vacate vacated vacates vacating vacationed vacationing vaccinate vaccinated vaccinates vaccinating vaccination vaccinations vaccine vaccines vacillate vacillated vacillates vacillating vacuous vacuumed vacuuming vacuums vagabond vagabonded vagabonding vagabonds vagaries vagary vagina vaginae vaginal vagrant vagrants vagued vagueing vagueness vaguer vagues vaguest vainer vainest valentine valentines valet valeted valeting valets valiant validate validated validates validating validation validly valise valises valleys valuables valueless valved valving vampire vampired vampires vampiring vandal vandals vane vanes vanguard vanguards vanilla vanillas vanities vanity vanned vanning vanquish vanquished vanquishes vanquishing variously varnish varnished varnishes varnishing varsities varsity vase vases vaster vastest vastness vasts vats vatted vatting vault vaulted vaulting vaults veal vealed vealing veals veer veered veering veers vegetarianism vegetarians vegetation vehement vehemently veil veiled veiling veils veined veining veins velocities velvet velveted velvetier velvetiest velveting velvets velvety vendors veneer veneered veneering veneers venerable venerate venerated venerates venerating veneration vengeance vengeful venison venom venomous vent vented ventilate ventilated ventilates ventilating ventilation ventilator ventilators venting ventricle ventricles ventriloquist ventriloquists vents ventured ventures venturing veracity veranda verandas verballed verballing verbals verbiage verbosity verdicts verge verged verges verging verier veriest veritable vermin vernacular vernaculars versatility versed versing vertebra vertebrae vertebrate vertebrates verticals vertigo verve vessels vest vested vestibule vestibules vestige vestiges vesting vestment vestments vests veteran veterans veterinarian veterinarians veterinaries veterinary veto vetoed vetoes vetoing vets vetted vetting vex vexation vexations vexed vexes vexing viability viaduct viaducts vial vials vibrant vibrate vibrated vibrates vibrating vibration vibrations vicarious vicariously vicars viced vices vicing viciously victor victories victorious victors videoed videoing videos videotape videotaped videotapes videotaping vie vied vies viewers vigil vigilance vigilant vigilante vigilantes vigils vigorous viler vilest vilified vilifies vilify vilifying villa villager villagers villain villainies villainous villains villainy villas vindicate vindicated vindicates vindicating vindictive vine vined vinegar vines vineyard vineyards vining vintages vinyls viola violas violated violates violating violations violet violets violins viper vipers viral virginity virgins virile virility virtuoso virtuosos virtuous virtuously virulent visa visaed visaing visas vise vised vises visibility visibly vising visionaries visionary visioned visioning visions visitation visitations visor visors vista vistaed vistaing vistas visuals vitality vitally vitals vitamin vitamins vitriolic vivacious vivaciously vivacity vivid vivider vividest vividly vivisection vocabularies vocalist vocalists vocals vocation vocational vocations vociferous vociferously vodka vogue vogued vogueing vogues voguing voiced voicing voided voiding voids volatile volcanic volcanics volcano volcanoes volition volley volleyball volleyballs volleyed volleying volleys volt voltages volts volumed voluming voluminous voluntaries voluptuous vomited vomiting vomits voodoo voodooed voodooing voodoos voracious vortex vortexes vouched voucher vouchers vouches vouching vow vowed vowels vowing vows voyage voyaged voyager voyagers voyages voyaging vulgar vulgarer vulgarest vulgarities vulgarity vulnerabilities vulnerability vulture vultures vying wad wadded wadding waddle waddled waddles waddling wads wafer wafers waffled waffles waffling waft wafted wafting wafts wag waged wager wagered wagering wagers wagged wagging waging wags waif waifed waifing waifs wail wailed wailing wails waist waisted waisting waistline waistlines waists waiter waiters waitress waitresses waive waived waiver waivers waives waiving waken wakened wakening wakens walker walkers walkout walkouts walled wallets walling wallop walloped walloping wallops wallow wallowed wallowing wallows wallpaper wallpapered wallpapering wallpapers walnut walnuts walrus walruses waltz waltzed waltzes waltzing wan wand wanderer wanderers wands wane waned wanes waning wanna wanner wannest wanton wantoned wantoner wantoning wantons warble warbled warbles warbling warded warden wardened wardening wardens warding wardrobe wardrobes wards warehoused warehouses warehousing warfare warhead warheads warier wariest warlike warmer warmest warmly warmth warpath warpaths warranted warrantied warranties warranting warrants warrantying warred warren warrens warring warrior warriors wart warts wases washable washables washcloth washcloths washer washered washering washers washout washouts washroom washrooms wasp wasps wastage wastebasket wastebaskets wastefully wasteland wastelands watchdog watchdogs watchful watchman watchmen watchword watchwords watered waterfall waterfalls waterfront waterfronts waterier wateriest watering waterlogged watermark watermarked watermarking watermarks watermelon watermelons waterproof waterproofed waterproofing waterproofs watershed watersheds watertight waterway waterways waterworks watery watt watter wattest watts waveform wavelength wavelengths waver wavered wavering wavers wavier waviest wavy wax waxed waxes waxier waxiest waxing waxy waylaid waylay waylaying waylays wayside waysides wayward weaken weakened weakening weakens weaker weakest weaklier weakliest weakling weakly wealthier wealthiest wean weaned weaning weans weaponry wearied wearier wearies weariest wearily weariness wearisome wearying weathered weathering weathers weave weaved weaver weavers weaves weaving web webbed webbing webs wedder weddings wedge wedged wedges wedging wedlock weed weeded weedier weediest weeding weeds weedy weeing weekdays weekended weekending weeklies weep weeping weeps weer wees weest weighed weighing weighs weighted weightier weightiest weighting weights weighty weirded weirder weirdest weirding weirdness weirdo weirdos weirds weld welded welder welders welding welds welled welling wellington wells welt welted welter weltered weltering welters welting welts wept werewolf werewolves wested westerlies westerly westerns westing wests westward wetter wettest whack whacked whacking whacks whaled whaler whalers whaling wharf wharves whats wheat wheedle wheedled wheedles wheedling wheelbarrow wheelbarrows wheelchair wheelchairs wheeled wheeling wheeze wheezed wheezes wheezing whens whereabouts wherein wheres wherewithal whet whets whetted whetting whew whewed whewing whews whiff whiffed whiffing whiffs whiled whiles whiling whimmed whimming whimper whimpered whimpering whimpers whims whimsical whine whined whines whining whinnied whinnier whinnies whinniest whinny whinnying whip whipped whipping whips whir whirl whirled whirling whirlpool whirlpools whirls whirlwind whirlwinds whirred whirring whirs whisk whisked whisker whiskered whiskers whisking whisks whisper whispered whispering whispers whistled whistling whiten whitened whitening whitens whiter whitest whitewash whitewashed whitewashes whitewashing whittle whittled whittles whittling whizzed whizzes whizzing whoa wholehearted wholes wholesale wholesaled wholesaler wholesalers wholesales wholesaling wholesome whooped whooping whopper whoppers whore whores whys wick wickeder wickedest wickedly wickedness wicker wickers wicket wickets wicks widen widened widening widens widow widowed widower widowers widowing widows widths wield wielded wielding wields wig wigged wigging wiggle wiggled wiggles wiggling wigs wigwam wigwams wildcat wildcats wildcatted wildcatting wilded wilder wilderness wildernesses wildest wildfire wildfires wilding wildlife wildness wilds wilier wiliest willinger willingest willingness willow willows willpower wilt wilted wilting wilts wily wince winced winces winch winched winches winching wincing windfall windfalls windier windiest windmill windmilled windmilling windmills windowpane windowpanes windpipe windpipes windscreen windscreens windshield windshields windy wined winged wingers winging wining wink winked winking winks winnings winsome winsomer winsomest wintered wintering winters wintertime wintrier wintriest wintry wiper wipers wirier wiriest wiry wisecrack wisecracked wisecracking wisecracks wiselier wiseliest wisely wises wishbone wishbones wishful wisp wispier wispiest wisps wispy wist wistful wistfully witchcraft witched witches witching withdrawals withe withed wither withered withering withers withes withheld withhold withholding withholds withing withs withstand withstanding withstands withstood witless wits witticism witticisms wittier wittiest witting wizards wizened wobble wobbled wobbles wobblier wobblies wobbliest wobbling wobbly woe woes wok woks wolfed wolfing wolfs wolves womanhood womankind womb wombats wombs wonderland wonderlands woo woodchuck woodchucks wooded woodener woodenest woodier woodies woodiest wooding woodland woodlands woodpecker woodpeckers woodsman woodsmen woodwind woodwinds woodwork woody wooed woof woofed woofing woofs wooing wool woollier woollies woolliest woolly woos wordier wordiest wordings wordy workbench workbenches workbook workbooks workforce workman workmanship workmen workout workouts workplace workshops worldlier worldliest worldly wormed wormhole wormholes worming worrisome worsen worsened worsening worsens worships worsted worsting worsts worthier worthies worthiest wost wot woulds wounded wounder wounding wounds wove woven wovens wowed wowing wows wrangle wrangled wrangler wranglers wrangles wrangling wrappings wrathed wrathing wraths wreak wreaked wreaking wreaks wreath wreathe wreathed wreathes wreathing wreaths wreckage wrench wrenched wrenches wrenching wrens wrest wrested wresting wrestle wrestled wrestler wrestlers wrestles wrestling wrests wretch wretcheder wretchedest wretches wried wries wriggle wriggled wriggles wriggling wright wring wringer wringers wringing wrings wrinkle wrinkled wrinkles wrinkling wrists wristwatch wristwatches writ writable writhe writhed writhes writhing writs wrongdoer wrongdoers wrongdoing wrongdoings wronged wronger wrongest wronging wrought wrung wry wryer wryest wrying xenophobia xylophone xylophones yacht yachted yachting yachts yak yakked yakking yaks yam yams yank yanked yanking yanks yap yapped yapping yaps yardstick yardsticks yarn yarns yawned yawning yawns yearlies yearling yearn yearned yearning yearnings yearns yeast yeasts yell yelled yelling yellowed yellower yellowest yellowing yellows yells yelp yelped yelping yelps yen yens yeses yessed yessing yesterdays yew yews yielded yielding yodel yodels yoga yogurt yogurts yoke yoked yokel yokels yokes yoking yolk yolks yonder youngster youngsters yous youthful youths yowl yowled yowling yowls zanied zanier zanies zaniest zany zanying zeal zealous zebra zebras zenith zeniths zeroed zeroing zest zests zeta zigzag zigzagged zigzagging zigzags zillion zillions zinc zincked zincking zincs zip zipped zipper zippered zippering zippers zipping zips zodiac zodiacs zombie zombies zoned zoning zoo zoological zoologist zoologists zoology zoomed zooming zooms zoos zucchini zucchinis """.split()) SCOWL50 = set(""" aardvarks abaft abalone abalones abase abased abasement abases abash abashed abashes abashing abasing abatement abattoir abattoirs abbe abbes abbess abbesses abduction abductions abductor abductors abeam abed aberrant abettor abettors abeyance abidings abjectly abjuration abjurations abjure abjured abjures abjuring ablative ablatives abloom ablution ablutions abnegate abnegated abnegates abnegating abnegation abolitionist abolitionists abominably abominate abominated abominates abominating abominations aboriginals abortionist abortionists abracadabra abrade abraded abrades abrading abrasion abrasions abrasively abrasiveness abrogate abrogated abrogates abrogating abrogation abrogations abruptness abscissa abscissas absenteeism absently absinthe absolution absolutism absorbency abstainer abstainers abstemious abstinent abstractedly abstractly abstractness abstractnesses abstrusely abstruseness abstruser abstrusest abusively abusiveness abut abutment abutments abuts abutted abutting abuzz abysmally acacia acacias academia academical academician academicians acanthus acanthuses accentuation accessibly accession accessioned accessioning accessions acclamation acclimation acclimatisation acclimatization accouterments accreditation accretion accretions accrual accruals acculturation accumulative accumulator accurateness accursed accusative accusatives accusatory accusingly acerbic acerbity acetaminophen acetate acetates acetic acetone acetylene achier achiest achiever achievers achoo achromatic achy acidic acidified acidifies acidify acidifying acidly acidulous acme acmes acolyte acolytes aconite aconites acoustical acoustically acquiescent acquirable acquirement acquisitive acquisitiveness acrostic acrostics actinium actionable activation activism actuarial actuaries actuate actuated actuates actuating actuator actuators acuity acupuncturist acupuncturists acuteness adagio adagios adamantly adaptability addend addenda addends adder adders addle addled addles addling addressable adduce adduced adduces adducing adenoid adenoidal adenoids adeptly adeptness adequacy adiabatic adieu adieus adios adipose adjacently adjectival adjectivally adjudge adjudged adjudges adjudging adjudicate adjudicated adjudicates adjudicating adjudication adjudicator adjudicators adjuration adjurations adjure adjured adjures adjuring adjuster adjusters adjutant adjutants adman admen administrate administrated administrates administrating administratively admiralty admiringly admissibility admixture admixtures admonishment admonishments admonitory adoptive adorably adoringly adrenal adrenaline adrenals adroitness adulate adulated adulates adulating adulterant adulterants adulterer adulterers adulteress adulteresses adulterous adumbrate adumbrated adumbrates adumbrating adumbration advantageously adventitious advents adventuresome adventuress adventuresses adventurously adversarial adverted adverting advisability advisedly advisement advocacy adz adzes aegis aerate aerated aerates aerating aeration aerator aerators aerialist aerialists aerie aerier aeries aeriest aerobatics aerobic aerobics aerodynamically aeronautical aeronautics aesthete aesthetes aesthetics affability affirmatively affluently afforest afforestation afforested afforesting afforests affray affrays afghan afghans aficionado aficionados afire aflutter aforethought afoul aft afterbirth afterbirths afterburner afterburners aftercare afterglow afterglows aftershave aftershaves aftershock aftershocks aftertaste aftertastes afterword afterwords agape agar agate agates agave ageism ageless agglomerate agglomerated agglomerates agglomerating agglomeration agglomerations agglutinate agglutinated agglutinates agglutinating agglutination agglutinations aggregation aggregations aggrieve aggrieved aggrieves aggrieving agilely agleam aglitter agog agrarian agrarians agribusiness agribusinesses agriculturalist agriculturalists agronomist agronomists agronomy ague aha ahas ahem ahems aileron ailerons aimlessness airbrush airbrushed airbrushes airbrushing airdrop airdropped airdropping airdrops airfare airfares airhead airheads airily airiness airings airless airlift airlifted airlifting airlifts airman airmen airship airships airsick airsickness airspace airwaves airway airways airworthier airworthiest airworthy akimbo alabaster alacrity alb albacore albacores albatross albatrosses albs albumen albumin alchemist alchemists alchemy alder alderman aldermen alders alderwoman alderwomen alertly alertness alfalfa alfresco algebraically algebras algorithmic alienable alimentary alkalinity alkaloid alkaloids allegorically allegro allegros alleluia alleluias allergen allergenic allergens allergist allergists alleviation alleyway alleyways alliteration alliterations alliterative allover allspice allusive allusively alluvial alluvium alluviums aloe aloes aloha alohas aloofness alpaca alpacas alphanumerics alphas alpine alpines alright altercation altercations alternations alternators altimeter altimeters altruist altruistically altruists alum alumna alumnae alumni alumnus alums amalgam amalgams amanuenses amanuensis amaranth amaranths amaryllis amaryllises amateurism amatory amazon amazons ambassadorial ambassadorship ambassadorships ambergris ambiance ambiances ambidextrously ambitiousness ambivalently ambrosia ambulatories ambulatory ameliorate ameliorated ameliorates ameliorating amelioration amendable amiability amicability amidships amigo amigos amity ammeter ammeters ammo amnesiac amnesiacs amniocenteses amniocentesis amoebic amorality amorally amorously amorousness amorphously amorphousness amour amours amped amperage amping amplitudes ampule ampules amputee amputees anachronistic anaconda anacondas anaerobic anagrams analgesia analog analogously analogs analogues analytically anapest anapests anarchically anarchistic anathemas anatomic anatomically anatomist anatomists ancestress ancestresses anchorite anchorites anchorman anchormen anchorpeople anchorperson anchorwoman anchorwomen ancillaries ancillary andante andantes andiron andirons androgen androgynous anecdotal anemometer anemometers anemone anemones aneurysm aneurysms angelically angina angioplasties angioplasty angiosperm angiosperms angleworm angleworms angora angoras angstrom angstroms angularities angularity animatedly animator animators animism animist animistic animists animus anion anions anise aniseed ankh ankhs anklet anklets anneal annealed annealing anneals annihilator annihilators annular annulars anode anodes anodyne anodynes anointment anons anopheles anorexia anorexic anorexics antacid antacids antagonistically antarctic antebellum antecedent antecedents antechamber antechambers antedate antedated antedates antedating antediluvian anterior anteroom anterooms anther anthers anthologist anthologists anthracite anthropocentric anthropoid anthropoids anthropomorphic anthropomorphism anti antiabortion antiaircraft anticipatory anticked anticking anticlimactic anticlockwise anticyclone anticyclones antidepressant antidepressants antigen antigens antihero antiheroes antihistamine antihistamines antiknock antimatter antimony antiparticle antiparticles antipasti antipasto antipastos antipathetic antipersonnel antiperspirant antiperspirants antiphonal antiphonals antipodes antiquarian antiquarians antiquaries antiquary antis antiseptically antislavery antithetical antithetically antitoxin antitoxins antitrust antiviral antivirals antiwar antlered anymore anytime apace apathetically aperitif aperitifs aphasia aphasic aphasics aphelia aphelion aphelions aphid aphids aphoristic aphrodisiac aphrodisiacs apiaries apiary aplenty apocalypse apocalypses apocalyptic apogee apogees apolitical apologia apologias apologist apologists apoplectic apoplexies apoplexy apostasies apostasy apostate apostates apostolic apothecaries apothecary apotheoses apotheosis appeaser appeasers appellant appellants appellate appellation appellations appendectomies appendectomy appertain appertained appertaining appertains applejack applesauce applique appliqued appliqueing appliques apportion apportioned apportioning apportionment apportions appositely appositeness apposition appositive appositives appraiser appraisers appreciably appreciatively apprehensively apprehensiveness apprise apprised apprises apprising approbation approbations appropriateness approvingly appurtenance appurtenances apropos apse apses aptness aqua aquaculture aquanaut aquanauts aquaplane aquaplaned aquaplanes aquaplaning aquas aquavit aqueous aquifer aquifers aquiline arabesque arabesques arachnid arachnids arbitrariness arboreal arboretum arboretums arborvitae arborvitaes arbutus arbutuses archaically archaism archaisms archangel archangels archbishopric archbishoprics archdeacon archdeacons archdiocese archdioceses archduke archdukes archenemies archenemy archetype archetypes architecturally archivist archivists archly archness arctic arctics arduousness argon argosies argosy argot argots argumentation argyle argyles aridity aright aristocratically arithmetical arithmetically armada armadas armature armatured armatures armaturing armband armbands armful armfuls armhole armholes armlet armlets armrest armrests aromatherapy arousal arpeggio arpeggios arraignment arraignments arranger arrangers arrant arrogate arrogated arrogates arrogating arrowhead arrowheads arrowroot arroyo arroyos arsonist arsonists arteriosclerosis artfully artfulness arthropod arthropods articulateness artier artiest artificer artificers artificiality artiste artistes artless artlessly artlessness artsier artsiest artsy artworks arty ascendancy ascendant ascendants ascertainable asceticism ascot ascots ascribable ascription aseptic asexually ashamedly ashcans ashier ashiest ashram ashrams ashy asinine aslant asocial asocials asp aspartame asperities asperity asphyxia aspic aspics aspirate aspirated aspirates aspirating asps assailable assay assayed assaying assays assemblage assemblages assemblyman assemblymen assemblywoman assemblywomen assertively assertiveness asseverate asseverated asseverates asseverating assiduous assiduously assiduousness assignable assignation assignations assize assizes assonance assuage assuaged assuages assuaging assuredly aster astern asters asthmatic asthmatics astigmatic astigmatism astigmatisms astir astoundingly astrakhan astral astrals astringency astrologer astrologers astronautics astronomic astronomically astrophysicist astrophysicists astrophysics astuteness asunder asymmetric asymmetrical asymmetrically asymptotic asymptotically atavism atavistic atelier ateliers atherosclerosis athletically atmospherically atoll atolls atonal atonality atop atria atrium atrociousness atrophied atrophies atrophy atrophying attackers attainable attar attender attentiveness attenuate attenuated attenuates attenuating attenuation attestation attestations attractively attributions attributive attributively attributives attrition atwitter atypical atypically audaciously audaciousness audibility audiophile audiophiles audiovisual auger augers aught aughts augmentation augmentations augur augured auguries auguring augurs augury auk auks aurally aureole aureoled aureoles aureoling auricle auricles auspice auspices auspiciously auspiciousness austerely authentication authentications authoritarianism authoritarians authoritativeness autism autistic autistics autocratically autoimmune automaton automatons autonomously autopilot autopilots autoworker autoworkers avariciously avast avasts avatar avatars avenger avengers aver averred averring avers avian avians aviaries aviary aviatrices aviatrix aviatrixes avidity avidly avionics avocation avocations avoidably avoirdupois avowedly avuncular awakenings awash aweigh awesomely awestruck awfulness awl awls axial axiomatically axon axons ayatollah ayatollahs azimuth azimuths b baa baaed baaing baas babbler babblers babel babels babushka babushkas babyhood babysat babysit babysits babysitter babysitters babysitting baccalaureate baccalaureates bacchanal bacchanalian bacchanalians bacchanals bacilli bacillus backache backaches backbit backbite backbiter backbiters backbites backbiting backbitings backbitten backboard backboards backbreaking backdate backdated backdates backdating backdrop backdrops backfield backfields backhoe backhoes backless backpacker backpackers backpedal backpedals backrest backrests backsides backslapper backslappers backslid backslide backslider backsliders backslides backsliding backspaced backspaces backspacing backspin backstabbing backstairs backstop backstopped backstopping backstops backstretch backstretches backstroke backstroked backstrokes backstroking backup backups backwardness backwash backwater backwaters backyard backyards bacteriological bacteriologist bacteriologists bacteriology badinage badlands badmouth badmouthed badmouthing badmouths bafflement bagatelle bagatelles bagginess bagpipe bagpipes bah bahs bailiff bailiffs bailiwick bailiwicks bailout bailouts baize balalaika balalaikas balderdash baldly baleen baleful balefuller balefullest balefully balkier balkiest balky balladeer balladeers ballistic balloonist balloonists ballpark ballparks ballplayer ballplayers ballpoint ballpoints ballsier ballsiest ballsy ballyhoo ballyhooed ballyhooing ballyhoos balminess balsa balsam balsamed balsaming balsams balsas baluster balusters balustrade balustrades banalities banality banditry bandoleer bandoleers bane baned baneful banefuller banefullest banes bangle bangles baning banishment banjoist banjoists bankbook bankbooks bankroll bankrolled bankrolling bankrolls banns banshee banshees bantam bantams bantamweight bantamweights banyan banyans baobab baobabs baptismal baptist baptisteries baptistery baptists barbarism barbarisms barbarities barbarity barbarously barbell barbells barberries barberry barbershop barbershops barefaced barefooted barehanded bareheaded bareness barf barfed barfing barfs barium barker barkers barmaid barmaids barnstorm barnstormed barnstorming barnstorms barometric baroness baronesses baronet baronets baronial barrack barracks barracuda barracudas barrenness barrio barrios barroom barrooms barrow barrows basal basalt baseboard baseboards baseless baselines basely baseman basemen baseness bashfully bashfulness basilica basilicas bassinet bassinets bassist bassists basso bassoonist bassoonists bassos bast bastion bastions basts bate bated bates bather bathers bathhouse bathhouses bathmat bathmats bathos bathrobe bathrobes batik batiks bating batsmen batten battened battening battens battier battiest battleground battlegrounds battlement battlements batty bauble baubles bauxite bawdily bawdiness bayberries bayberry bazillion bazillions bazooka bazookas beachcomber beachcombers beachhead beachheads beanbag beanbags bearish bearskin bearskins beastlier beastliest beastliness beastly beatific beatification beatifications beatified beatifies beatify beatifying beatings beatitude beatitudes beatnik beatniks beau beaus beauteous beauteously beautification beautifier beautifiers bebop bebops becalm becalmed becalming becalms beck becks becomingly bedazzle bedazzled bedazzles bedazzling bedeck bedecked bedecking bedecks bedevil bedevilment bedevils bedfellow bedfellows bedpan bedpans bedraggle bedraggled bedraggles bedraggling bedroll bedrolls bedsore bedsores bedstead bedsteads beechnut beechnuts beefburger beefsteak beefsteaks beekeeper beekeepers beekeeping beeline beelined beelines beelining beep beeped beepers beeping beeps befog befogged befogging befogs befoul befouled befouling befouls befuddle befuddled befuddles befuddling beget begets begetting beggarly begone begonia begonias begot begotten begrudgingly beguilingly behemoth behemoths behest behests beholden beholders belay belayed belaying belays beleaguer beleaguered beleaguering beleaguers belladonna belle belles bellicose bellicosity belligerence belligerency belligerently bellwether bellwethers bellyache bellyached bellyaches bellyaching bellybutton bellybuttons bellyful bellyfuls beltway beltways benchmark benchmarks benefaction benefactions benefactress benefactresses benefice beneficence beneficent beneficently benefices beneficially benevolently benignly benumb benumbed benumbing benumbs benzene berate berated berates berating berg bergs beriberi berm berms beryl beryllium beryls besieger besiegers besmirch besmirched besmirches besmirching besom besomed besoming besoms besot besots besotted besotting bespeak bespeaking bespeaks bespoke bespoken bestiaries bestiary bestir bestirred bestirring bestirs bestowal bestowals bestridden bestride bestrides bestriding bestrode bestseller bestsellers betake betaken betakes betaking betas bethink bethinking bethinks bethought betide betided betides betiding betoken betokened betokening betokens betook betrayer betrayers betroth betrothed betrothing betroths betwixt bevel bevels bevies bevy bewail bewailed bewailing bewails biannual biannually biathlon biathlons bibles bibliographer bibliographers bibliographical bibliophile bibliophiles bibulous bicameral bicep biceps bicuspid bicuspids bicyclist bicyclists bidder bidders biddies biddy bidet bidets bidirectional biennially bier biers bifocal bifurcate bifurcated bifurcates bifurcating bifurcation bifurcations biggie biggies bighearted bighorn bighorns bight bights bigmouth bigmouths bigness bigotries bigwig bigwigs biker bikers bilaterally bilge bilges bilious bilk bilked bilking bilks billet billeted billeting billets billies billings billionaire billionaires billionth billionths billowier billowiest billowy billy bimbo bimbos bimonthlies bimonthly binderies bindery binge binged binges binging binnacle binnacles binocular binoculars binomials biochemicals biochemist biochemists biodiversity biofeedback bionic bionics biophysicist biophysicists biophysics biopsied biopsies biopsy biopsying biorhythm biorhythms biosphere biospheres biotechnology bipartite bipedal bipolar biracial birdbath birdbaths birdbrained birdhouse birdhouses birdie birdied birdieing birdies birdseed birdwatcher birdwatchers biretta birettas birthrate birthrates birthright birthrights birthstone birthstones bisection bisections bisector bisectors bisexuality bishopric bishoprics bismuth bisque bistro bistros bitchier bitchiest bitchy bitingly bittern bitterns bitters bitumen bituminous bivalve bivalves bivouac bivouacked bivouacking bivouacs biweeklies biweekly bizarrely blabbermouth blabbermouths blackball blackballed blackballing blackballs blackcurrant blackguard blackguards blackish blackness blackthorn blackthorns blah blahed blahing blahs blamelessly blameworthy blandishment blandishments blandly blandness blankness blarney blarneyed blarneying blarneys blasphemer blasphemers blasphemously blasters blastoff blastoffs blazon blazoned blazoning blazons bleacher bleachers bleakly bleakness blearily bleeder bleeders bleep bleeped bleeping bleeps blench blenched blenches blenching blender blenders blessedly blessedness blinders blindside blindsided blindsides blindsiding blintz blintze blintzes blissfulness bloat bloated bloating bloats blockages blockhouse blockhouses blondness bloodbath bloodbaths bloodcurdling bloodless bloodlessly bloodmobile bloodmobiles bloodstain bloodstained bloodstains bloodstreams bloodsucker bloodsuckers bloodthirstiness bloomer bloomers blooper bloopers blotchier blotchiest blotchy blower blowers blowgun blowguns blowup blowups blowzier blowziest blowzy bluebottle bluebottles bluefish bluefishes bluejacket bluejackets bluenose bluenoses bluffers bluish blunderbuss blunderbusses blunderer blunderers blurbs blurrier blurriest blurry blusher blushers blustery boardinghouse boardinghouses boardroom boardrooms boaster boasters boastfulness boater boaters boatman boatmen boatswain boatswains bobbies bobble bobbled bobbles bobbling bobby bobolink bobolinks bobtail bobtails bobwhite bobwhites bodega bodegas bodkin bodkins bodybuilding bogey bogeyed bogeying bogeyman bogeymen bogeys boggier boggiest boggy bohemian bohemians boilerplate boilings boisterously boisterousness bola bolas boldface bole bolero boleros boles boll bolled bolling bolls bombardier bombardiers bombast bombastic bombshell bombshells bonanza bonanzas bonbon bonbons bondsman bondsmen bonehead boneheads boneless boner boners bong bonged bonging bongo bongos bongs bonito bonitos bonkers bonnie bonnier bonniest bonny bonsai bonsais boob boobed boobies boobing boobs boodle boodles boogie boogied boogieing boogies bookie bookies bookish bookmaker bookmakers bookmaking bookmobile bookmobiles bookseller booksellers bookshelves bookstores boondocks boondoggle boondoggled boondoggles boondoggling boorishly bootblack bootblacks bootlegger bootleggers bootless bootstraps boozed boozer boozers boozes boozier booziest boozing boozy bopped bopping bops borax bordello bordellos borderland borderlands borer borers boron borrower borrowers borscht bosh bossily bossiness botulism boudoir boudoirs bouffant bouffants bouillabaisse bouillabaisses bouillon bouillons bouncer bouncers bouncier bounciest bouncy bounden bounder bounders bounteous bountifully boutonniere boutonnieres bower bowers bowlers bowman bowmen bowsprit bowsprits bowstring bowstrings boxwood boyishly boyishness boysenberries boysenberry bozo bozos bracken bract bracts brad brads bragger braggers braille brainchild brainchildren brainteaser brainteasers brakeman brakemen bramble brambles brashly brashness brattier brattiest bratty bravura bravuras brawler brawlers brawniness brazenly brazenness breadbasket breadbaskets breadfruit breadfruits breakage breakages breaker breakers breakup breakups breastbone breastbones breastplate breastplates breaststroke breaststrokes breastwork breastworks breathable breathier breathiest breathlessly breathlessness breathtakingly breathy breech breeches breezily breeziness breviaries breviary brewer brewers brickbat brickbats bricklaying bridgehead bridgeheads bridgework briefings briefness brier briers brig brigand brigandage brigands brigantine brigantines brigs brilliancy brimful brindled brinkmanship briquette briquettes brisket briskets briskness bristlier bristliest bristly brittleness broadcaster broadcasters broadcloth broadloom broadness broadsword broadswords brogan brogans brogue brogues brokenhearted brokerage brokerages bromide bromides bromine bronchi bronchial bronchus brontosaur brontosaurs brontosaurus brontosauruses brooder brooders broomstick broomsticks brothel brothels brotherliness brouhaha brouhahas brownish brownout brownouts brownstone brownstones browser browsers brr bruin bruins bruiser bruisers brunet brunets brushwood brusquely brusqueness brutishly buccaneer buccaneered buccaneering buccaneers buckboard buckboards bucketful bucketfuls buckeye buckeyes buckler bucklers buckram bucksaw bucksaws buckshot buckskin buckskins buckteeth bucktooth bucktoothed buckwheat bucolic bucolics buddings budgerigar budgerigars budgetary budgie budgies buffoonery bugaboo bugaboos bugbear bugbears buildup buildups bulgier bulgiest bulgy bulimia bulimic bulimics bulkhead bulkheads bulkiness bulletproof bulletproofed bulletproofing bulletproofs bullfighting bullfinch bullfinches bullheaded bullhorn bullhorns bullish bullock bullocks bullpen bullpens bullring bullrings bullshit bullshits bullshitted bullshitting bulrush bulrushes bulwark bulwarks bumble bumbled bumbler bumblers bumbles bumbling bumblings bummers bumpkin bumpkins bumptious bunged bunghole bungholes bunging bungs bunkhouse bunkhouses bunkum bunt bunted bunting buntings bunts buoyantly bur burdock bureaucratically burg burgeon burgeoned burgeoning burgeons burgher burghers burgled burgles burgling burgs burlesque burlesqued burlesques burlesquing burliness burnoose burnooses burnout burnouts burrito burritos burs bursars bursitis busbies busboy busboys busby bushiness bushings bushman bushmen bushwhack bushwhacked bushwhacker bushwhackers bushwhacking bushwhacks businesslike buster busters busyness busywork butane butch butches butterfat butterfingers butterier butteries butteriest butternut butternuts buttocked buttocking buyout buyouts buzzword buzzwords bylaw bylaws byline bylines byplay byproduct byproducts byword bywords c cabal cabals cabana cabanas cabinetmaker cabinetmakers cablecast cablecasting cablecasts cablegram cablegrams caboodle cachet cacheted cacheting cachets cacophonies cacophonous cacophony cadaver cadaverous cadavers caddish cadenza cadenzas cadge cadged cadger cadgers cadges cadging cadmium cadre cadres cads caducei caduceus caesura caesuras caftan caftans cagily caginess cahoot cahoots cairn cairns caisson caissons cajolery calabash calabashes calamine calamined calamines calamining calamitous calcified calcifies calcify calcifying calcine calcined calcines calcining calcite calculable calfskin calibrator calibrators caliph caliphate caliphates caliphs calisthenic calisthenics calligrapher calligraphers calliope calliopes callously callousness callower callowest caloric calorific calumniate calumniated calumniates calumniating calumnies calumny calved calving calypso calypsos calyx calyxes camber cambered cambering cambers cambium cambiums cambric camcorder camcorders camellia camellias cameraman cameramen camerawoman camerawomen camisole camisoles campanile campaniles campfire campfires campground campgrounds camphor campier campiest campsite campsites campy cams camshaft camshafts canape canapes canard canards canasta cancan cancans cancerous candelabra candelabras candelabrum candidness candlelight cankerous cannabis cannabises cannibalistic cannily canniness cannonade cannonaded cannonades cannonading cannonball cannonballed cannonballing cannonballs canoeist canoeists canonicals cantankerously cantankerousness cantata cantatas canted canticle canticles cantilever cantilevered cantilevering cantilevers canting canto canton cantons cantor cantors cantos cants canvasback canvasbacks capacious capaciously capaciousness caparison caparisoned caparisoning caparisons capitalistic capitol capitols capitulation capitulations caplet caplets capon capons cappuccino cappuccinos capriciousness capstan capstans captaincies captaincy captious captivation carafe carafes carapace carapaces caraway caraways carbide carbides carbine carbines carbonate carbonated carbonates carbonating carbonation carboy carboys carbuncle carbuncles carcase carcinogen carcinogens carcinoma carcinomas cardiogram cardiograms cardiologist cardiologists cardiology cardiopulmonary cardiovascular cardsharp cardsharps careen careened careening careens caregiver caregivers caret carets careworn carfare caricaturist caricaturists caries carillon carillonned carillonning carillons carjack carjacked carjacker carjackers carjacking carjackings carjacks carmine carmines carnally carnelian carnelians carom caromed caroming caroms carotid carotids carousal carousals carousel carousels carouser carousers carpal carpals carpel carpels carpetbag carpetbagged carpetbagger carpetbaggers carpetbagging carpetbags carpi carport carports carpus carrel carrels carryall carryalls carryout carryouts carsick carsickness cartilaginous carver carvers carvings caryatid caryatids casein caseload caseloads casement casements casework caseworker caseworkers cassava cassavas cassia cassias cassock cassocks castanet castanets castigation castigator castigators castration castrations casualness casuist casuistry casuists catacomb catacombs catafalque catafalques catalepsy cataleptic cataleptics catalpa catalpas catalysis catalyst catalysts catalytic catamaran catamarans catarrh catastrophically catatonic catatonics catbird catbirds catboat catboats catchall catchalls catcher catchers catchphrase catchword catchwords caterings caterwaul caterwauled caterwauling caterwauls catgut catharses catharsis cathartic cathartics catheter catheters cathode cathodes catholicity cation cations catkin catkins cattail cattails cattier cattiest cattily cattiness cattleman cattlemen catty caudal cauldron cauldrons causalities causally causals causation causative causeless caustically cautionary cautiousness cavalcade cavalcades cavalryman cavalrymen caveatted caveatting caveman cavemen cavernous cavil cavils cayenne cedilla cedillas celebrant celebrants celebratory celerity celesta celestas cellulite celluloid cenotaph cenotaphs censer censers censorious censoriously centaur centaurs centenarian centenarians centenaries centenary centigrade centime centimes centrifugal centrifuged centrifuges centrifuging centripetal centrist centrists centurion centurions cephalic cephalics ceramics cerebellum cerebellums cerebra cerebrum cerebrums ceremonially ceremoniously cerise certifiable certification certifications certitude cerulean cervices cervix cesarean cesareans cession cessions cesspool cesspools cetacean cetaceans chaffinch chaffinches chainsawed chainsawing chainsaws chairlift chairlifts chairmanship chairwoman chairwomen chaise chaises chalkboard chalkboards chamberlain chamberlains chambermaid chambermaids chambray chamois chamomile chamomiles chancel chancelleries chancellery chancels chanceries chancery chancier chanciest chancy chandler chandlers changeling changeovers chanter chanters chantey chanteys chanticleer chanticleers chaotically chaparral chaparrals chaplaincies chaplaincy chaplet chaplets charade charades charbroil charbroiled charbroiling charbroils chargers charier chariest charily charioteer charioteered charioteering charioteers charmer charmers charmingly chartreuse charwoman charwomen chary chaser chasers chastely chasuble chasubles chateau chateaus chateaux chatelaine chatelaines chattel chattels chatterer chatterers chattily chattiness chauvinism chauvinistic cheapskate cheapskates cheater cheaters checklist checklists checkmate checkmated checkmates checkmating checkouts checkpoints checkroom checkrooms cheddar cheekbone cheekbones cheekier cheekiest cheekily cheekiness cheeky cheerily cheeriness cheerleader cheerleaders cheerless cheerlessly cheerlessness cheerses cheeseburger cheeseburgers cheesecake cheesecakes cheesier cheesiest cheesy chemise chemises chemotherapy chenille cheroot cheroots cherubic chervil chessboard chessboards chessman chessmen chevron chevrons chewer chewers chiaroscuro chicaneries chicanery chichi chichier chichiest chichis chickadee chickadees chickenpox chickpea chickpeas chickweed chicle chicories chicory chiffon chigger chiggers chignon chignons chilblain chilblains childbearing childcare childishly childishness childless childlessness childproof childproofed childproofing childproofs chillers chilliness chillings chimera chimeras chimerical chinchilla chinchillas chino chinos chinstrap chinstraps chintzier chintziest chintzy chiropodist chiropodists chiropody chiropractic chiropractics chirrup chirruped chirruping chirrups chiseler chiselers chit chitchat chitchats chitchatted chitchatting chitin chits chitterlings chivalrously chive chived chives chiving chloride chlorides chlorinate chlorinated chlorinates chlorinating chlorination chlorofluorocarbon chlorofluorocarbons chock chocked chocking chocks choker chokers choler choleric chomp chomped chomping chomps choppily choppiness chopstick chopsticks chorale chorales choreograph choreographed choreographic choreographing choreographs chorister choristers chromatic chromatics chronicler chroniclers chronometer chronometers chrysalis chrysalises chubbiness chuckhole chuckholes chumminess chump chumps chunkiness churchgoer churchgoers churchman churchmen churchyard churchyards churl churlish churlishly churlishness churls chutney chutzpah cicada cicadas cicatrice cicatrices cigarillo cigarillos cilantro cilia cilium cinchona cinchonas cincture cinctures cinematic cinematographer cinematographers cinematography cinnabar circadian circlet circlets circuitously circularity circumflexes circumlocution circumlocutions circumnavigate circumnavigated circumnavigates circumnavigating circumnavigation circumnavigations circumscribe circumscribed circumscribes circumscribing circumscription circumscriptions circumspect circumspection circumstantially cirrhosis cirrus citadel citadels citizenry citron citronella citrons civet civets civilly civvies claimant claimants clambake clambakes clamminess clamorous clampdown clampdowns clandestinely clannish clapboard clapboarded clapboarding clapboards clareted clareting clarets clarinetist clarinetists clarion clarioned clarioning clarions classically classicism classicist classicists classier classiest classifiable classifieds classiness classless claustrophobic clavichord clavichords clavicle clavicles clayey clayier clayiest cleanings cleanness cleanup cleanups clearinghouse clearinghouses clematis clematises clement clerestories clerestory clergywoman clergywomen clew clewed clewing clews cliched cliffhanger cliffhangers climatic clincher clinchers clingier clingiest clingy clinician clinicians clinker clinkers clipper clippers cliquish clitoral clitorises cloakroom cloakrooms clobber clobbered clobbering clobbers cloche cloches clodhopper clodhoppers clomp clomped clomping clomps cloned cloning clop clopped clopping clops closefisted closemouthed closeout closeouts clothesline clotheslined clotheslines clotheslining clothier clothiers cloture clotures cloudiness cloudless cloverleaf cloverleafs clownish clownishly clownishness cloy cloyed cloying cloys clubfeet clubfoot clunk clunked clunker clunkers clunkier clunkiest clunking clunks clunky coachman coachmen coagulant coagulants coalescence coatings coauthor coauthored coauthoring coauthors cobbled cobbles cobblestone cobblestones cobbling cocci coccis coccus coccyges coccyx cochlea cochleae cochleas cockade cockades cockamamie cockatoo cockatoos cockerel cockerels cockfight cockfights cockily cockiness cockle cockles cockleshell cockleshells cockney cockneys cockscomb cockscombs cocksucker cocksuckers cocksure coda codas coddle coddled coddles coddling codeine codependency codependent codependents codex codfish codfishes codger codgers codices codicil codicils codification codifications codified codifies codify codifying coed coeds coeducation coeducational coequal coequals coercive coeval coevals coffeecake coffeecakes coffeehouse coffeehouses coffeepot coffeepots cogently cogitate cogitated cogitates cogitating cogitation cognate cognates cognition cognomen cognomens cogwheel cogwheels cohabit cohabitation cohabited cohabiting cohabits cohere cohered coheres cohering cohesion cohesive cohesively cohesiveness cohort cohorts coif coiffed coiffing coiffure coiffured coiffures coiffuring coifs coincident coital coitus cola colas coled coleslaw colicky coliseum coliseums colitis collaboratives collations collectible collectibles collectivism collectivist collectivists colleen colleens collegian collegians collier collieries colliers colliery colling collocate collocated collocates collocating collocation collocations colloid colloids colloquially colloquies colloquium colloquiums colloquy collude colluded colludes colluding collusive cologne colognes colonialism colonialist colonialists colonist colonists colonnade colonnades colossally colossi colossus cols coltish columbine columbines columned columnist columnists comatose combative combo combos combustibility comebacks comedic comedienne comediennes comedown comedowns comeliness comer comers comeuppance comeuppances comfier comfiest comforter comforters comfortingly comfy comically comity commemorative commendably commensurable commensurate commentate commentated commentates commentating commingle commingled commingles commingling commissar commissariat commissariats commissaries commissars commissary committal committals commode commodes commodious commoners communally communicant communicants communicators communistic commutation commutations compactly compactness compactor compactors companionable companionway companionways comparability comparably compassionately compatibly compellingly compendium compendiums compensatory competencies competency competitively competitiveness complacence complacently complainant complainants complainer complainers complaisance complaisant complaisantly complected complicity comport comported comporting comportment comports compositor compositors compote compotes comprehensibility comprehensiveness compressor compressors comptroller comptrollers compulsively compulsiveness compulsorily computationally concavities concavity concentrically concertina concertinaed concertinaing concertinas concertmaster concertmasters concessionaire concessionaires conch conched conching conchs concierge concierges conciliator conciliators conciliatory conclave conclaves concomitant concomitants concordances concordant concretely concubine concubines condemnatory condenser condensers condescendingly condescension conditioner conditioners condo condole condoled condoles condoling condos conduce conduced conduces conducing conduction conductive conductivity conduit conduits confab confabbed confabbing confabs confectioner confectioneries confectioners confectionery conferencing conferment conferments confessedly confessional confessionals confessor confessors confidante confidantes confirmatory conflagration conflagrations confluence confluences confluent conformance conformation conformations conformist conformists confrere confreres confrontational confusedly confusingly confusions confute confuted confutes confuting conga congaed congaing congas congeniality congenially congenital congenitally congestive conglomeration conglomerations congratulation congratulatory congregational congressional congruence congruities congruity congruous conic conics conjectural conjoin conjoined conjoining conjoins conjoint conjunctive conjunctives conjunctivitis conjuncture conjunctures conjurer conjurers conk conked conking conks connectives connivance connive connived conniver connivers connives conniving connotative connubial conquistador conquistadors consanguinity conscientiously conscientiousness conscript conscripted conscripting conscription conscripts consecration consecrations consecutively consensual conservationist conservationists conservatively conservator conservators considerately consonance consonances consortia conspiratorial constable constables constabularies constabulary constipate constipated constipates constipating constitutionality constrictive constrictor constrictors constructively constructor constructors consultancies consultative consumings consummation consummations consumptive consumptives contactable containment contaminant contaminants contemporaneous contemporaneously contemptibly contemptuously contentedly contentedness contentiously contiguity continence continua continuance continuances contortionist contortionists contractile contractually contradistinction contradistinctions contrail contrails contralto contraltos contrapuntal contrarily contrariness contrariwise contravened contravening contraventions contretemps contritely contrition contrivance contrivances controversially controvert controverted controverting controverts contumacious contumelies contumely contuse contused contuses contusing contusion contusions conundrum conundrums conurbation conurbations conventionality convergences convergent conversationalist conversationalists conversationally convexity conveyor conveyors convivial conviviality convocation convocations convoke convoked convokes convoking convolution convolutions convulsively cookeries cookers cookery cookout cookouts coolant coolants coolie coolies coolness coon coons cooperatively coopered coopering coopers coordinators coot cootie cooties coots copilot copilots copings coppery copra copse copsed copses copsing copter copters copula copulas copulated copulates copulating copycat copycats copycatted copycatting copywriter copywriters coquette coquetted coquettes coquetting coquettish cordiality cordite corduroys corespondent corespondents coriander corm cormorant cormorants corms cornball cornballs cornbread corncob corncobs corneal cornerstone cornerstones cornflower cornflowers cornice cornices cornrow cornrowed cornrowing cornrows cornstalk cornstalks cornucopia cornucopias corolla corollaries corollas corona coronas coronet coronets corpora corporas corporeal corpulence correctable correctional correctives correlative correlatives corroborations corroborative corrugate corrugated corrugates corrugating corrugation corrugations corruptly corruptness corsair corsairs cortege corteges cortical cortices cortisone coruscate coruscated coruscates coruscating cosign cosignatories cosignatory cosigned cosigner cosigners cosigning cosigns cosine cosmetically cosmetologist cosmetologists cosmetology cosmically cosmogonies cosmogony cosmological cosmologies cosmologist cosmologists cosponsor cosponsored cosponsoring cosponsors costar costarred costarring costars costliness cote coterie coteries cotes cotillion cotillions cotter cotters cottonmouth cottonmouths cottonseed cottonseeds cotyledon cotyledons councilman councilmen councilwoman councilwomen counselings countably counteraction counteractions counterclaim counterclaimed counterclaiming counterclaims counterculture counterespionage counterexamples counterfeiter counterfeiters counterintelligence countermand countermanded countermanding countermands counteroffer counteroffers counterpane counterpanes counterpoint counterpoints counterproductive counterrevolution counterrevolutionaries counterrevolutionary counterrevolutions countersink countersinking countersinks countersunk countertenor countertenors counterweight counterweights countrified countrywoman countrywomen coupe couped coupes couping couplet couplets courteousness courtesan courtesans courtier courtiers courtlier courtliest courtliness courtly coven covens coverall coveralls coverings coverlet coverlets covetously covetousness covey coveys cowardliness cowbird cowbirds cowhand cowhands cowl cowlick cowlicks cowling cowls coworker coworkers cowpoke cowpokes cowpox cowpuncher cowpunchers cowslip cowslips coxcomb coxcombs coxswain coxswained coxswaining coxswains coyly coyness cozen cozened cozening cozens crabbily crabbiness crackdown crackdowns crackerjack crackerjacks cracklier crackliest crackly crackup crackups craftiness craftsmanship cranial crankcase crankcases crankiness crankshaft crankshafts crannied crannies cranny crannying crape crapes crapped crappie crappier crappies crappiest crapping crappy craps crassly crassness cravat cravats cravatted cravatting craven cravenly cravens craw crawlspace crawlspaces craws creamer creameries creamers creamery creaminess creationism creativeness creche creches credenza credenzas credibly creditably credo credos credulity credulously creel creeled creeling creels creeper creepers creepily creepiness crematoria crematories crematorium crematoriums crematory creole creoles creosote creosoted creosotes creosoting cress crewman crewmen cribbage crick cricked cricketer cricketers cricking cricks crier criers criminologist criminologists criminology crimp crimped crimping crimps crinklier crinklies crinkliest crinkly crinoline crinolines crispier crispiest crispness critter critters crocked croissant croissants crone crones crookedly crookedness crooner crooners cropper croppers croquette croquettes crosier crosiers crossbar crossbarred crossbarring crossbars crossbeam crossbeams crossbones crossbred crossbreed crossbreeding crossbreeds crosscheck crosschecked crosschecking crosschecks crossfire crossfires crossly crossness crossover crossovers crosspiece crosspieces crosstown crosswise crotchet crotchets crotchety croup crouped croupier croupiers croupiest crouping croups croupy crouton croutons crucible crucibles cruciform cruciforms crud cruddier cruddiest cruddy crudeness crudites crudities cruet cruets cruller crullers crumbier crumbiest crumby crumpet crumpets cruncher crunchier crunchiest cryings cryogenics cryptically cryptogram cryptograms cryptographer cryptographers cryptography crystalline crystallines crystallographic crystallography cubbyhole cubbyholes cubical cubism cubist cubists cubit cubits cuckold cuckolded cuckolding cuckolds cud cuddlier cuddliest cudgel cudgels cuds culotte culottes culpability cultivator cultivators culvert culverts cumin cummerbund cummerbunds cumulatively cumuli cumulus cuneiform cunnilingus cunt cunts cupcake cupcakes cupidity cupola cupolaed cupolaing cupolas curacies curacy curate curated curates curating curative curatives curer curie curies curler curlers curlew curlews curlicue curlicued curlicues curlicuing curlier curliest curliness curmudgeon curmudgeons curred curring currycomb currycombed currycombing currycombs curs curseder cursedest cursive cursored cursorily cursoring cursors curtailment curtailments curtly curtness curvaceous curvier curviest curvy cushier cushiest cushy cusp cuspid cuspids cusps cuss cussed cusses cussing custodial customarily cutely cuteness cutesier cutesiest cutesy cutlass cutlasses cutoff cutoffs cuttlefish cuttlefishes cutup cutups cybernetic cyberpunk cyberpunks cyberspace cyclamen cyclamens cyclical cyclically cyclonic cyclotron cyclotrons cygnet cygnets cynically cynosure cynosures cystic cytology cytoplasm czarina czarinas d dB dabbler dabblers dacha dachas dactyl dactylic dactylics dactyls dado dadoes daemons daffier daffiest daffy dafter daftest daguerreotype daguerreotyped daguerreotypes daguerreotyping dahlia dahlias daintiness daiquiri daiquiris dairying dairymaid dairymaids dairyman dairymen dale dales dalliance dalliances dalmatian dalmatians damask damasked damasking damasks damnable damnably dampers damply damson damsons dander dandered dandering danders dandle dandled dandles dandling dankly dankness dapple dappled dapples dappling daringly darkroom darkrooms darneder darnedest dartboard dartboards dashiki dashikis dashingly databased databasing dateline datelined datelines datelining dative datives datums dauber daubers dauntlessly dauntlessness dauphin dauphins davenport davenports davit davits dawdler dawdlers daybed daybeds daydreamer daydreamers daylights dazzlings deaconess deaconesses deactivate deactivated deactivates deactivating deadbeat deadbeats deadbolt deadbolts deadliness deadpan deadpanned deadpanning deadpans deadwood deafen deafened deafening deafens dealership dealerships dearness deathblow deathblows deathless deathlier deathliest deathlike deathly deathtrap deathtraps deb debacle debacles debar debark debarkation debarked debarking debarks debarment debarred debarring debars debater debaters debauch debauched debauches debauching debenture debentures debilitation debonairly debriefings debs debuggers decadently decaf decaffeinate decaffeinated decaffeinates decaffeinating decal decals decamp decamped decamping decamps decant decanted decanting decants decapitation decapitations decathlon decathlons decedent decedents deceitfulness deceiver deceivers decelerate decelerated decelerates decelerating deceleration deceptively deceptiveness decimation decipherable decisiveness deckhand deckhands declaim declaimed declaiming declaims declamation declamations declamatory declarative declassified declassifies declassify declassifying declensions declination declivities declivity decollete decolletes decommission decommissioned decommissioning decommissions decompress decompressed decompresses decompressing decompression decongestant decongestants deconstruction deconstructions decontaminate decontaminated decontaminates decontaminating decontamination decor decorously decors decremented decrements decrepitude decrescendo decrescendos deducible deductible deductibles deejay deejayed deejaying deejays deepness deerskin deescalate deescalated deescalates deescalating defacement defaulter defaulters defeatism defeatists defecation defection defections defector defectors defensively defensiveness deferentially deferment deferments defilement definer definers definiteness definitively deflector deflectors defogger defoggers defoliant defoliants defoliate defoliated defoliates defoliating defoliation deforest deforestation deforested deforesting deforests deformation deformations defray defrayal defrayed defraying defrays defroster defrosters deftness defuse defused defuses defusing degeneracy degeneration degenerative dehumidified dehumidifier dehumidifiers dehumidifies dehumidify dehumidifying dehydration deice deiced deicer deicers deices deicing deification deism dejectedly delectation deliciousness delightfully delineate delineated delineates delineating delineation delineations delinquently deliquescent deliverer deliverers dell dells delphinium delphiniums delusive demagogic demagoguery demagogy demarcate demarcated demarcates demarcating demarcation dementedly demesne demesnes demigod demigods demijohn demijohns demitasse demitasses demo demoed demographer demographers demographic demographically demographics demography demoing demoniac demoniacal demonic demonstrable demonstratively demos demur demurred demurrer demurring demurs denature denatured denatures denaturing dendrite dendrites denier deniers denigrated denigrates denigrating denigration denizen denizens denominate denominated denominates denominating denominational denotation denotations denouement denouements denouncement denouncements denseness dentifrice dentifrices dentin denture dentures denude denuded denudes denuding dependability dependably depictions depilatories depilatory deplane deplaned deplanes deplaning depletion deplorably deploy deployed deploying deployment deployments deploys depopulate depopulated depopulates depopulating depopulation deposition depositions depositor depositories depositors depository deprecation deprecatory depredation depredations depressant depressants depressive depressives deprogram deprogrammed deprogramming deprograms deputation deputations depute deputed deputes deputing derailleur derailleurs derangement derbies derby deregulate deregulated deregulates deregulating deregulation dereliction derisive derisively derisory derivable dermatitis dermatologist dermatologists dermatology dermis derogate derogated derogates derogating derogation derriere derrieres derringer derringers dervish dervishes desalinate desalinated desalinates desalinating desalination descant descanted descanting descants descender descried descries descriptively descry descrying desegregate desegregated desegregates desegregating desertion desertions deservedly deservings desiccate desiccated desiccates desiccating desiccation desiderata desideratum desirably desktops desolately desolateness despairingly desperado desperadoes despicably despoil despoiled despoiling despoils despondency despondently despotism destruct destructed destructible destructing destructively destructiveness destructs desultory detainment detente detentes determinant determinants determinate determiner determiners deterrence detestable detestation dethronement detox detoxed detoxes detoxification detoxified detoxifies detoxify detoxifying detoxing detraction detractor detractors detritus deuce deuced deuces deucing deuterium devaluation devaluations devalued devalues devaluing developmental deviance deviants devilish devilishly devilment devilries devilry deviltries deviltry deviously deviousness devotedly devotional devotionals devoutness dewberries dewberry dewdrop dewdrops dewier dewiest dewlap dewlaps dewy dexterously dextrose dhoti dhotis diabolic diabolically diacritic diacritical diacritics diadem diadems diagnostician diagnosticians diagrammatic dialectal dialectic dialysis diametrical diaphanous diarist diarists diastolic diatom diatoms diatribes dibble dibbled dibbles dibbling dicey dichotomies dichotomy dicier diciest dick dicker dickered dickering dickers dickey dickeys dickier dickiest dicks dicta dictum didactic didactics diddle diddled diddles diddling diereses dieresis dieter dieters dietetic dietetics dietitian dietitians differentials diffidence diffident diffidently diffraction diffusely diffuseness diggers digitalis digraph digraphs digressive dilapidation dilatory dilettante dilettantes dilettantism dillies dilly dillydallied dillydallies dillydally dillydallying dimensionless diminuendo diminuendos diminution diminutions dimmers dimness dimwit dimwits dimwitted dinette dinettes ding dinged dinginess dinging dingo dingoes dings dinkier dinkies dinkiest dinky dint diocesan diocesans diode diodes diorama dioramas dioxin dioxins dipole dipper dippers dipsomania dipsomaniac dipsomaniacs dipstick dipsticks directional directionals directorate directorates directorial directorship directorships dirigible dirigibles dirk dirks dirtiness dis disablement disabuse disabused disabuses disabusing disadvantageously disaffect disaffected disaffecting disaffection disaffects disambiguation disappointingly disapprobation disapprovingly disarrange disarranged disarrangement disarranges disarranging disassemble disassembled disassembles disassembling disassociate disassociated disassociates disassociating disastrously disavowal disavowals disbar disbarment disbarred disbarring disbars discernment disclaimers discoed discoing discombobulate discombobulated discombobulates discombobulating discomfit discomfited discomfiting discomfits discomfiture discommode discommoded discommodes discommoding discompose discomposed discomposes discomposing discomposure disconnectedly disconnection disconnections discontentedly discontentment discontinuance discontinuances discontinuation discontinuations discontinuities discontinuous discotheque discotheques discountenance discountenanced discountenances discountenancing discouragingly discourteously discoverer discoverers discreditable discriminant discursive discussant discussants disdainfully disembodied disembodies disembody disembodying disembowel disemboweled disemboweling disembowels disenchant disenchanted disenchanting disenchants disencumber disencumbered disencumbering disencumbers disenfranchise disenfranchised disenfranchisement disenfranchises disenfranchising disengagement disengagements disentanglement disestablish disestablished disestablishes disestablishing disfigurement disfigurements disfranchise disfranchised disfranchisement disfranchises disfranchising disgorge disgorged disgorges disgorging disgracefully disgustedly disharmonious disharmony dishcloth dishcloths dishevel dishevels dishpan dishpans dishrag dishrags dishtowel dishtowels dishwater disinclination disincline disinclined disinclines disinclining disinformation disinter disinterest disinterestedly disinterests disinterment disinterred disinterring disinters disjointedly diskette diskettes disloyally dismemberment disobediently disoblige disobliged disobliges disobliging disorderliness disorient disorientation disoriented disorienting disorients disparagement disparates dispatcher dispatchers dispensable dispirit dispirited dispiriting dispirits displayable disport disported disporting disports dispossession disproof disproportion disproportionately disproportions disputable disputant disputants disputation disputations disputatious disqualification disqualifications disquisition disquisitions disreputably disrespectfully disrobe disrobed disrobes disrobing dissed dissemble dissembled dissembles dissembling disses dissidence dissimulate dissimulated dissimulates dissimulating dissimulation dissing dissolutely dissoluteness dissonant dissuasion distaff distaffs distastefully distemper distension distensions distention distentions distillate distillates distinctiveness distrait distressful distributive distrustfully disturbingly disunite disunited disunites disuniting disunity diuretic diuretics diurnal diurnally diva divan divans divas diversely diversification diversionary divider dividers divination divinely diviners divisibility divisional divisively divisiveness divot divots divvied divvies divvy divvying dizzily doable doc docent docents docilely docility docket docketed docketing dockets dockyard dockyards docs doctoral doctorates doctrinaire doctrinaires doctrinal docudrama docudramas dodder doddered doddering dodders dodger dodgers dodos doff doffed doffing doffs dogcatcher dogcatchers dogfight dogfighting dogfights dogfish dogfishes dogfought doggedness doggier doggies doggiest doggone doggoned doggoner doggones doggonest doggoning doggy dogie dogies dogmatically dogmatism dogmatist dogmatists dogtrot dogtrots dogtrotted dogtrotting doings dollhouse dollhouses dollop dolloped dolloping dollops dolmen dolmens dolorous dolt doltish dolts domestically domestication dominantly domineer domineered domineering domineers donned donning doodad doodads doodler doodlers doohickey doohickeys doomsday doorbell doorbells doorknob doorknobs doormat doormats dories dork dorkier dorkiest dorks dorky dorm dormancy dormer dormers dormice dormouse dorms dory dosage dosages dossier dossiers dotage doth dotingly dotings dotty doublet doublets doubloon doubloons doubter doubters doubtlessly douche douched douches douching doughier doughiest doughtier doughtiest doughty doughy dourly dovetail dovetailed dovetailing dovetails dowager dowagers dowdily dowdiness dowel dowels downbeat downbeats downer downers download downloaded downloading downloads downplay downplayed downplaying downplays downscale downscaled downscales downscaling downsize downsized downsizes downsizing downstage downstate downswing downswings downtime downtrodden downturn downturns downwind dowse dowsed dowses dowsing doxologies doxology doyen doyens drably drabness drachma drachmas draftee draftees dragnet dragnets dragoon dragooned dragooning dragoons drainer drainers drainpipe drainpipes drake drakes dram drams drawstring drawstrings dray drays dreadlocks dreadnought dreadnoughts dreamily dreamland dreamless dreamlike drearily dreariness dredger dredgers dressage dressiness dressmaking dribbler dribblers driblet driblets drifter drifters drinkings drippings drivings drizzlier drizzliest drizzly drolleries drollery drollness drolly dromedaries dromedary droopier droopiest droopy droplet droplets dropper droppers dropsy drover drovers drownings drowsily drub drubbed drubbing drubbings drubs druid druids dryad dryads drywall drywalled drywalling drywalls duality dubiety dubiousness ducal ducat ducats duchies duchy duckbill duckbills ductile ductility ducting ductless dudgeon duffer duffers duh dukedom dukedoms dulcet dulcimer dulcimers dullard dullards dumbly dumbness dumbwaiter dumbwaiters dun dungaree dungarees dunned dunner dunnest dunning duns duodena duodenal duodenum duos duplicator duplicators durably dustbins duster dusters dustiness dustless dustman duteous dutiable dwarfish dwarfism dweeb dweebs dyadic dyer dyers dyestuff dynamism dynastic dysfunction dysfunctional dysfunctions dyslexic dyslexics dyspepsia dyspeptic dyspeptics e eaglet eaglets earful earfuls earldom earldoms earliness earlobe earlobes earmuff earmuffs earphone earphones earplug earplugs earsplitting earthen earthenware earthiness earthling earthlings earthshaking earthward earthwards earthwork earthworks earwax earwig earwigs easiness eastbound easterner easterners easternmost eastwards eatable eatables eateries eaters eatery eavesdropper eavesdroppers ebullience ebullient eccentrically ecclesiastic ecclesiastics echelon echelons eclat eclectically eclecticism eclectics ecliptic econometric ecru ecstatically ecumenically edelweiss edginess edgings edibility edification edified edifies edify edifying editable editorially educable educables educationally eerily eeriness efface effaced effacement effaces effacing effectually effectuate effectuated effectuates effectuating effeminacy effervesce effervesced effervescence effervesces effervescing effete efficacious efficaciously efficacy effluent effluents effrontery effulgence effulgent effusion effusions effusiveness egalitarianism egalitarians eggbeater eggbeaters egghead eggheads eggnog eggshell eggshells eglantine eglantines egocentrics egoist egoistic egoists egotistic egotistical egotistically egregious egregiously egress egresses egret egrets eider eiderdown eiderdowns eiders eigenvalues elaborateness elan elate elated elates elating elbowroom elderberries elderberry electioneer electioneered electioneering electioneers electrification electrocardiogram electrocardiograms electrocardiograph electrocardiographs electrodynamics electroencephalogram electroencephalograms electroencephalograph electroencephalographs electrolyte electrolytes electrolytic electromagnet electromagnetism electromagnets electroplate electroplated electroplates electroplating elegiac elegiacs elephantine elfin elfish elide elided elides eliding elision elisions elitists elixir elixirs ell elliptically ells elocution elocutionist elocutionists elongation elongations elucidated elucidates elucidating elucidation elucidations elusively elusiveness emaciate emaciated emaciates emaciating emaciation emanation emanations emancipator emancipators emasculate emasculated emasculates emasculating emasculation embalmer embalmers embarkation embarkations embarrassingly embattled embezzler embezzlers emblazon emblazoned emblazoning emblazons emblematic embolden emboldened emboldening emboldens embolism embolisms embroil embroiled embroiling embroils embryologist embryologists embryology emcee emceed emceeing emcees emend emendation emendations emended emending emends emeried emeries emeritus emery emerying emetic emetics emigre emigres emirate emirates emollient emollients emolument emoluments emote emoted emotes emoting emotionalism empathetic empirically empiricism emplacement emplacements employable employables empowerment emptily ems emu emulsification emulsified emulsifies emulsify emulsifying emus encamp encamped encamping encampment encampments encamps encapsulation encapsulations encephalitis enchanter enchanters enchantingly enchantress enchantresses enchilada enchiladas encirclement enclave enclaves encoder encoders encouragingly encroachment encroachments encrust encrustation encrustations encrusted encrusting encrusts encrypt encrypts encyclical encyclicals encyclopedic endearingly endlessness endocrine endocrines endorser endorsers endue endued endues enduing endurable enervate enervated enervates enervating enervation enfeeble enfeebled enfeebles enfeebling enfold enfolded enfolding enfolds enforceable enforcer enforcers enfranchise enfranchised enfranchisement enfranchises enfranchising engagingly engorge engorged engorges engorging enhancer enigmatically enjoin enjoined enjoining enjoins enlarger enlargers enlistee enlistees enmesh enmeshed enmeshes enmeshing ennoble ennobled ennoblement ennobles ennobling ennui enormousness enrapture enraptured enraptures enrapturing ensconce ensconced ensconces ensconcing enshroud enshrouded enshrouding enshrouds enslavement ensnare ensnared ensnares ensnaring entente ententes entertainingly enthrone enthroned enthronement enthronements enthrones enthroning enthuse enthused enthuses enthusing enticings entitlement entitlements entomb entombed entombing entombment entombs entomological entourage entourages entrapment entrenchment entrenchments entrepreneur entrepreneurial entrepreneurs entryway entryways enumerable enumerations envelopment enviably enviousness environmentalism environmentalist environmentalists envision envisioned envisioning envisions epee epees epicure epicurean epicureans epicures epidemiology epidermal epiglottis epiglottises epigram epigrammatic epigrams episcopacy episcopal episcopate episodic epistemology epistle epistles epistolaries epistolary epochal epoxied epoxies epoxy epoxying equability equable equably equestrienne equestriennes equidistant equinoctial equipage equipages equipoise equitably equivalences equivocally equivocate equivocated equivocates equivocating equivocation equivocations eradication erasures ere erectile erectly erectness erg ergonomics ergs ermine ermines erogenous erosive erotica erotically eroticism errata erratas erratum ersatz ersatzes eruditely erudition erythrocyte erythrocytes es escalations escapee escapees escapist escapists escarole escaroles escarpment escarpments eschatology eschew eschewed eschewing eschews escrow escrows escutcheon escutcheons esoterically espadrille espadrilles espied espies esplanade esplanades espousal espouse espoused espouses espousing espresso espressos espy espying esquire esquires essayist essayists ester esters esthetically estimable estimator estimators estrange estranged estranges estranging estuaries estuary eta etcher etchers ethereally ethnically ethnicity ethnological ethnologist ethnologists ethnology etiologies etiology etude etudes etymologist etymologists eucalypti eucalyptus eucalyptuses eugenics eulogistic eunuch eunuchs euphemistic euphemistically euphony euphoria euphoric eurekas euro euros eutectic evacuee evacuees evanescent evasively evasiveness evenhanded eventfully eventfulness eventide eventuate eventuated eventuates eventuating everglade everglades everyplace evildoer evildoers evilly evince evinced evinces evincing eviscerate eviscerated eviscerates eviscerating evisceration evocation evocations ewer ewers ex exacerbation exactingly exactitude exactness excavator excavators exceptionable exchangeable exchequer exchequers excision excisions excitability excitation excitedly excitingly exclamatory exclusiveness exclusivity excoriate excoriated excoriates excoriating excoriation excoriations excrescence excrescences excreta excretion excretions excretories excretory excruciatingly exculpate exculpated exculpates exculpating exec execrable execrate execrated execrates execrating execs executrices executrix exegeses exegesis exemplar exemplars exemplification exemplifications exes exhalation exhalations exhaustible exhaustively exhibitionism exhibitionist exhibitionists exhibitor exhibitors exhumation exhumations exigencies exigency exigent exigents exiguous existentialism existentialist existentialists exorbitance exorbitantly exorcise exorcised exorcises exorcising exorcism exorcisms exorcist exorcists exotically expansionist expansionists expansively expansiveness expatiate expatiated expatiates expatiating expatriation expectantly expectorant expectorants expectorate expectorated expectorates expectorating expectoration expedience expediences expediently expediter expediters expeditionary expeditious expeditiously expensively experimenter experimenters expertness expiate expiated expiates expiating expiation explicate explicated explicates explicating explication explications explicitness exploitative exploiter exploiters exploratory explosively explosiveness expo exponentiation exportation expos expository expostulate expostulated expostulates expostulating expostulation expostulations expressible expressionism expressionist expressionists expressionless expressiveness expropriate expropriated expropriates expropriating expropriation expropriations expunge expunged expunges expunging expurgate expurgated expurgates expurgating expurgation expurgations exquisitely extemporaneously extempore extempores extensional extensiveness extenuate extenuated extenuates extenuating extenuation exterminator exterminators extinguishable extirpate extirpated extirpates extirpating extirpation extortionist extortionists extractor extractors extramarital extraneously extrasensory extravaganza extravaganzas extremism extrication extrinsic extrinsically extroversion extroverted extrude extruded extrudes extruding extrusion extrusions exuberantly exultantly eyeful eyefuls eyeglass eyeglasses eyelet eyelets eyeliner eyeliners eyepiece eyepieces eyestrain eyeteeth eyetooth f fa fabled fabulously facetiously facetiousness facially facilitation facings factional factionalism factitious factotum factotums faddish fag fagged fagging fags fain fained fainer fainest faining fains fainthearted faintness fairground fairgrounds fairway fairways fairyland fairylands faithlessly faithlessness faker fakers fakir fakirs falconer falconers fallaciously fallibility fallibly falloff falloffs fallow fallowed fallowing fallows falseness falsifiable falteringly falterings familial familiarly famish famished famishes famishing famously fanatically fanaticism fanciers fancifully fancily fanciness fannies fanny fanzine farcical farina farinaceous farmhand farmhands farmhouse farmhouses farmyard farmyards farrow farrowed farrowing farrows farsighted farsightedness fart farted farthing farthings farting farts fastidiously fastidiousness fastness fastnesses fatalism fatalist fatalists fatefully fathead fatheads fatherless fathomable fathomless fatness fattenings fatuously fatuousness faultfinding faultily faultiness faultlessly faun fauns fax faxed faxes faxing fealty fearfulness fearlessness feasibly featherbedding featherweight featherweights featureless febrile fecal feckless fecund fecundity federally federate federated federates federating fedora fedoras feebleness feebly feedbag feedbags feedings feelingly feistier feistiest feisty feldspar felicities felicitous felicity fellatio felonious femoral fems femur femurs fencer fencers fennel fens fer feral ferociousness ferric ferrous ferrule ferrules ferryboat ferryboats fervency fervid fervidly fest festal festals festively fests feta fetchingly fetishism fetishist fetishistic fetishists fetlock fetlocks fettle feudalistic fevered fey fiat fiats fibroid fibrous fibula fibulae fiches fickleness fiddlesticks fiduciaries fiduciary fie fief fiefs fielder fielders fieldwork fieriness fies fife fifes figurine figurines filamentous filbert filberts filial filibuster filibustered filibustering filibusters filigree filigreed filigreeing filigrees filings fillers fillings fillip filliped filliping fillips filmmaker filmmakers filmstrip filmstrips filterable filthiness filtrate filtrated filtrates filtrating filtration finagle finagled finagler finaglers finagles finagling finder finders fineness finery fingerboard fingerboards fingerings finis finises finisher finishers finitely fink finked finking finks finnier finniest finny fireball fireballs firebomb firebombed firebombing firebombs firebrand firebrands firebreak firebreaks firebug firebugs firefight firefighting firefights firehouse firehouses fireplug fireplugs firepower firestorm firestorms firetrap firetraps firewall firewalled firewalling firewalls firewater firmament firmaments firstborn firstborns firth firths fiscally fishbowl fishbowls fishers fishhook fishhooks fishnet fishnets fishtail fishtailed fishtailing fishtails fishwife fishwives fistful fistfuls fisticuffs fitfully fitly fitters fittingly fixate fixated fixates fixating fixative fixatives fixedly fixer fixers fixings fixity fizzier fizziest fjord fjords flab flabbergast flabbergasted flabbergasting flabbergasts flabbiness flaccid flack flacks flagella flagellate flagellated flagellates flagellating flagellation flagellum flagon flagons flagstaff flagstaffs flakiness flaks flambe flambeed flambeing flambes flamenco flamencos flamethrower flamethrowers flamings flammability flan flange flanges flapper flappers flashbulb flashbulbs flashers flashgun flashguns flashily flashiness flatbed flatbeds flatboat flatboats flatcar flatcars flatfeet flatfish flatfishes flatfoot flatfooted flatfooting flatfoots flatiron flatirons flatteringly flattop flattops flatulence flatulent flatware flautist flautists flax flaxen flay flayed flaying flays fleetingly fleetness fleshlier fleshliest fleshly flextime flibbertigibbet flibbertigibbets flightiness flimflam flimflammed flimflamming flimflams flimsily flintier flintiest flintlock flintlocks flinty flippancy flippantly flirtatiously floater floaters floe floes floggings floodgate floodgates floodlit floorboard floorboards floozies floozy flophouse flophouses floppiness floridly florin florins flotation flotations flotsam flourier flouriest floury flowerbed flowerbeds floweriness flowerpot flowerpots flub flubbed flubbing flubs fluffiness fluidity fluidly flukier flukiest fluky flume flumes flummox flummoxed flummoxes flummoxing fluoresce fluoresced fluorescence fluoresces fluorescing fluoridate fluoridated fluoridates fluoridating fluoridation fluoride fluorides fluorine fluorite fluorocarbon fluorocarbons fluoroscope fluoroscopes fluttery flyby flybys flycatcher flycatchers flyleaf flyleaves flypaper flypapers flysheet flyspeck flyspecked flyspecking flyspecks flyswatter flyswatters flyweight flyweights flywheel flywheels fob fobbed fobbing fobs foetid fogbound fogginess foldaway folio folios follicle follicles fomentation fondant fondants fondue fondues fooleries foolery foolhardiness foolscap footballer footballers footbridge footbridges footfall footfalls footlocker footlockers footloose footman footmen footrest footrests footsie footsies footsore fop fopped fopping foppish fops forager foragers forbiddingly forcefulness forebear forebears forecaster forecasters forecastle forecastles foreclose foreclosed forecloses foreclosing foreclosure foreclosures forefeet forefoot forehand forehands foreknowledge forelock forelocks foremast foremasts forename forenames forenoon forenoons foreordain foreordained foreordaining foreordains foresail foresails foreshorten foreshortened foreshortening foreshortens forestation forester foresters forevermore forewoman forewomen forfeiture forgather forgathered forgathering forgathers forgetfully forgettable forgivable forklift forklifts forlornly formaldehyde formalism formidably formlessly formlessness formulaic fornicate fornicated fornicates fornicating forsooth forsythia forsythias forthrightly forthrightness fortissimo fortnights fortuitously forwardness foully foulness fountainhead fountainheads fourfold fourscore foursome foursomes foursquare fourthly foxglove foxgloves foxhole foxholes foxhound foxhounds foxtrot foxtrots foxtrotted foxtrotting fractals fractionally fractious fractiously fragrantly framer framers franchisee franchisees franchiser franchisers frankincense frankness frappe frappes frat fraternally fratricide fratricides frats fraudulence frazzle frazzled frazzles frazzling freakier freakiest freakish freaky freebase freebased freebases freebasing freebie freebies freebooter freebooters freedman freedmen freehold freeholder freeholders freeholds freelanced freelancer freelancers freelances freelancing freeload freeloaded freeloader freeloaders freeloading freeloads freeman freemen freestanding freestyle freestyles freethinker freethinkers freethinking freewheel freewheeled freewheeling freewheels freewill frenetic frenetically frenziedly fresco frescoes freshet freshets fretfulness fretwork friable fricassee fricasseed fricasseeing fricassees fridge fridges friendless frigidly fripperies frippery friskily friskiness frivolously frizz frizzed frizzes frizzing frizzle frizzled frizzles frizzling frogman frogmen frolicsome frontally frontiersman frontiersmen frontispiece frontispieces frostily frostiness frowzier frowziest frowzy fructified fructifies fructify fructifying fructose fruitcake fruitcakes fruitfully fruitfulness fruitlessness frump frumpier frumpiest frumps frumpy fryer fryers fuchsia fuchsias fuck fucked fucker fuckers fucking fucks fuddle fuddled fuddles fuddling fugue fugues fullback fullbacks fulminate fulminated fulminates fulminating fulmination fulminations fulsome fumbler fumblers fumigator fumigators functionaries functionary funereal funereally fungal fungals fungicidal fungous funicular funiculars funk funked funkier funkiest funking funks funky funniness furbelow furbish furbished furbishes furbishing furriers furtherance furthermost furze fusible fusillade fusillades fusions fussbudget fussbudgets fussily fussiness fustian fustier fustiest fusty futilely futon futons futuristics futurities futurity futz futzed futzes futzing fuzzily fuzziness g gabardine gabardines gabbier gabbiest gabble gabbled gabbles gabbling gabby gad gadabout gadabouts gadded gadding gadflies gadfly gadgetry gads gaff gaffe gaffed gaffes gaffing gaffs gaggle gaggles gainfully gainsaid gainsay gainsaying gainsays gaiter gaiters galena gallantly gallbladder gallbladders galleon galleons gallium gallstone gallstones galosh galoshed galoshes galoshing galvanic galvanometer galvanometers gambol gambols gamecock gamecocks gamekeeper gamekeepers gamely gameness gamesmanship gamete gametes gamier gamiest gamin gamine gamines gamins gammas gamy gangland ganglia ganglion gangrenous gannet gannets gantlet gantlets gantries gantry gaoled gaoling gaols gapings garbageman garbanzo garbanzos gargantuan garishly garishness garlicky garner garnered garnering garners garnishee garnisheed garnisheeing garnishees garrote garroted garrotes garroting garrulity garrulously garrulousness gaslight gaslights gasohol gassier gassiest gassy gastritis gastrointestinal gastronomic gastronomical gastronomy gasworks gatecrasher gatecrashers gatepost gateposts gatherer gatherers gauche gaucher gauchest gaucho gauchos gaudily gaudiness gauntness gauzier gauziest gauzy gavotte gavottes gawkily gawkiness gayness gazebo gazebos gazer gazers gazetteer gazetteered gazetteering gazetteers gazillion gazillions gazpacho gearbox gearboxes gearshift gearshifts gearwheel gearwheels gecko geckos geek geekier geekiest geeks geeky geezer geezers geisha gelatinous gelid gelled gelling gels gemstone gemstones gendarme gendarmes genealogist genealogists generalissimo generalissimos generalities generative generically geniality genitalia genitive genitives genome genomes genteel genteeler genteelest gentian gentians gentlefolk gentlemanly gentlewoman gentlewomen gentrification gentrified gentrifies gentrify gentrifying genuflect genuflected genuflecting genuflection genuflections genuflects geocentric geode geodes geodesic geodesics geographer geographers geologic geologically geometer geometrical geometrically geophysical geophysics geopolitical geopolitics geostationary geothermal geriatric geriatrics germane germanium germicidal germinal gerontologist gerontologists gerontology gerrymander gerrymandered gerrymandering gerrymanders gerund gerunds gestate gestated gestates gestating gesticulation gesticulations gesundheit getup gewgaw gewgaws ghastliness gherkin gherkins ghostliness ghostwrite ghostwriter ghostwriters ghostwrites ghostwriting ghostwritten ghostwrote ghoulish giantess giantesses gibbet gibbeted gibbeting gibbets gibbon gibbons giblet giblets giddily gigabyte gigabytes giggler gigglers gigglier giggliest giggly gigolo gigolos gimcrack gimcracks gimlet gimleted gimleting gimlets gimmickry gimmicky gimpier gimpiest gimpy gingersnap gingersnaps gingivitis ginkgo ginkgoes ginseng gird girded girding girds girlishly girt girted girting girts giveaway giveaways glacially gladiatorial gladiola gladiolas gladioli gladiolus gladness glamorously glaringly glassful glassfuls glaucoma glazier glaziers gleamings gleeful gleefully glibness glimmerings glissandi glissando glitch glitches glitterings glittery glitz glitzier glitziest glitzy gloaming gloamings glob globed globetrotter globetrotters globing globs glockenspiel glockenspiels gloomily gloominess glop glopped glopping glops glossiness glottis glottises glowingly glowworm glowworms gluey gluier gluiest glumly glumness gluten glutinous gluttonous gluttonously glycerol glycogen glyph gnarlier gnarliest gnarly gneiss gnomish goalpost goalposts goaltender goaltenders goatherd goatherds goatskin goatskins gobbledygook gobbler gobblers goddamn goddaughter goddaughters godforsaken godhood godliness godson godsons gofer gofers goggled goggling goings goldbrick goldbricked goldbricking goldbricks goldenrod goldfinch goldfinches gollies golly gonad gonads gondolier gondoliers goober goobers goodbyes goodlier goodliest goodly gook gooks goop gooseberries gooseberry gorgeously goriness gorse goshes gossipy gotta gouger gougers gourmand gourmands goutier goutiest gouty governable governance governorship govs gracefulness gracelessly gracelessness grackle grackles grad graders grads grafter grafters grail grainier grainiest grainy grammarian grammarians gramme grammes granaries granary granddad granddads grandee grandees grandiloquence grandiloquent grandma grandmas grandness grandpa grandpas grange granges granularity granulate granulated granulates granulating granulation graphologist graphologists graphology grapnel grapnels grassland gratefulness gratis gravelly graybeard graybeards grayish grayness greasepaint greasiness grebe grebes greengrocer greengrocers greenish greenness greensward gregariously gregariousness grenadier grenadiers griddlecake griddlecakes gridlock gridlocked gridlocking gridlocks grievously griffin griffins grimness gringo gringos grippe grippes grist gristlier gristliest gristly grog groggily grogginess grommet grommets grosbeak grosbeaks grossness grotesquely grouchiness groundbreaking groundbreakings grounder grounders groundhog groundhogs groundings groundlessly groundswell groundswells groupie groupies grout grouted grouting grouts grownup grownups grubbiness grubstake grudgingly grudgings gruesomely gruffness grumbler grumblers grumpily grumpiness grunge grungier grungiest grungy gs guacamole guano guarantied guaranties guaranty guarantying guardedly guardhouse guardhouses guardianship guardrail guardrails guardroom guardrooms guardsman guardsmen guava guavas guesser guessers guesstimate guesstimated guesstimates guesstimating guff guilder guilders guileful guileless guiltiness guineas guitarists gulag gulags gullibility gumbo gumbos gunboat gunboats gunfight gunfighting gunfights gunfought gunk gunnery gunny gunnysack gunnysacks gunpoint gunrunner gunrunners gunrunning gunslinger gunslingers gunsmith gunsmiths gunwale gunwales gurney gurneys gushier gushiest gushy gusset gusseted gusseting gussets gustatory gusto gutless gutsier gutsiest gutsy guttersnipe guttural gutturals guzzler guzzlers gymnastic gymnosperm gymnosperms gyp gypped gypping gyps gypsies gypsum gypsy gyro gyros h haberdasher haberdasheries haberdashers haberdashery habitability habituate habituated habituates habituating habituation habitue habitues hacienda haciendas hackle hackles hafnium haft hafts haggler hagglers haiku hailstorm hailstorms hairbreadth hairbreadths hairbrush hairbrushes hairdressing hairiness hairless hairnet hairnets hairpiece hairpieces hairpin hairpins hairsbreadth hairsbreadths hairsplitting hairspring hairsprings hairstyle hairstyles hairstylist hairstylists hake hakes halberd halberds halcyon halfback halfbacks halfhearted halfheartedly halfheartedness halfpence halfpennies halfpenny halftime halftimes halitosis hallow hallowed hallowing hallows hallucinate hallucinated hallucinates hallucinating hallucinatory hallucinogen hallucinogenic hallucinogenics hallucinogens halogen halogens haltingly haltings halyard halyards hammerhead hammerheads hammerings handball handballs handbill handbills handcar handcars handcart handcarts handcraft handcrafted handcrafting handcrafts handgun handguns handicapper handicappers handily handiness handmaid handmaiden handmaidens handmaids handpick handpicked handpicking handpicks handset handsets handshakes handshaking handsomely handsomeness handspring handsprings handstand handstands handwork handwritten handyman handymen hangdog hangman hangmen hangnail hangnails hank hankerings hankie hankies hanks hansom hansoms haphazardly happenstance happenstances harbinger harbingers hardbacks hardball hardcover hardcovers hardener hardeners hardheaded hardheadedly hardheadedness hardhearted hardheartedly hardheartedness hardily hardiness hardness hardtack hardtop hardtops harelip harelips harlequin harlequins harmfulness harmlessness harmonically harmonics harmoniously harmoniousness harpies harpy harridan harridans hashish hasp hasps hassock hassocks hastiness hatchback hatchbacks hatcheries hatchery hatchway hatchways hatefulness hater haters hath hatter hatters hauler haulers haunch haunched haunches haunching hauntingly hauteur haversack haversacks haw hawed hawing hawker hawkers hawkish haws hawser hawsers hawthorn hawthorns haycock haycocks hayloft haylofts haymow haymows hayseed hayseeds hazelnut hazelnuts hazily haziness hazings headband headbands headboard headboards headdress headdresses headgear headhunter headhunters headless headlock headlocks headmasters headmistress headmistresses headset headsets headwaiter headwaiters headwaters headwind headwinds headword headwords healthfully healthfulness healthily healthiness hearer hearers hearken hearkened hearkening hearkens heartiness heartland heartlands heartlessly heartlessness heartrending heartsick heartstrings heartthrob heartthrobs heartwarming heathenish heaths heatstroke heavenward heavenwards heavyset heck hectare hectares hectically hector hectored hectoring hectors hedgerow hedgerows hedonism hedonist hedonistic hedonists heedful heedlessly heedlessness heehaw heehawed heehawing heehaws heft hefted hefting hefts hegemony heinously heinousness heiress heiresses heist heisted heisting heists helical helices heliotrope heliotropes helix hellebore hellhole hellholes hellion hellions hellishly helmsman helmsmen helot helots helpfulness helplessness helpmate helpmates hemispheric hemispherical hemline hemlines hemorrhoid hemorrhoids hempen hemstitch hemstitched hemstitches hemstitching henceforward henna hennaed hennaing hennas henpeck henpecked henpecking henpecks hep hepatic hepatics hepper heppest heps heptagon heptagons heraldic heraldry herbaceous herbage herbal herbalist herbalists herbicide herbicides herbivore herbivores herculean herdsman herdsmen hereabout hereof hereto heretofore hereupon hermaphrodites hermaphroditic hermetic hermetically hermetics hermitage hermitages heroically heroics herringbone herringboned herringbones herringboning hertz hesitantly hesitatingly heterodox heterodoxy heterogeneity heuristics hewer hewers hex hexameter hexameters hexed hexes hexing hibachi hibachis hibiscus hibiscuses hickey hickeys hidebound hideousness hideout hideouts hie hied hieing hierarchically hies highball highballs highborn highboy highboys highchair highchairs highfalutin highlighter highlighters highness hightail hightailed hightailing hightails highwayman highwaymen hijacker hijackers hijackings hilariously hillock hillocks hilltop hilltops hindmost hindquarter hindquarters hippo hippos hireling hirsute histamine histamines histograms histrionic histrionics hitter hitters hoarfrost hoarier hoariest hoariness hoarsely hoary hoaxer hoaxers hob hobbyist hobbyists hobnail hobnailed hobnailing hobnails hobs hockshop hockshops hod hods hoedown hoedowns hogan hogans hoggish hogshead hogsheads hogwash hokey hokier hokiest hokum holdings holdout holdouts holdover holdovers holistic hollowly hollowness hollyhock hollyhocks hologram holograms holograph holographic holographs holography homburg homburgs homebodies homebody homeboy homeboys homecoming homecomings homegrown homelessness homeliness homemaker homemakers homeowner homeowners homepage homepages homer homered homering homeroom homerooms homers homesteader homesteaders homestretch homestretches hometown hometowns homeyness homilies homily hominy homogeneity homogeneously homograph homographs homophobia homophone homophones honcho honchos honeybee honeybees honeydew honeydews honeymooner honeymooners honorarium honorariums honorific honorifics hooch hoodoo hoodooed hoodooing hoodoos hooey hookah hookahs hooker hookers hookier hookiest hookup hookups hookworm hookworms hooky hooligan hooliganism hooligans hoopla hooters hopefulness hopelessness hoppers hormonal hornless hornpipe hornpipes horology horridly horseflies horsefly horsehair horsehide horsemanship horsemen horsetail horsetails horsewhip horsewhipped horsewhipping horsewhips horsewoman horsewomen horsey horsier horsiest horticulturist horticulturists hos hosanna hosannas hospice hospices hospitably hosteler hostelers hostelries hostelry hostilely hostilities hostler hostlers hotcake hotcakes hotelier hoteliers hotheadedly hotheadedness hothouse hothoused hothouses hothousing hotness hotshot hotshots housebound housebreak housebreaking housebreaks housebroke housebroken houseclean housecleaned housecleaning housecleans housecoat housecoats houseflies housefly householder householders househusband househusbands housekeeping housemaid housemaids housemother housemothers houseplant houseplants housetop housetops housewares hovercraft howdah howdahs howdied howdies howdy howdying howitzer howitzers howler howlers howsoever hubbies hubby hubcap hubcaps hubris huckleberries huckleberry huckster huckstered huckstering hucksters huffily hugeness huhs hula hulaed hulaing hulas humaneness humanistic humanists humanitarianism humankind humanness humanoid humanoids humbleness humblings humbugged humbugging humbugs humdinger humdingers humeri humerus humidifier humidifiers humidor humidors hummock hummocked hummocking hummocks humongous humpback humpbacked humpbacks humus hunchbacked hundredfold hundredfolds hundredweight hundredweights hungover hunker hunkered hunkering hunkers huntress huntresses huntsman huntsmen hurdler hurdlers hurler hurlers husbandry husker huskers hussar hussars hussies hussy hustings hydra hydrangea hydrangeas hydras hydrate hydrated hydrates hydrating hydraulically hydrocarbon hydrocarbons hydroelectricity hydrofoil hydrofoils hydrogenate hydrogenated hydrogenates hydrogenating hydrology hydrolysis hydrometer hydrometers hydrophobia hydroponic hydroponics hydrosphere hydrotherapy hygienically hygienist hygienists hygrometer hygrometers hying hymen hymens hype hyped hyper hyperactive hyperactives hyperactivity hyperbola hyperbolas hyperbolic hypercritical hypercritically hypermarket hypersensitive hypersensitivities hypersensitivity hyperspace hypertext hyperventilate hyperventilated hyperventilates hyperventilating hyperventilation hypes hyphenations hyping hypnoses hypnotically hypo hypoallergenic hypocritically hypodermic hypodermics hypoglycemia hypoglycemic hypoglycemics hypos hypothalami hypothalamus hypothermia hypothetically hysterectomies hysterectomy hysteresis i iamb iambic iambics iambs ibex ibexes ibis ibises ibuprofen icebound icebox iceboxes icecap icecaps icily iciness ickier ickiest icky iconoclast iconoclastic iconoclasts idealism idealistically ideogram ideograms ideograph ideographs ideologist ideologists ides idiomatically idiotically idleness idlers idolater idolaters idolatrous idolatry ids idyll idylls iffier iffiest iffy igneous ignoble ignobly ignominies ignominious ignominiously ignominy ignoramus ignoramuses ignorantly ilks illegalities illegality illegibility illegitimacy illegitimately illiberal illicitly illicitness illogically illumine illumined illumines illumining illusive imaginably imaginatively imam imams imbalanced imbecilic imbecilities imbecility imbibe imbibed imbibes imbibing imbroglio imbroglios imbue imbued imbues imbuing immaculateness immanence immanent immaturely immediacy immemorial imminence immobility immoderate immoderately immodest immodestly immodesty immolate immolated immolates immolating immolation immorally immortally immovably immunology immure immured immures immuring immutability immutable immutably impala impalas impalement impalpable impanel impanels impassively impassivity impeachment impeachments impeccability impeccably impecunious impecuniousness impedimenta impenetrability impenetrably impenitence impenitent impenitents imperatively imperialistic imperialists imperially imperious imperiously imperiousness imperishable imperishables impermanence impermanent impermeable impermissible impersonator impersonators impertinently imperturbability imperturbable imperturbably impetigo impetuosity impieties impiety impingement impious impiously impishly impishness implacability implacably implantation implausibilities implausibility implausibly implode imploded implodes imploding implosion implosions impolitely impoliteness impolitenesses impolitic imponderable imponderables importer importers importunate importunated importunates importunating importune importuned importunes importuning importunity imposingly imposture impostures impotently impoverishment impracticable impracticably impracticality imprecation imprecations imprecisely imprecision impregnability impregnably impregnation impresario impresarios impressionism impressionist impressionistic impressionists impressiveness imprimatur imprimaturs improvable improvidence improvident improvidently imprudence imprudent impudently impugn impugned impugning impugns impulsion impulsiveness impurely imputation imputations impute imputed imputes imputing inaccessibility inaccurately inadvertence inamorata inamoratas inanely inanities inanity inappropriately inapt inarticulately inattention inattentive inaudibly inboard inboards inbound inbounded inbounding inbounds incalculably incapability incautious inchoate inchoated inchoates inchoating incineration incipient incise incised incises incising incisively incisiveness incivilities incivility inclemency inclement inclusively incombustible incommensurate incommunicado incomparably incompetently incompletely incompleteness incomprehensibly inconceivably inconclusively incongruously inconsequentially inconsiderately inconsiderateness inconsistently inconspicuously inconspicuousness inconstancy inconstant incontestable incontestably incontinence incontinent incontrovertible incontrovertibly incorporeal incorrectness incorrigibility incorrigibly incorruptibility incorruptible incorruptibles increasings incredibility incredulously incrimination incriminatory incrustation incrustations incubus incubuses inculcate inculcated inculcates inculcating inculcation inculpate inculpated inculpates inculpating incumbencies incumbency incurably incurious incursion incursions indebtedness indecently indecipherable indecisively indecisiveness indecorous indefatigable indefatigably indefensibly indefinably indelicacies indelicacy indelicately indemnification indemnifications indemnified indemnifies indemnify indemnifying indemnities indemnity indenture indentured indentures indenturing indescribably indestructibly indeterminable indeterminacy indeterminately indictable indifferently indigence indigent indigents indirectness indiscernible indiscreetly indispensably indisposition indispositions indisputably indissoluble indistinctly indistinctness individualistic indivisibility indivisibly indolently indomitably indubitable indubitably inductance inductee inductees inductive indulgently industrialism industrially industriously industriousness inebriate inebriated inebriates inebriating inebriation ineducable ineffable ineffably ineffectively ineffectiveness ineffectually inelastic inelegance inelegantly ineligibility ineluctable ineluctably ineptly ineptness inequitable inequities inequity inertly inertness inescapably inessential inessentials inestimable inestimably inevitability inexcusably inexhaustibly inexpedient inexpensively inexpert inexperts inexpressible inextinguishable inextricable infallibility infallibly infamously infanticide infanticides infantryman infantrymen infarction infatuate infatuated infatuates infatuating infectiously infectiousness infelicitous inferential infernal infertility infielder infielders infighting infiltrator infiltrators infinitesimally infinitude inflatables inflect inflected inflecting inflectional inflects inflexibility inflexibly inflexion infliction inflorescence inflow influentially infomercial infomercials infotainment infrastructures infrequency infuriatingly ingenue ingenues ingenuous ingenuously ingenuousness ingestion inglorious ingot ingots ingrate ingrates ingratiatingly ingress ingresses ingrown inhabitable inhalant inhalants inhalation inhalations inhalator inhalators inhere inhered inheres inhering inheritor inheritors inhumanely inhumanly inimical inimically inimitable inimitably iniquities iniquitous iniquity injector injectors injudicious inkblot inkblots inkiness inkwell inkwells inmost innately innocuously innovate innovated innovates innovating innovator innovators inoffensively inoperable inordinately inorganic inpatient inpatients inquietude inquirer inquirers inquiringly inquisitively inquisitiveness inquisitor inquisitors inroad inroads insatiably inscrutably inseam inseams insectivore insectivores insectivorous insecurely inseminate inseminated inseminates inseminating insemination insensate insensibility insensible insensibly insensitively insentience insentient inseparability inseparably inset insets insetting inshore insidiously insidiousness insightful insignificantly insistently insole insolently insoles insolubility insolvable insomniac insomniacs insouciance insouciant inspirational instigator instigators instinctively instructional instructively instrumentalist instrumentalists instrumentality instrumentation insufferably insufficiency insularity insuperable insupportable insureds insurgence insurgences insurgencies insurgency insurrectionist insurrectionists intaglio intaglios intangibly integrator integument integuments intellectualism intelligentsia intelligibility intemperance intemperate intendeds intensification intensifier intensifiers intensively intently intentness interbred interbreed interbreeding interbreeds interceptor interceptors intercession intercessions intercessor intercessors interchangeably intercollegiate interconnected interconnecting interconnection interconnections interconnects interdenominational interdepartmental interdict interdicted interdicting interdiction interdicts interdisciplinary interfaith interferon intergalactic interlace interlaced interlaces interlacing interlard interlarded interlarding interlards interleave interleaved interleaves interleaving interleukin interlink interlinked interlinking interlinks interlocutory intermezzi intermezzo intermezzos internationalism internecine internee internees internist internists internment internship internships interoffice interpersonal interpolate interpolated interpolates interpolating interpolations interposition interpretative interpretive interrelate interrelated interrelates interrelating interrelation interrelations interrelationship interrelationships interrogative interrogatives interrogatories interrogatory interscholastic interstice interstices interurban interviewee interviewees intestate intone intoned intones intoning intoxicant intoxicants intractability intransigence intransigent intransigents intransitively intravenously intrepidly intricately intriguingly intros introspection introversion introverted intuit intuited intuiting intuits inure inured inures inuring invalidation invalidity invasive inveigh inveighed inveighing inveighs inveigle inveigled inveigles inveigling inventiveness investigative investiture investitures invidious invidiously invigoration invincibility invincibly inviolability inviolable inviolate invitational invitationals invitingly invulnerability invulnerably ionosphere ionospheres ipecac ipecacs irascibility irately irateness iridium irksome ironclad ironclads ironical ironware ironwork irradiation irrationality irrecoverable irredeemable irredeemables irregardless irregularly irrelevancies irrelevancy irrelevantly irreligious irremediable irremediably irreparably irresistibly irresolute irresolutely irresolution irresponsibly irreverently irreversibly irritatingly irruption irruptions isinglass islet islets ism isms isobar isobars isolationism isolationist isolationists isometric isometrics isomorphic isosceles isotope isotopes isotopic isotropic issuance itchiness iterated iterates iterating iterator iterators j jabberer jabberers jabot jabots jackboot jackboots jackdaws jackhammer jackhammered jackhammering jackhammers jackrabbit jackrabbits jag jaggedly jaggedness jags jailbreak jailbreaks jalapeno jalapenos jalousie jalousies janitorial japan japanned japanning japans jape japed japes japing jardiniere jardinieres jasmine jasmines jasper jauntiness jawbreaker jawbreakers jazzier jazziest jazzy jeep jeeps jeeringly jeez jejune jellybean jellybeans jeremiad jeremiads jerkily jerkin jerkins jerkwater jetsam jib jibbed jibbing jibs jigger jiggered jiggering jiggers jihad jihads jimmied jimmies jimmy jimmying jingoism jingoist jingoistic jingoists jinn jinns jinrikisha jinrikishas jitney jitneys jitterbug jitterbugged jitterbugging jitterbugs jive jived jives jiving jobber jobbers jobless joblessness jock jocked jocking jocks jockstrap jockstraps jocose jocosely jocosity jocularity jocularly jocund jocundity jocundly jodhpurs joggle joggled joggles joggling john johns joiner joiners joist joists jokingly jolliness jollity jonquil jonquils josh joshed joshes joshing jottings joule joules jounce jounced jounces jouncing journalese journalistic journeyman journeymen joust jousted jousting jousts joviality jowl jowls joyfulness joyless joyousness joyridden joyride joyrider joyriders joyrides joyriding joyrode joysticks jubilantly judgeship judicature judiciousness juggernauts juicer juicers juiciness jujitsu jujube jujubes jukebox jukeboxes julep juleps julienne julienned juliennes julienning jumpiness jumpsuit jumpsuits junco juncos junker junkers junkyard junkyards juridical jurisdictional jurisprudence jurist jurists justness k kHz kW kabob kabobs kaboom kale kaleidoscopic kamikaze kamikazes kaolin kapok kaput karakul karaoke karaokes karma katydid katydids kazoo kazoos kc kebab kebabs keenness kenned kenning kens keratin kestrel kestrels ketch ketches kettledrum kettledrums keyboarder keyboarders keypunch keypunched keypunches keypunching keystroked keystroking khan khans kibbutz kibbutzim kibitz kibitzed kibitzer kibitzers kibitzes kibitzing kibosh kicker kickers kickier kickiest kickstand kickstands kicky kidder kidders kiddie kiddied kiddies kiddo kiddos kiddying kidnappings kielbasa kielbasas killdeer killdeers killjoy killjoys kilocycle kilocycles kilohertz kiloton kilotons kilter kindergartner kindergartners kindhearted kindliness kinematic kinematics kinetic kinetics kinfolks kinglier kingliest kingly kingpin kingpins kingship kinsman kinsmen kinswoman kinswomen kippered kippering kippers kirk kirked kirking kirks kismet kisser kissers kitchenware kith kithed kithing kiths kitsch kitschy kittenish kleptomania kleptomaniac kleptomaniacs klutz klutzes klutzier klutziest klutzy knackwurst knackwursts knave knavery knaves knavish kneader kneaders knell knelled knelling knells knickknack knickknacks knightly knitter knitters knitwear knobbier knobbiest knobby knothole knotholes knowable knowledgeably knucklehead knuckleheads kohlrabi kohlrabies kook kookaburra kookaburras kooked kookier kookiest kookiness kooking kooks kooky kopeck kopecks krona krone kroner kronor kronur krypton ks kudzu kudzus kumquat kumquats l la labia labial labials labium laburnum laburnums labyrinthine lachrymal lachrymose lackadaisical lackadaisically lackey lackeys laconic laconically lactate lactated lactates lactating lactation lactic lactose lacuna lacunae laddie laddies ladings ladybird ladybirds ladyfinger ladyfingers ladyship lagers lagniappe lagniappes laity lam lama lamas lamaseries lamasery lambaste lambasted lambastes lambasting lambent lambkin lambkins lambskin lambskins lamebrain lamebrains lamely lameness lamentably laminate laminated laminates laminating lamination lammed lammer lamming lampblack lamppost lampposts lamprey lampreys lampshade lampshades lams lancer lancers lancet lancets landfall landfalls landfill landfills landholder landholders landlubber landlubbers landmass landmasses landscaper landscapers landward landwards languidly languorously lank lanker lankest lankiness lanolin lanyard lanyards lapidaries lapidary laptop laptops lapwing lapwings larboard larboards larcenous larch larches larder larders largeness largess largo largos lariat lariated lariating lariats larkspur larkspurs larval lasagna lasagnas lasciviously lasciviousness lassie lassies lassitude lasso lassoed lassoing lassos lastingly latecomer latecomers latency lateness laterally latitudinal lats latterly latticed latticework latticeworks laudably laudanum laudatory laughably laughingly launderer launderers laundress laundresses laundryman laundrymen lavishly lavishness lawbreaker lawbreakers lawfully lawfulness lawgiver lawgivers lawlessly lawlessness lawrencium laxly laxness layaway layette layettes layoff layoffs layover layovers laypeople layperson laywoman laywomen laze lazed lazes lazily lazing lazybones lea leached leaches leaching leafless leakier leakiest leanings leanness learner learners leas leasehold leaseholder leaseholders leaseholds leastwise leatherneck leathernecks leathers leaven leavened leavening leavens leavings lecher lecherous lecherously lechers lechery lecithin lees leeward leewards lefties leftism leftist leftists leftover leftovers leftwards lefty legalese legalism legalisms legate legated legatee legatees legates legating legation legations legato legatos legerdemain leggier leggiest leggy legionnaire legionnaires legit legless legman legmen legroom legrooms leguminous legwork lei leis leitmotif leitmotifs lemma lemmas lemming lemmings lemony lemur lemurs lender lenders lengthily leniently leonine leprechaun leprechauns leprous lesbianism lessee lessees lessor lessors lethally lethargically letterbox leukocyte leukocytes levelheaded levelheadedness levelness leviathan leviathans levitate levitated levitates levitating levitation lewdly lewdness lexicographer lexicographers lexicography liaise liaised liaises liaising lib libation libations libbed libbing liberality liberator liberators libertarians libertine libertines libidinous libido libidos librettist librettists librettos libs licensee licensees licentiate licentiates licentious licentiously licentiousness licit lickings lidded lief liefer liefest liefs liege lieges lien liens lieutenancy lifeblood lifer lifers lifesaver lifesavers lifesaving lifespans lifework lifeworks liftoff liftoffs ligatured ligaturing lightheaded lighthearted lightheartedly lightheartedness lignite likableness limbless limboed limboing limbos limeade limeades limier limiest limitings limn limned limning limns limo limos limpet limpets limpid limpidity limpidly limply limpness limy linage linden lindens lineal lineally lineament lineaments linebacker linebackers lineman linemen linens linesman linesmen lineup lineups lingerer lingerers lingeringly lingerings lingual linkages linkup linkups linnet linnets linseed lintel lintels lionhearted lipid lipids liposuction lipread lipreading lipreads liquefaction liquidator liquidators liquidity lira lire lisle lissome listlessly listlessness litchi litchis lite literati lites lithograph lithographed lithographer lithographers lithographic lithographing lithographs lithography lithosphere lithospheres litigant litigants litigate litigated litigates litigating litigious litigiousness litmus littleness littoral littorals livability livelong livelongs liveried liveries liverwurst livery lividly llano llanos lo loaders loamier loamiest loamy loaner loaners loanword loanwords loathsomeness lobotomies loch lochs loci lockable lockjaw lockout lockouts lockstep lockup lockups loco locoweed locoweeds locus locution locutions lode lodes lodestar lodestars lodestone lodestones loftily loganberries loganberry logarithms logbook logbooks loge loges loggerhead loggerheads loggers logicians logistic logistical logistically logistics logjam logjams logos logotype logotypes logrolling loner loners longboat longboats longhair longhairs longhorn longhorns longingly longitudinally longtime loofah lookalike lookalikes loopier loopiest loopy looseness looter looters lopsidedly lopsidedness loquacious loquacity lordlier lordliest lordly lordship lordships lorgnette lorgnettes lorn lotto loudmouth loudmouthed loudmouths lousiness lout loutish louts lovebird lovebirds loveless lovelorn lovemaking lovesick lowbrow lowbrows lowercase lowish lowland lowlands lowliness lowness lox loxed loxes loxing loyalist loyalists loyally ls luau luaus lubber lubbers lube lubed lubes lubing lubricator lubricators lucidity lucidly lucidness luckiness luckless lucratively lucre ludicrousness lugubrious lugubriously lugubriousness lumbago lumbar lumberman lumbermen lumberyard lumberyards luminescence luminescent luminosity luminously lummox lummoxes lumpiness lumpish lunchbox lunchboxes luncheonette luncheonettes lunchroom lunchrooms lunchtimes lupus luridly luridness lusciously lusciousness lushness lustful lustfully lustily lustiness luxuriance luxuriantly luxuriously luxuriousness lyceum lyceums lymphoma lymphomas lynchings lynx lynxes lyrically lyricist lyricists macadam macaroon macaroons macaw macaws macerate macerated macerates macerating maceration machination machinations machismo mackinaw mackinaws mackintosh mackintoshes macrame macro macrobiotic macrobiotics macrocosm macrocosms macron macrons macros maddeningly madders mademoiselle mademoiselles madras madrases madrigal madrigals madwoman madwomen maestro maestros magisterial magisterially magma magnesia magnetically magneto magnetos magnetosphere magnification magnifications magnificently magnifier magnifiers magnums maharajah maharajahs maharani maharanis maharishi maharishis mahatma mahatmas maidenhair maidenhead maidenheads maidenhood maidenly maidservant maidservants mailer mailers mailings mainlined mainlines mainlining mainmast mainmasts mainsail mainsails mainspring mainsprings mainstreamed mainstreaming mainstreams majorette majorettes majorly makings maladjustment maladroit malaise malapropism malapropisms malarial malarkey malcontent malcontents malediction maledictions malefactor malefactors maleness malevolently malfeasance malformation malformations malfunctioned malfunctioning malfunctions malignantly malignity malinger malingered malingerer malingerers malingering malingers malleability mallow mallows malnourished malodorous malteds maltreatment mambo mamboed mamboing mambos mammalians mammary mammogram mammograms mammography mammon manageability manatee manatees mandarin mandarins mandrake mandrakes mandrill mandrills manege maneged maneges maneging manful manfully manganese manhunt manhunts manics manikin manikins manipulative manipulator manipulators manna mannered mannerly mannishly mannishness manorial manque mansard mansards manse manservant manses mantilla mantillas mantis mantises mantissa mantra mantras manumit manumits manumitted manumitting marabou marabous maraca maracas marathoner marathoners maraud marauded marauder marauders marauding marauds marchers marchioness marchionesses margarita margaritas marginalia marginals maria mariachi mariachis marimba marimbas marinade marinaded marinades marinading marjoram markdown markdowns marketability marketer marketers marksmanship markup markups marlin marlins marmoset marmosets marmot marmots marquess marquesses marquetry marquis marquise marquises marriageable marrieds marten martens martinet martinets martini martinis martins marzipan masculinity masher mashers masochism masochistic masonic masque masquerader masqueraders masques masseur masseurs masseuse masseuses massiveness mastectomies mastectomy masterfully masterstroke masterstrokes masterwork masterworks masthead mastheads mastication mastiff mastiffs mastodon mastodons mastoid mastoids masturbate masturbated masturbates masturbating matchbox matchboxes matchmaking matchstick matchsticks materialistically materially materiel maternally matins matriarchies matriarchy matricide matricides mattock mattocks maturation maturely matzo matzoh matzohs matzos matzot matzoth maunder maundered maundering maunders maven mavens maw mawed mawing mawkish mawkishly maws maxed maxes maxilla maxillae maxillary maximally maximals maxing mayday maydays mayflies mayflower mayflowers mayfly mayo mayoral mayoralty maypole maypoles mead meadowlark meadowlarks meagerly meagerness mealtime mealtimes meaningfully meanly meanness measurably measureless meatball meatballs meatier meatiest meatloaf meatloaves meaty mecca meccas mechanistic medial medians medic medicinally medics meditative meditatively medulla medullas meetinghouse meetinghouses meg megacycle megacycles megahertz megalith megaliths megalomania megalomaniacs megalopolis megalopolises megs melancholia melancholic melancholics melange melanges melanin melanoma melanomas meld melded melding melds melee melees mellifluous mellifluously mellowness melodically melodiously melodiousness melodramatically meltdown meltdowns membranous memorabilia menacingly menage menages mendacious mendacity mender menders mendicant mendicants menfolk menhaden menially meningitis menopausal menorah menorahs menservants menses menswear mentholated merchantman merchantmen mercurial mercuric meretricious merganser mergansers merino merinos meritocracies meritocracy meritorious meritoriously merman mermen merriness merrymaker merrymakers merrymaking mesa mesas mescal mescaline mescals mesdemoiselles mesmerism mesquite mesquites messiah messiahs messieurs messily messiness mestizo mestizos metacarpal metacarpals metacarpi metacarpus metallurgical metallurgist metallurgists metamorphic metamorphism metamorphosed metamorphosing metastases metastasis metatarsal metatarsals meteoroid meteoroids meteorological methadone methane methanol methinks methodically methodological methodologies methought meticulously meticulousness metier metiers metrical metrically metrication metrics metronome metronomes mettlesome mewl mewled mewling mewls mi miasma miasmas mica microbiologist microbiologists microchip microchips microcosm microcosms microeconomics micron microns microprocessors microscopically microscopy microsurgery mid midair middies middlebrow middlebrows middleweight middleweights middling middy midge midges midland midlands midmost midmosts midpoint midpoints midshipman midshipmen midterm midterms midtown midweek midweeks midwiferies midwifery midwinter midyear midyears miff miffed miffing miffs mightily mightiness mil milch mildness milepost mileposts miler milers milieu milieus militantly militarism militarist militaristic militarists militiaman militiamen milkiness milkmaid milkmaids milkshake milksop milksops milkweed milkweeds millage millennial millennium millenniums millet millipede millipedes millrace millraces millstone millstones milquetoast milquetoasts mils mimeograph mimeographed mimeographing mimeographs mimetic mimosa mimosas minaret minarets minatory mindfully mindfulness mindlessness minefields mineralogist mineralogists mineralogy minestrone minesweeper minesweepers mini miniaturist miniaturists minibike minibikes minicam minicams minicomputers minim minimalists minims minis miniseries miniskirt miniskirts ministrant ministrants ministration ministrations minivan minivans minster mintier mintiest minty minuend minuends minutely minuteman minutemen minuteness minutia minutiae minx minxes mirthful mirthfully mirthless misalignment misalliance misalliances misanthrope misanthropes misanthropic misanthropist misanthropists misanthropy misapplication misapplied misapplies misapply misapplying misapprehend misapprehended misapprehending misapprehends misapprehensions misbegotten miscalculate miscalculated miscalculates miscalculating miscalculation miscalculations miscall miscalled miscalling miscalls miscast miscasting miscasts miscegenation miscellanies mischance mischanced mischances mischancing mischievously mischievousness misconceive misconceived misconceives misconceiving misconstruction misconstructions miscount miscounted miscounting miscounts miscreant miscreants miscue miscued miscues miscuing misdeal misdealing misdeals misdealt misdiagnose misdiagnosed misdiagnoses misdiagnosing misdiagnosis misdid misdo misdoes misdoing misdoings misdone miserliness misfeasance misfire misfired misfires misfiring misgovern misgoverned misgoverning misgoverns misguidedly mishandle mishandled mishandles mishandling mishmash mishmashes misidentified misidentifies misidentify misidentifying misinterpretations mismanage mismanaged mismanages mismanaging misogynist misogynistic misogynists misogyny misplay misplayed misplaying misplays mispronounce mispronounced mispronounces mispronouncing mispronunciation mispronunciations misquotation misquotations misreadings misrule misruled misrules misruling missal missals missilery misspend misspending misspends misspent misstate misstated misstatement misstatements misstates misstating misstep misstepped misstepping missteps mister misters mistily mistime mistimed mistimes mistiming mistiness mistranslated mistreat mistreated mistreating mistreatment mistreats mistrial mistrials mistrustful mistypes mitigation mitosis mizzen mizzenmast mizzenmasts mizzens mobster mobsters mocha mocker mockers mockingly modals modem modems modernism modernist modernistic modernists modifiable modish modishly mods modulator modulators modulus mogul moguls moieties moiety moire moires moistly moistness molder moldered moldering molders moldiness molehill molehills moleskin molestation molester molesters moll mollification molls mollycoddle mollycoddled mollycoddles mollycoddling molybdenum momentousness momma mommas mommies mommy monarchic monarchical monarchism monarchist monarchists monasticism monaural monetarily moneybag moneybags moneyed moneymaker moneymakers moneymaking monger mongered mongering mongers mongolism mongooses moniker monikers monkeyshine monkeyshines mono monochromatic monochromes monocle monocles monocotyledon monocotyledons monograph monographs monolingual monolinguals monolith monoliths monomania monomaniac monomaniacs mononucleosis monophonic monopolist monopolistic monopolists monosyllabic monotheism monotheist monotheistic monotheists monotone monotoned monotones monotonic monotoning monotonously monoxide monoxides monsieur monsignor monsignors monstrance monstrances monstrously montage montages monumentally mooch mooched moocher moochers mooches mooching moodiness moonlighter moonlighters moonlit moonscape moonscapes moonshine moonshines moonshot moonshots moonstone moonstones moonstruck moorland mopeds moppet moppets moraine moraines moralistic moray morays morbidity morbidly mordant mordants mores moribund morocco morosely moroseness morpheme morphemed morphemes morpheming morphological morrow morrows mortarboard mortarboards mortgagee mortgagees mortgagor mortgagors mortician morticians mortise mortised mortises mortising moses mosey moseyed moseying moseys mossed mossing mote motes motherboard motherboards motherfucker motherfuckers motherfucking motherland motherlands motherless motherliness motile motiles motivational motivator motivators motocross motocrosses motorbiked motorbiking motorboat motorboats motorcar motorcars motorcyclist motorcyclists motorman motormen motormouth motormouths mottle mottled mottles mottling moult moulted moulting moults mountainside mountainsides mountaintop mountaintops mountebank mountebanks mountings mournfully mournfulness mouser mousers mousetrap mousetrapped mousetrapping mousetraps mousiness mouthwash mouthwashes mouthwatering movingly mozzarella mucilage muckier muckiest muckrake muckraked muckraker muckrakers muckrakes muckraking mucky muddiness mudguard mudguards mudslide mudslides mudslinger mudslingers mudslinging muesli muezzin muezzins mufti muftis muggings mukluk mukluks mulatto mulattoes mulberries mulberry muleteer muleteers mulish mulishly mulishness mullah mullahs mullet mullets mulligatawny mullion mullions multicultural multiculturalism multidimensional multifaceted multifarious multifariousness multilateral multilingual multimedia multimillionaire multimillionaires multiplex multiplexed multiplexer multiplexers multiplexes multiplexing multiplicand multiplicands multiplier multipliers multipurpose multiracial multitudinous multivariate multivitamin multivitamins mumbler mumblers mummer mummers mummery mummification munchies mundanely municipally munificence munificent munition munitions muralist muralists murderess murderesses murderously murk murkily murkiness murks muscat muscatel muscatels muscularity musculature mushiness musicale musicales musicianship musicologist musicologists musicology musings muskellunge muskellunges musketeer musketeers musketry muskier muskiest muskiness muskmelon muskmelons muskrat muskrats musky muslin mussier mussiest mussy mustiness mutability mutable muteness mutineer mutineered mutineering mutineers mutinously mutuality muumuu muumuus myna mynas myopia myrrh myrtle myrtles mysteriousness mystically mystification mystique mythic mythologist mythologists n nabob nabobs nacho nachos nacre nadir nadirs naiad naiads nailbrush nailbrushes nakedly nannied nannies nanny nannying nanosecond nanoseconds naphtha naphthalene nappier nappiest narc narced narcing narcissism narcissist narcissistic narcissists narcissus narcosis narcs narwhal narwhals nary nasally nascent nasturtium nasturtiums natal nattily naturalism naturalistic nauseatingly nautically nautilus nautiluses nave naves navigability navigational naysayer naysayers nearness neath nebular necromancer necromancers necromancy necrosis needful needfuls neediness needlepoint nefarious nefariously nefariousness negativity neglectfully negligibly negs nematode nematodes nemeses nemesis neoclassic neoclassical neoclassicism neocolonialism neodymium neologism neologisms neonatal neonate neonates neoprene nephritis neptunium nerd nerdier nerdiest nerds nerdy nerveless nervelessly nervier nerviest nervy nethermost nettlesome neuralgia neuralgic neuritis neurological neurosurgery neurotically neurotransmitter neurotransmitters neutrally neutrino neutrinos nevermore newel newels newlywed newlyweds newness newsboy newsboys newsflash newsman newsmen newspaperman newspapermen newspaperwoman newspaperwomen newsreel newsreels newsworthier newsworthiest newsworthy newtons nexus nexuses niacin nib nibbed nibbing nibbler nibblers nibs niceness nickelodeon nickelodeons niggard niggarded niggarding niggardliness niggardly niggards nigger niggers niggle niggled niggles niggling nigglings nigher nighest nightcap nightcaps nightclothes nighthawk nighthawks nightie nighties nightlife nightshade nightshades nightshirt nightshirts nightstick nightsticks nihilism nihilist nihilistic nihilists nimbi nimbleness nimbus ninepin ninepins ninja ninjas nipper nippered nippering nippers nirvana nitpick nitpicked nitpicker nitpickers nitpicking nitpicks nitrogenous nitroglycerin nix nixed nixes nixing nobleness nocturnally nocturne nocturnes nodal noddy nodular nodule nodules noel noels noggin noggins noiselessness noisemaker noisemakers noisome nonabrasive nonabsorbent nonabsorbents nonagenarian nonagenarians nonalcoholic nonalcoholics nonaligned nonbeliever nonbelievers nonbreakable nonce noncom noncombatant noncombatants noncommercial noncommercials noncommittally noncompetitive noncompliance noncoms nonconductor nonconductors nonconformity noncontagious noncooperation nondairy nondeductible nondenominational nondrinker nondrinkers nonempty nonessential nonesuch nonesuches nonevent nonevents nonexempt nonexistence nonexistent nonfat nonfatal nongovernmental nonhazardous nonhuman nonindustrial noninterference nonintervention nonjudgmental nonliving nonmalignant nonmember nonmembers nonnegotiable nonobjective nonpareil nonpareils nonpayment nonpayments nonphysical nonplus nonpluses nonplussed nonplussing nonpoisonous nonpolitical nonpolluting nonprescription nonproductive nonprofessional nonprofessionals nonproliferation nonrefillable nonrefundable nonrenewable nonrepresentational nonrestrictive nonreturnable nonreturnables nonrigid nonscheduled nonseasonal nonsectarian nonsensically nonsexist nonskid nonsmoker nonsmokers nonsmoking nonstick nonsupport nontaxable nontechnical nontoxic nontransferable nonunion nonuser nonusers nonverbal nonviolent nonvoting nonwhite nonwhites nonzero noonday noontime nope nopes normalcy normative northbound northeaster northeasters northeastward northerner northerners northernmost northwards northwesterly northwestward nosedive nosedived nosedives nosediving nosegay nosegays nosh noshed noshes noshing nosiness nostalgically nostrum nostrums notaries notary notepad notepaper notionally nous novae novas novelette novelettes novella novellas novitiate novitiates noway noways nowise nth nu nuanced nub nubile nubs nucleic nudism nudist nudists nuke nuked nukes nuking nullification nullity numberless numbly numeracy numerated numerates numerating numeration numerations numerology numismatic numismatics numismatist numismatists numskull numskulls nuncio nuncios nunneries nunnery nurseryman nurserymen nuthatch nuthatches nutmeat nutmeats nutria nutrias nutritionally nutritionist nutritionists nutritive nuttiness nylons nymphomania nymphomaniac nymphomaniacs o oafish oaken oakum oarlock oarlocks oarsman oarsmen oat oaten oats obduracy obdurate obdurated obdurately obdurates obdurating obeisance obeisances obeisant obfuscate obfuscated obfuscates obfuscating obit obits objectionably objectiveness oblate oblation oblations obligingly obliquely obliqueness obliviously obliviousness obloquy obnoxiously oboist oboists obscenely obscurely obsequies obsequious obsequiously obsequiousness obsequy observably observantly observational obsessively obsessives obsidian obstetric obstetrical obstinately obstreperous obstructionist obstructionists obstructively obstructiveness obstructives obtrude obtruded obtrudes obtruding obtrusively obtrusiveness obtusely obtuseness obverse obverses obviate obviated obviates obviating obviousness ocarina ocarinas occidental occidentals occlude occluded occludes occluding occlusion occlusions occult oceangoing oceanographer oceanographers oceanographic ocelot ocelots octane octet octets octogenarian octogenarians oculist oculists oddball oddballs oddness odiously odium odoriferous odorous odyssey odysseys offal offensively offertories offertory offhandedly officeholder officeholders officialdom officiously officiousness offside offsides oft oftentimes ofter oftest oho ohos oilcloth oilcloths oilfield oilfields oiliness oilskin oink oinked oinking oinks oldie oldies oleaginous oleander oleanders oleo oleomargarine oligarch oligarchic oligarchies oligarchs oligarchy ombudsman ombudsmen omegas omnibuses omnipresence omniscience omnivore omnivores omnivorous oncology oneness onetime ongoings onionskin onomatopoeic onrushing onshore onyx onyxes oops oopses opacity opalescence opalescent opaquely opaqueness openhanded openwork operable operationally operetta operettas ophthalmic opiate opiates opine opined opines opining opportunism opportunistic oppressively opprobrious opprobrium optically optimistically optometry opulence oracular orally orangeade orangeades orate orated orates orating oratorical oratorio oratorios orb orbs orderings orderliness ordinal ordinals ordinariness ordnance ordure oregano organdy organelle organelles organically orgasmic orgasms orgiastic orientals orifices origami origination oriole orioles ormolu ornamentation ornateness ornerier orneriest ornery orotund orthodontia orthodontic orthodontics orthodoxies orthodoxy orthographic orthographies oscillator oscillators oscilloscopes osier osiers osmotic osprey ospreys ossification ossified ossifies ossify ossifying ostentatiously osteopath osteopaths osteopathy osteoporosis ostracism otherworldly otiose ottoman ottomans outage outages outback outbacks outbalance outbalanced outbalances outbalancing outbid outbidding outbids outbounds outbuilding outbuildings outcrop outcropped outcropping outcroppings outcrops outfielder outfielders outfitter outfitters outflank outflanked outflanking outflanks outfox outfoxed outfoxes outfoxing outgo outgoes outlandishly outperform outperformed outperforming outperforms outplacement outplay outplayed outplaying outplays outpouring outpourings outrank outranked outranking outranks outre outreach outreached outreaches outreaching outrider outriders outrigger outriggers outsell outselling outsells outsize outsizes outsold outsource outsourced outsources outsourcing outspokenly outspokenness outspread outspreading outspreads outstay outstayed outstaying outstays outstretch outstretched outstretches outstretching outtake outtakes outvote outvoted outvotes outvoting outwear outwearing outwears outwore outworn ovarian overabundance overabundant overachieve overachieved overachiever overachievers overachieves overachieving overact overacted overacting overactive overacts overage overages overambitious overanxious overawe overawed overawes overawing overbalance overbalanced overbalances overbalancing overbite overbites overbook overbooked overbooking overbooks overcautious overcompensate overcompensated overcompensates overcompensating overcompensation overconfident overcook overcooked overcooking overcooks overdrafts overdress overdressed overdresses overdressing overdrive overeager overenthusiastic overexpose overexposed overexposes overexposing overexposure overextend overextended overextending overextends overfull overgenerous overgrowth overindulge overindulged overindulgence overindulges overindulging overjoy overjoyed overjoying overjoys overkilled overkilling overkills overlord overlords overmuch overmuches overpaid overpay overpaying overpays overplay overplayed overplaying overplays overpopulate overpopulated overpopulates overpopulating overproduce overproduced overproduces overproducing overproduction overprotective overqualified overreach overreached overreaches overreaching overreaction overreactions overripe oversell overselling oversells oversensitive oversexed overshoe overshoes oversimplifications oversimplified oversimplifies oversimplify oversimplifying oversize oversizes oversizing oversold overspend overspending overspends overspent overspill overspread overspreading overspreads overstatement overstatements overstay overstayed overstaying overstays overstock overstocked overstocking overstocks overstuffed oversupplied oversupplies oversupply oversupplying overtax overtaxed overtaxes overtaxing overviews overweening overzealous oviduct oviducts oviparous ovoid ovoids ovulate ovulated ovulates ovulating ovulation ovule ovules ow owlet owlets owlish oxbow oxbows oxford oxfords oxyacetylene oxygenate oxygenated oxygenates oxygenating oxygenation oxymora oxymoron p pH pacesetter pacesetters pachyderm pachyderms pacifically pacification padre padres paean paeans paediatrics paganism pagers paginate paginated paginates paginating pailful pailfuls painkiller painkillers painstakingly paintbrush paintbrushes painters paintwork pairwise paisley paisleys palatal palatals palaver palavered palavering palavers paleface palefaces paleness palimony palimpsest palimpsests palindrome palindromes palindromic palings palisade palisades palladium pallet pallets palliate palliated palliates palliating palliation palliative palliatives palmetto palmettos palmier palmiest palmist palmistry palmists palmy palpate palpated palpates palpating palpation palpitate palpitated palpitates palpitating palpitation palpitations palsied palsies palsy palsying paltriness pampas pamphleteer pamphleteers panache panchromatic pandemic pandemics panderer panderers panegyric panegyrics panelist panelists pannier panniers panoplies panoply pantaloons pantheism pantheist pantheistic pantheists pantheon pantheons pantsuit pantsuits pantyhose papaw papaws paperboy paperboys papergirl papergirls paperhanger paperhangers papery papilla papillae papoose papooses papped papping paps parabola parabolas parabolic parachutist parachutists paradigmatic paradigms paralegal paralegals parallax parallaxes parallelism parallelisms parallelogram parallelograms paramecia paramecium paramedic paramedical paramedicals paramedics paramilitaries paramilitary paramour paramours paranormal parapet parapets paraplegia paraprofessional paraprofessionals parapsychology paratroops parboil parboiled parboiling parboils parenthetic parenthetically parfait parfaits pariah pariahs parings parlance parlay parlayed parlaying parlays parley parleyed parleying parleys parliamentarian parliamentarians parochialism parolee parolees paroxysm paroxysms parquet parqueted parqueting parquetry parquets parricide parricides parried parries parry parrying parsimonious parsimony partaker partakers parterre parterres parthenogenesis participator participators participatory participial particularities particularity particulate particulates partisanship parturition partway parvenu parvenus paschal pasha pashas passably passel passels passerby passersby passionless passivity passkey passkeys pasteboard pastern pasterns pastiches pastorate pastorates pastrami pasturage patchier patchiest patchiness patella patellae patellas paternalistic paternally pathogen pathogenic pathogens pathologically patina patinas patois patriarchies patriarchy patrician patricians patricide patricides patrimonial patriotically patrolman patrolmen patrolwoman patrolwomen patronymic patronymics patsies patsy pauperism pavings pawl pawls pawnshop pawnshops paycheck paychecks payday paydays payee payees payloads paymaster paymasters peaceably peacefulness peacekeeping peacetime peafowl peafowls peahen peahens pearlier pearliest pearly peasantry pebblier pebbliest pebbly peccadillo peccadilloes peccaries peccary pectin pectoral pectorals pecuniary pedagogic pedagogical pedagogics pedagogue pedagogued pedagogues pedagoguing pedantically pederast pederasts pederasty pedicure pedicured pedicures pedicuring pedigreed pediment pediments pedometer pedometers pee peed peeing peekaboo peeper peepers peephole peepholes peerage peerages pees peevishly peevishness peewee peewees pejorative pejoratives pekoe pelagic pellagra pellucid penchants pendent pendents pendulous penetrable penetrative penile peninsular penitential penitently penlight penlights pennon pennons pennyweight pennyweights penologist penologists penology pensiveness pent pentameter pentameters pentathlon pentathlons pents penultimates penurious penury peonage peppercorn peppercorns pepperoni pepperonis peppery peppier peppiest peppy pepsin peptic peptics perambulate perambulated perambulates perambulating perambulator perambulators percale percales perceivable percentile percentiles perceptibly perceptively perceptiveness perceptual percussionist percussionists perdition peregrination peregrinations peremptorily perennially perfectible perfectionism perfidies perfidious perfidy perforce perfumeries perfumery pericardia pericardium perigee perigees perihelia perihelion periodicity periodontal peripatetic peripatetics periphrases periphrasis peritoneum peritoneums peritonitis periwig periwigged periwigging periwigs periwinkle periwinkles perjurer perjurers perkiness perm permafrost permeability permeable permed perming permissibly permissively permissiveness perms permute permuted permutes permuting perniciously peroration perorations perpetration perpetuation perpetuity perquisite perquisites persiflage persimmon persimmons persnickety personae personage personages perspicacious perspicacity perspicuity perspicuous persuasiveness pertinacious pertinacity pertinence pertly pertness perturbation perturbations perversely perverseness perversity peseta pesetas peso pesos pessimistically pestilent pestle pestled pestles pestling petard petards petiole petioles petitioner petitioners petrel petrels petrifaction petrochemical petrochemicals petrolatum pettifog pettifogged pettifogger pettifoggers pettifogging pettifogs pettily petulance petulantly pewee pewees peyote phalanges phalanx phalanxes phalli phallic phallus phantasm phantasmagoria phantasmagorias phantasms pharaoh pharaohs pharmacologist pharmacologists pharmacology pharmacopoeia pharmacopoeias pharyngeal pharynges pharynx phenobarbital phenotype pheromone pheromones phial phialled phialling phials philander philandered philanderer philanderers philandering philanders philanthropically philatelic philatelist philatelists philately philharmonic philharmonics philippic philippics philistine philistines philodendron philodendrons philological philologist philologists philology philosophic philosophically philter philters phlebitis phlegmatically phloem phlox phobic phobics phoebe phoebes phoenixes phoneme phonemes phonemic phonemics phonetically phonetician phoneticians phonic phonically phoniness phonological phonologist phonologists phonology phooey phooeys phosphate phosphates phosphoric phosphors photoelectric photographically photojournalism photojournalist photojournalists photosensitive phototypesetting phrasal phrasings phrenology phyla phylae phylum physicked physicking physiognomies physiognomy physiologist physiologists physiotherapist physiotherapists physiotherapy pianissimo pianissimos pianoforte pianofortes piazza piazzas pica picaresque picaresques picayune piccalilli picker pickerel pickerels pickers pickings picnicker picnickers pictograph pictographs pictorially pidgin pidgins piebald piebalds pied pieing piercingly piercings piffle piggier piggies piggiest piggishness piggy piglet piglets pigmentation pigskin pigskins pigsties pigsty piing piker pikers pilaf pilafs pilaster pilasters pilchard pilchards pileup pileups pilferer pilferers pilings pillbox pillboxes pillion pillioned pillioning pillions pilloried pillories pillory pillorying pilothouse pilothouses pimento pimentos pimiento pimientos pimp pimped pimpernel pimpernels pimping pimps pinafore pinafores pinball pincer pincers pinfeather pinfeathers ping pinged pinging pings pinhead pinheads pinhole pinholes pinkeye pinkie pinkies pinkish pinnate pinochle pinprick pinpricked pinpricking pinpricks pinstripe pinstriped pinstripes pinto pintos pinup pinups pinwheel pinwheeled pinwheeling pinwheels piously pip piper pipers pipit pipits pipped pippin pipping pippins pips pipsqueak pipsqueaks piquancy piquant piratical piscatorial piss pissed pisses pissing pistil pistillate pistils pita pitchblende pitchman pitchmen pith pithily pitiable pitiably pitilessly piton pitons pituitaries pituitary pixel pixels pizazz pizzeria pizzerias pizzicati pizzicato placation placebo placebos placeholder placements placental placentals placer placers placidity placket plackets plainclothes plainclothesman plainclothesmen plainness plaint plaintively plaints plait plaited plaiting plaits plangent plannings plantings plasterboard plasterer plasterers plasticity plateful platefuls platelet platelets platen platens platitudinous platonic platypus platypuses plaudit plaudits playact playacted playacting playacts playbacks playbill playbills playboy playboys playgoer playgoers playoff playoffs playroom playrooms pleader pleaders pleasantness pleasingly pleasurably plebeian plebeians plebiscite plebiscites plectra plectrum plectrums plenaries plenary plenipotentiaries plenipotentiary plenitude plenitudes plenteous pleurisy plexus plexuses pliability pliancy plinth plinths plodder plodders ploddings plottered plottering plover plovers pluckier pluckiest pluckiness plumpness plunderer plunderers plunk plunked plunking plunks pluperfect pluperfects pluralism pluralistic pluralities plushier plushiest plushy plutocracies plutocracy plutocrat plutocratic plutocrats pneumatically pock pocked pocketful pocketfuls pocketknife pocketknives pocking pocks podiatrist podiatrists podiatry poesied poesies poesy poesying poetess poetesses poetically pogrom pogromed pogroming pogroms poi poignantly pointier pointiest pointillism pointillist pointillists pointlessness pointy poisoner poisoners poisonings poisonously pol polarities polecat polecats polemical polestar polestars policyholder policyholders poliomyelitis polisher polishers politesse politic politicked politicking politico politicos polities polity polliwog polliwogs polluter polluters polonaise polonaises polonium pols poltergeist poltergeists poltroon poltroons polyester polyesters polyethylene polygamist polygamists polyglot polyglots polygonal polygraph polygraphed polygraphing polygraphs polyhedron polyhedrons polymath polymaths polymer polymeric polymers polymorphic polyphonic polyphony polystyrene polysyllabic polysyllable polysyllables polytechnics polytheism polytheist polytheistic polytheists polythene polyunsaturated pomade pomaded pomades pomading pommel pommels pompadour pompadoured pompadours pompom pompoms pomposity pompously pompousness ponderously pone pones poniard poniards pontiff pontiffs pontifical pontificate pontificated pontificates pontificating ponytail ponytails pooch pooched pooches pooching pooh poohed poohing poohs poorhouse poorhouses popes popgun popguns popinjay popinjays poplin popover popovers poppa poppas poppycock populism populist populists porcine porn porno pornographer pornographers porosity porphyry porringer porringers portage portaged portages portaging portcullis portcullises portentous portentously porterhouse porterhouses portliness portmanteau portmanteaus portraitist portraitists portraiture poser posers poseur poseurs posh poshed posher poshes poshest poshing posit posited positing positron positrons posits posse posses possessively possessiveness postcodes postdate postdated postdates postdating postdoc postdocs postdoctoral posthaste postlude postludes postmistress postmistresses postmodern postmortem postmortems postnatal postoperative postpaid postpartum postwar potable potables potash potbellied potbellies potbelly potboiler potboilers potentate potentates potentialities potentiality potentials potful potfuls potholder potholders pothook pothooks potluck potlucks potpie potpies potpourri potpourris potsherd potsherds potshot potshots pottage pottier potties pottiest potty poultice poulticed poultices poulticing powerboat powerboats powerlessly powerlessness pox poxed poxes poxing practicability practicably pragmatically pragmatist pragmatists praiseworthiness praline pralines prancer prancers prankster pranksters prate prated prates pratfall pratfalls prating preachier preachiest preachy prearrange prearranged prearrangement prearranges prearranging precept preceptor preceptors precepts preciosity preciously preciousness precipitant precipitants precipitately precipitously preciseness preclusion precociously precociousness precocity precognition precondition preconditioned preconditioning preconditions predate predated predates predating predecease predeceased predeceases predeceasing predestine predestined predestines predestining predetermination predetermine predetermined predetermines predetermining predication predicative predictability predictive predilection predilections predispose predisposed predisposes predisposing preeminently preemption preemptive preexist preexisted preexisting preexists prefabricate prefabricated prefabricates prefabricating prefabrication prefatory prefects prefecture prefectures preferentially preferment prefigure prefigured prefigures prefiguring preheat preheated preheating preheats prehensile prehistory prejudge prejudged prejudges prejudging prelate prelates premarital premeditate premeditated premeditates premeditating premenstrual premonitory preoccupation preoccupations preordain preordained preordaining preordains prep prepackage prepackaged prepackages prepackaging preparedness prepayment prepayments preponderant preponderate preponderated preponderates preponderating prepossess prepossessed prepossesses prepossessing preposterously prepped preppier preppies preppiest prepping preppy preps prequel prequels prerecord prerecorded prerecording prerecords preregister preregistered preregistering preregisters preregistration presage presaged presages presaging preschool preschooler preschoolers preschools prescience prescient prescriptive presentiment presentiments preserver preservers preses preset presets presetting preshrank preshrink preshrinking preshrinks preshrunk pressman pressmen prestos presumable presumptive presumptuously presumptuousness presupposition presuppositions preteen preteens preterit preterits preternatural prettified prettifies prettify prettifying prettily prettiness prevaricate prevaricated prevaricates prevaricating prevarication prevarications prevaricator prevaricators preventative preventatives prewar pricey pricier priciest priestlier priestliest priestly prig priggish prigs primacy primitively primness primogeniture primordial primordials princelier princeliest princely prioress prioresses priories priory prismatic prissier prissies prissiest prissiness prissy pristine prithee prithees privateer privateers privet privets prizefight prizefighter prizefighters prizefighting prizefights proactive probate probated probates probating probationaries probationary probationer probationers probity problematical problematically problematics proboscis proboscises proclivities proclivity procrastinator procrastinators procreate procreated procreates procreating procreation procreative proctor proctored proctoring proctors procurator procurators procurer procurers prodigality prodigiously productively productiveness prof profanation profanations profanely professionalism professorial professorship professorships profitability profitably profligacy profligate profligates proforma profs progenitor progenitors progesterone prognostic prognosticate prognosticated prognosticates prognosticating prognostication prognostications prognosticator prognosticators prognostics programmables prohibitionist prohibitionists prohibitory projectionist projectionists prolifically prolix prolixity prolongation prolongations promiscuously promisingly promissory promo promos promoter promoters promotional prompters promptings promulgation proneness pronged pronghorn pronghorns pronounceable pronto proofreader proofreaders propagandist propagandists propane propellant propellants propertied prophetess prophetesses prophetically prophylactic prophylactics prophylaxis propinquity propitiate propitiated propitiates propitiating propitiation propitiatory propitious proportionately proposer propound propounded propounding propounds proprietorship proprietress proprietresses propulsive prorate prorated prorates prorating prosaic prosaically proscenium prosceniums proscribe proscribed proscribes proscribing proscription proscriptions proselyte proselyted proselytes proselyting prosier prosiest prosodies prosody prosperously prostate prostates prostheses prosthesis prosthetic prosthetics prostration prostrations prosy protean proteans protectively protectiveness protectorate protectorates protestants protestation protestations protester protesters protoplasm protoplasmic prototyping protozoa protozoan protozoans protraction protuberance protuberances protuberant provender provendered provendering provenders proverbially provident providential providentially providently providers provincialism provocatively provost provosts prudential prudentials prudently prudery prudishly prurience prurient psalmist psalmists pshaw pshaws psoriasis psst pssts psychical psychically psycho psychobabble psychogenic psychokinesis psychopathic psychopathics psychos psychosomatic psychosomatics psychotherapist psychotherapists psychotics ptarmigan ptarmigans pterodactyl pterodactyls ptomaine ptomaines pubbed pubbing pubescence pubescent pubic publican publicans publicist publicists publishable pubs puckish puerile puerility puffball puffballs puffin puffiness puffins pug pugilism pugilist pugilistic pugilists pugnaciously pugnacity pugs pulchritude pullback pullbacks puller pullers pullet pullets pullout pullouts pulpier pulpiest pulpy pulsar pulsars punchier punchiest punchy punctilious punctiliously punctually pungency pungently punster punsters pupa pupae pupal puppeteer puppeteers puppetry purblind purchasable purebred purebreds pureness purgative purgatives purgatorial purgatories purifier purifiers purism purist purists puritan puritanically puritanism puritans purl purled purling purloin purloined purloining purloins purls purplish purportedly purposefully purposeless purposely purser pursers pursuance pursuant pursuer pursuers purulence purulent purvey purveyed purveying purveyors purveys purview pushcart pushcarts pushiness pusillanimity pusillanimous pussycat pussycats pussyfoot pussyfooted pussyfooting pussyfoots pustule pustules putrefaction putrefied putrefies putrefy putrefying putrescence putrescent putsch putsches puzzlement puzzler puzzlers pygmies pygmy pylon pylons pyramidal pyrite pyromania pyromaniac pyromaniacs pyrotechnic pyrotechnics pyx pyxed pyxes pyxing q quackery quad quadrangular quadraphonic quadraphonics quadrature quadrennial quadriceps quadricepses quadrille quadrilled quadrilles quadrilling quadriplegia quadriplegic quadriplegics quadruplicate quadruplicated quadruplicates quadruplicating quads quaff quaffed quaffing quaffs quahog quahogs quaintly quaintness qualitatively quanta quantified quantifiers quantifies quantifying quarks quarterdeck quarterdecks quarterfinal quarterfinals quartermaster quartermasters quarto quartos quasar quasars quasi quatrain quatrains quavery queasily queasiness queerly queerness querulous querulously questionably questioner questioners questioningly quibbler quibblers quiches quickie quickies quicklime quickness quicksilver quid quids quiescence quiescent quietness quietude quietus quietuses quilter quilters quince quinces quintessential quintuple quintupled quintuples quintupling quire quires quirkier quirkiest quisling quislings quixotic quizzically quoit quoited quoiting quoits quondam quotable quoth quotidian r rabbinate rabbinical racecourse racecourses racehorse racehorses raceme racemes racers raceway raceways racily raciness raconteur raconteurs racquetball racquetballs radially radiantly radicalism radiogram radiograms radioisotope radioisotopes radiologist radiologists radiology radiotelephone radiotelephones radiotherapist radiotherapists radiotherapy radon raffia raffish raga ragas raggedier raggediest raggedly raggedness raggedy raglan raglans ragout ragouts ragtag ragtags ragweed railleries raillery raiment rainmaker rainmakers rajah rajahs rakish rakishly rakishness ramblings rambunctious rambunctiousness ramified ramifies ramify ramifying rampantly rampart ramparts rancidity rancorously randier randiest randy rangier rangiest ranginess rangy rankings rankness ranter rapacious rapaciously rapaciousness rapacity rapier rapiers rapine rapper rappers rapprochement rapprochements rapscallion rapscallions rarefied rarefies rarefy rarefying rareness rascally rashers rashness raspier raspiest raspy ratchet ratcheted ratcheting ratchets rathskeller rathskellers rationalism rationalist rationalistic rationalists rattan rattans rattier rattiest rattletrap rattletraps rattlings rattrap rattraps raucousness raunchier raunchiest raunchiness raunchy ravioli raviolis ravishingly ravishment rawboned rawhide rawness razz razzed razzes razzing reachable reactivate reactivated reactivates reactivating reactivation readabilities readerships readjustment readjustments readmit readmits readmitted readmitting readout readouts reaffirm reaffirmed reaffirming reaffirms reagent reagents realign reallocation reamer reamers reanimate reanimated reanimates reanimating reappearance reappearances reapplied reapplies reapply reapplying reappoint reappointed reappointing reappointment reappoints reapportion reapportioned reapportioning reapportionment reapportions reappraisal reappraisals reappraise reappraised reappraises reappraising rearm rearmament rearmed rearming rearmost rearms rearward rearwards reasonableness reassemble reassembled reassembles reassembling reassert reasserted reasserting reasserts reassess reassessed reassesses reassessing reassessment reassessments reassign reassigned reassigning reassigns reassuringly reawaken reawakened reawakening reawakens rebelliously rebelliousness rebroadcast rebroadcasting rebroadcasts rebus rebuses recalcitrance recantation recantations recapitulate recapitulated recapitulates recapitulating recapitulation recapitulations recast recasting recasts receivable receivables receivership receptively receptiveness receptivity receptor receptors recessional recessionals recessive recessives recheck rechecked rechecking rechecks recherche recidivism recidivist recidivists reciprocally reciprocation reciprocity recitative recitatives reckonings reclassified reclassifies reclassify reclassifying recliner recliners reclusive recombination recombine recombined recombines recombining recommence recommenced recommences recommencing recompilation reconcilable recondite reconfiguration reconquer reconquered reconquering reconquers reconsideration reconstitute reconstituted reconstitutes reconstituting reconvene reconvened reconvenes reconvening recopied recopies recopy recopying recreant recreants recriminate recriminated recriminates recriminating recrimination recriminations recrudescence recruiter recruiters rectifiable rectification rectifications rectifier rectifiers rectilinear rectitude rectories rectory recumbent recuperative recyclable recyclables redbreast redbreasts redcap redcaps redcoat redcoats reddish redecorate redecorated redecorates redecorating rededicate rededicated rededicates rededicating redeemer redeemers redeploy redeployed redeploying redeployment redeploys redevelop redeveloped redeveloping redevelopment redevelopments redevelops redheaded rediscovery redistrict redistricted redistricting redistricts redneck rednecks redness redolence redolent redouble redoubled redoubles redoubling redoubt redoubtable redoubted redoubting redoubts redound redounded redounding redounds redrafted redrafting redrafts redrawing redrawn redraws redrew redskin redskins redundantly redwood redwoods reedier reediest reeducate reeducated reeducates reeducating reeducation reedy reefer reefers reelection reelections reemerge reemerged reemerges reemerging reenact reenacted reenacting reenactment reenactments reenacts reenlist reenlisted reenlisting reenlists reenter reentered reentering reenters reentries reentry reestablish reestablished reestablishes reestablishing reevaluate reevaluated reevaluates reevaluating reeve reeves reeving reexamine reexamined reexamines reexamining ref refashion refashioned refashioning refashions refectories refectory referent referential referral referrals reffed reffing refile refiled refiles refiling refillable refinance refinanced refinances refinancing refiner refiners refinish refinished refinishes refinishing refit refits refitted refitting reflexively refocus refocused refocuses refocusing reforest reforestation reforested reforesting reforests reformatories reformatory reformulate reformulated reformulates reformulating refract refracted refracting refractories refractory refracts refresher refreshers refreshingly refrigerant refrigerants refs refulgence refulgent refundable refurbishments refurnish refurnished refurnishes refurnishing refutations regally regencies regency regenerative reggae regicide regicides regimentation regionalism regionalisms regionally registrant registrants regressive regretfully regroup regrouped regrouping regroups regulator regulators regulatory regurgitation rehab rehabbed rehabbing rehabs reheat reheated reheating reheats rehire rehired rehires rehiring reimpose reimposed reimposes reimposing reinsert reinserted reinserting reinserts reinterpret reinterpretation reinterpretations reinterpreted reinterpreting reinterprets reinvent reinvented reinventing reinvents reinvest reinvested reinvesting reinvests reissue reissued reissues reissuing rejoicings rekindle rekindled rekindles rekindling relabel relabels relaxant relaxants relearn relearned relearning relearns relegation relentlessness relevancy relevantly relinquishment remades remaindered remand remanded remanding remands remarriage remarriages remarried remarries remarry remarrying rematch rematches remediable remissness remonstrance remonstrances remonstrate remonstrated remonstrates remonstrating remorsefully remorselessly remoteness remount remounted remounting remounts remover removers remunerative renaissances renal renascence renascences renascent renderings renegotiate renegotiated renegotiates renegotiating rennet renovator renovators renter renters renumber renumbered renumbering renumbers reoccupied reoccupies reoccupy reoccupying reoccur reoccurred reoccurring reoccurs reorder reordered reordering reorders rep repackage repackaged repackages repackaging repaint repainted repainting repaints repairable repairman repairmen reparations repartee reparteed reparteeing repartees repast repasted repasting repasts repatriation repayable repeatably repeater repeaters repertories repertory rephrased rephrases rephrasing replaceable replayed replaying replays replenishment repletion replications reportage reposeful repossess repossessed repossesses repossessing repossession repossessions reprehend reprehended reprehending reprehends reprehensibly representational reprise reprises reprising reproachful reproachfully reprobate reprobates reprocess reprocessed reprocesses reprocessing reproducible reproducibles reproof reproofed reproofing reproofs reps reptilian reptilians republicanism republish republished republishes republishing repulsively repulsiveness reputably requester requiems requital requite requited requites requiting reran rerun rerunning reruns resales rescission resell reselling resells resend resentfully reservedly reservist reservists resettle resettled resettles resettling reshuffled reshuffles reshuffling residencies residency resignedly resiliency resinous resister resisters resold resoluteness resonantly resonate resonated resonates resonating resonator resonators resoundingly resourcefully respell respelled respelling respells respire respired respires respiring resplendence resplendently respondent respondents responsively responsiveness restate restated restatement restatements restates restating restaurateur restaurateurs restfully restfulness restively restiveness restock restocked restocking restocks restorative restoratives restorer restorers restrictively restroom restrooms restructurings restudied restudies restudy restudying resupplied resupplies resupply resupplying resurgent resuscitator resuscitators retake retaken retakes retaking retaliatory retardant retardants retardation retell retelling retells retentive retentiveness rethinking rethinks rethought retinal retinue retinues retiree retirees retold retook retool retooled retooling retools retouch retouched retouches retouching retractable retrain retrained retraining retrains retread retreaded retreading retreads retrench retrenched retrenches retrenching retrenchment retrenchments retrial retrials retributive retried retrievable retroactively retrod retrodden retrofit retrofits retrofitted retrofitting retrograded retrogrades retrograding retrogress retrogressed retrogresses retrogressing retrogression retrogressive retrorocket retrorockets retrospection retrying returnee returnees retyped retypes retyping reunification reunified reunifies reunify reunifying reupholster reupholstered reupholstering reupholsters reusable revaluation revaluations revalue revalued revalues revaluing revealings reveille reverend reverends reverential revilement reviler revilers revivalist revivalists revivification revivified revivifies revivify revivifying revocable revocation revocations revoltingly revolutionist revolutionists rewindable rewinding rewinds rewire rewired rewires rewiring reword reworded rewording rewords reworked reworking reworks rewound rhapsodic rhea rheas rheostat rheostats rhetorically rhetorician rhetoricians rheum rheumatic rheumatics rheumier rheumiest rheumy rhinestone rhinestones rhizome rhizomes rho rhodium rhomboid rhomboids rhombus rhombuses rhythmical rhythmically ribald ribaldry riboflavin rick ricked rickets ricking ricks ricotta ridgepole ridgepoles ridiculousness riff riffed riffing riffle riffled riffles riffling riffraff riffs rifleman riflemen rightfulness rightist rightists rigidness rigmarole rigmaroles rill rilled rilling rills rime rimed rimes riming ringer ringers ringmaster ringmasters ringside ripely riposted ripostes riposting rippers ripsaw ripsaws risible risibles riskiness ritualism ritualistic ritually ritzier ritziest ritzy riven riverbed riverbeds riverfront riverfronts riverside riversides rivulet rivulets roadbed roadbeds roadhouse roadhouses roadkill roadrunner roadrunners roadshow roadster roadsters roadway roadways roadwork roadworthy roamer roamers roan roans roaster roasters robotic robotics robustly rocketry rockiness rococo roebuck roebucks roentgen roentgens roger rogered rogering rogers roguery roguishly roil roiled roiling roils roister roistered roisterer roisterers roistering roisters rollback rollbacks rollerskating rollick rollicked rollicking rollicks romaine romanticism romanticist romanticists romper rompers rood roods rooftop rooftops rookeries rookery roomer roomers roomful roomfuls roominess rootless roseate rosebud rosebuds rosebush rosebushes rosette rosetted rosettes rosetting rosewood rosewoods rosily rosin rosined rosiness rosining rosins rotational rotogravure rotogravures rottenness rotundity rotundness roue roues roughneck roughnecked roughnecking roughnecks roughshod roundelay roundelays roundhouse roundhouses roundish roundly roundup roundups roundworm roundworms roustabout roustabouts rove roved rover rovers roves roving rowdyism rowel rowels rower rowers royalist royalists rs rubberier rubberiest rubberneck rubbernecked rubbernecking rubbernecks rubbery rubbishy rubdown rubdowns rube rubella rubes rubicund rubrics rucksacks ruddiness rudiment rudiments ruefully ruggedly ruggedness ruination ruinously rumba rumbaed rumbaing rumbas rumblings ruminant ruminants rumination ruminations rumpus rumpuses runabout runabouts runaround runarounds runnel runnels runoff runoffs rupee rupees rusk rusks russet russeted russets russetting rustically rusticity rustiness rustproof rustproofed rustproofing rustproofs rutabaga rutabagas s sabbaticals sable sabled sables sabling saccharin saccharine sacerdotal sachem sachems sachet sachets sackcloth sackful sackfuls sacramental sacredly sacredness sacristan sacristans sacristies sacristy sacrosanct saddlebag saddlebags sadistically safeness safflower safflowers sagacious sagacity sago saguaro saguaros sahib sahibs sailboard sailboarded sailboarding sailboards sailcloth sailfish sailfishes sainthood saintliness saith saiths salaam salaamed salaaming salaams salacious salaciously salaciousness salamander salamanders salesclerk salesclerks salesgirl salesgirls salesmanship saline salines salinity salivary salivation sallied sallies sallying salmonella salmonellae salsa salsas saltcellar saltcellars saltine saltines saltiness saltshaker saltshakers saltwater salubrious salutary salvageable salver salvers salvo salvos samba sambaed sambaing sambas samovar samovars sampan sampans samplers samurai sanctification sanctimoniously sanctum sanctums sandalwood sandbank sandbanks sandbar sandbars sandblast sandblasted sandblaster sandblasters sandblasting sandblasts sandbox sandboxes sandcastle sandcastles sander sanders sandhog sandhogs sandiness sandlot sandlots sandpiper sandpipers sanely sangfroid sanguinary sanguine sanguined sanguines sanguining sans sapience sapient sappier sappiest sappy saprophyte saprophytes sapsucker sapsuckers sarcoma sarcomas sarcophagi sarcophagus sardonic sardonically sarong sarongs sarsaparilla sarsaparillas sartorial sartorially sashay sashayed sashaying sashays sass sassafras sassafrases sassed sasses sassing satanically satanism sate sated sateen sates satiate satiated satiates satiating satiety sating satinwood satinwoods satiny satirically satrap satraps saturnine satyr satyrs saucily sauciness savageness savanna savannas savant savants savers sawhorse sawhorses sawmill sawmills sawyer sawyers sax saxes saxophonist saxophonists scabbard scabbards scabbier scabbiest scabby scabies scabrous scad scads scalawag scalawags scaldings scalene scallion scallions scalper scalpers scam scammed scamming scamp scampi scamps scams scandalmonger scandalmongers scandalously scansion scantily scantiness scapula scapulae scarab scarabs scarceness scarified scarifies scarify scarifying scat scathingly scatological scats scatted scatting scavenge scavenged scavenges scavenging scenically schedulers schema schematic schematically schematics schemings scherzo scherzos schism schismatic schismatics schisms schist schizoid schizoids schizophrenics schlemiel schlemiels schlep schlepped schlepping schleps schlock schlockier schlockiest schlocky schmaltz schmaltzier schmaltziest schmaltzy schmooze schmoozed schmoozes schmoozing schmuck schmucks schnapps schnauzer schnauzers scholastically schoolbook schoolbooks schooldays schoolgirl schoolgirls schoolhouse schoolhouses schoolmarm schoolmarms schoolmaster schoolmasters schoolmate schoolmates schoolmistress schoolmistresses schoolroom schoolrooms schoolwork schoolyard schoolyards schuss schussed schusses schussing schwa schwas sciatic sciatica scimitar scimitars scintilla scintillas scintillate scintillated scintillates scintillating scintillation scion scions sclerosis sclerotic sclerotics scofflaw scofflaws scoldings scoliosis sconce sconces scone scones scorcher scorchers scoreboard scoreboards scorecard scorecards scoreless scorers scornfully scotched scotches scotching scoutmaster scoutmasters scow scows scrabbled scrabbles scrabbling scragglier scraggliest scraggly scrambler scramblers scraper scrapers scrappier scrappiest scrappy scratchiness screechier screechiest screechy screenings screenplay screenplays screenwriter screenwriters screwball screwballs scribbler scribblers scrimmage scrimmaged scrimmages scrimmaging scrimp scrimped scrimping scrimps scrimshaw scrimshawed scrimshawing scrimshaws scrip scrips scriptural scrod scrofula scrooge scrooges scrota scrotum scrounger scroungers scrubber scrubbers scrubbier scrubbiest scrubby scrumptious scrunch scrunched scrunches scrunching scuba scubaed scubaing scubas scud scudded scudding scuds scull sculled sculleries scullery sculling scullion scullions sculls sculpt sculpted sculpting sculpts sculptural scumbag scumbags scummier scummiest scummy scupper scuppered scuppering scuppers scurf scurfier scurfiest scurfy scurrilously scurvier scurviest scurvy scuttlebutt scuzzier scuzziest scuzzy seabed seabeds seabird seabirds seaboard seaboards seacoast seacoasts seafarer seafarers seagoing sealant sealants sealer sealers sealskin seamanship seamier seamiest seamless seamy seance seances seaplane seaplanes searcher searchers searchingly seascape seascapes seasonally seaward seawards seaway seaways seaworthier seaworthiest seaworthy sebaceous secessionist secessionists seclusive secondhand secretariat secretariats secretively secretiveness secs sectarian sectarianism sectarians sectional sectionalism sectionals secularism sedately sedation sedge sedimentation sedition seditious seducer seducers seductively sedulous seediness seedless seeings seeker seekers seemlier seemliest seemliness seemly seers seersucker seethings segregationist segregationists segue segued segueing segues seismic seismically seismograph seismographic seismographs seismologist seismologists seismology selectivity selectman selectmen selenium selfishly selfless selflessly selflessness selfsame sellout sellouts seltzer selvage selvaged selvages selvaging semaphore semaphored semaphores semaphoring semi semiannual semiautomatic semiautomatics semicircular semiconscious semifinalist semifinalists semimonthlies semimonthly seminal seminarian seminarians semipermeable semiprecious semiprivate semiprofessional semiprofessionals semis semiskilled semitone semitones semitrailer semitrailers semitropical semiweeklies semiweekly senatorial senders senna sensationalist sensationalists sensationally senselessly senselessness sensitively sensitiveness sensually sensuously sensuousness sententious sentimentalism sentimentalist sentimentalists sentimentally sentinel sentinels sepal sepals separable separatism separatist separatists sepia sepsis septa septet septets septic septics septuagenarian septuagenarians septum sepulchral sequencers sequester sequestered sequestering sequesters sequestration sequestrations sequined sequoia sequoias seraglio seraglios serape serapes seraph seraphic seraphs sere sered serendipitous serendipity serenely sereneness serer seres serest serf serfdom serfs serge serially sering serous serpentine serrated serried servicewoman servicewomen servility servings servo servomechanism servomechanisms servos sesame sesames settee settees setup setups seventieth seventieths severally sewerage sexagenarian sexagenarians sexier sexiest sexiness sexists sexless sexpot sexpots sextant sextants sextet sextets sexton sextons sh shabbiness shad shadiness shadings shadowbox shadowboxed shadowboxes shadowboxing shads shag shagged shagginess shagging shags shah shahs shakedown shakedowns shaker shakers shakeup shakeups shakily shakiness shale shallot shallots shallowness shalt shaman shamans shambled shambling shamefaced shamefulness shamelessly shandy shanghai shanghaied shanghaiing shanghais shank shanks shantung shantytown shantytowns shapeless shapelessly shapelessness shapeliness shard shards sharecropper sharecroppers sharkskin sharpers sharpshooter sharpshooters shat shatterproof shavings shearer shearers sheathings shebang shebangs sheepdog sheepdogs sheepfold sheepfolds sheepishness sheepskin sheepskins sheeting sheikdom sheikdoms shekel shekels shellac shellacked shellacking shellacs shenanigan shenanigans shepherdess shepherdesses shibboleth shibboleths shiftily shiftiness shiftlessness shill shilled shillelagh shillelaghs shilling shillings shills shim shimmed shimmery shimmied shimmies shimming shimmy shimmying shims shinbone shinbones shindig shindigs shiner shiners shininess shinnied shinnies shinny shinnying shipboard shipboards shipbuilder shipbuilders shipbuilding shipload shiploads shipmate shipmates shipper shippers shipwright shipwrights shipyard shipyards shires shirker shirkers shirr shirred shirring shirrings shirrs shirtsleeve shirtsleeves shirttail shirttails shirtwaist shirtwaists shit shits shittier shittiest shitting shitty shivery shocker shockers shockingly shockproof shoddily shoddiness shoehorn shoehorned shoehorning shoehorns shoemaker shoemakers shoeshine shoeshines shogun shoguns shooter shooters shootings shootout shootouts shoplift shoplifted shoplifting shoplifts shoptalk shopworn shoreline shorelines shortbread shortcake shortcakes shortchange shortchanged shortchanges shortchanging shortcut shortcuts shortcutting shortfalls shorthorn shorthorns shortish shortsighted shortsightedly shortsightedness shortstop shortstops shortwave shortwaves shovelful shovelfuls showbiz showboat showboated showboating showboats showerier showeriest showery showgirl showgirls showily showiness showmanship showoff showoffs showpiece showpieces showplace showplaces showroom showrooms shredder shredders shrewdly shrewish shrift shrike shrikes shrillness shrilly shrinkable shrive shrived shriven shrives shriving shrubbier shrubbiest shrubby shtick shticks shuckses shuffleboard shuffleboards shuffler shufflers shush shushed shushes shushing shutdowns shuteye shutout shutouts shutterbug shutterbugs shuttlecock shuttlecocked shuttlecocking shuttlecocks shyly shyster shysters sibilant sibilants sibyl sibyls sickbed sickbeds sickeningly sidearm sidearms sidebar sidebars sideboard sideboards sideburns sidecar sidecars sidekick sidekicks sidelight sidelights sidereal sidesaddle sidesaddles sidesplitting sidestroke sidestroked sidestrokes sidestroking sideswipe sideswiped sideswipes sideswiping sidewall sidewalls sierras sifter sifters sightings sightread sightseeing sightseer sightseers signally signatories signatory signboard signboards signers signet signets signification significations signings silage silaged silages silaging silencer silencers silica silicate silicates siliceous silicone silicosis silkier silkies silkiest silkworm silkworms silky silverfish silverfishes simian simians simpatico simper simpered simpering simpers simpleness simpleton simpletons simplifications simulators simulcast simulcasted simulcasting simulcasts sinecure sinecures sinfully sinfulness singleton singletons singsong singsonged singsonging singsongs singularities sinkable sinker sinkers sinkhole sinkholes sinuous sinusitis sinusoidal sirocco siroccos sis sisal sises sitar sitars sitcom sitcoms sittings skateboarder skateboarders skedaddle skedaddled skedaddles skedaddling skeet skeletal skeptically skier skiers skiff skiffed skiffing skiffs skillfully skimpiness skinhead skinheads skinless skinniness skintight skitter skittered skittering skitters skivvied skivvies skivvy skivvying skulduggery skullcap skullcaps skycap skycaps skydive skydived skydiver skydivers skydives skydiving skyjack skyjacked skyjacker skyjackers skyjacking skyjacks skylark skylarked skylarking skylarks skyward skywards skywriter skywriters skywriting slackers slackly slackness slags slalom slalomed slaloming slaloms slammer slammers slanderer slanderers slanderous slangier slangiest slangy slantwise slapdash slapdashes slaphappier slaphappiest slaphappy slather slathered slathering slathers slattern slatternly slatterns slaughterer slaughterers slaughterhouse slaughterhouses slaver slavered slavering slavers slavishly slaw slayer slayers slayings sleaze sleazes sleazily sleaziness sledge sledged sledgehammered sledgehammering sledgehammers sledges sledging sleekly sleekness sleepily sleepiness sleeplessness sleepwalk sleepwalked sleepwalker sleepwalkers sleepwalking sleepwalks sleepwear sleepyhead sleepyheads sleetier sleetiest sleety slenderness sleuth sleuths slicer slicers slickers slickly slickness slider sliders slightness slimness slinkier slinkiest slinky slipcover slipcovers slipknot slipknots slippage slippages slipperiness slithery sloe sloes sloop sloops sloppily sloppiness slothfulness slouchier slouchiest slouchy slough sloughed sloughing sloughs sloven slovenliness slovens slowdown slowdowns slowpoke slowpokes slue slued slues sluggard sluggards slugger sluggers sluggishly sluggishness sluing slumberous slumlord slumlords slurp slurped slurping slurps slushier slushiest slushy sluttish slyly smacker smackers smallness smarmier smarmiest smarmy smarten smartened smartening smartens smartness smelter smelters smilingly smirch smirched smirches smirching smithies smithy smoggier smoggiest smoggy smokehouse smokehouses smokeless smokiness smooch smooched smooches smooching smorgasbord smorgasbords smudgier smudgiest smudgy smugness smuttier smuttiest smutty snaffle snaffled snaffles snaffling snafu snafus snakebite snakebites snakier snakiest snaky snapdragon snapdragons snapper snappers snappish snazzier snazziest snazzy sneeringly snifter sniftered sniftering snifters snippier snippiest snippy snit snits snivel snivels snobbier snobbiest snobbishness snobby snooper snoopers snoopier snoopiest snoopy snoot snootiness snoots snorer snorers snorkeler snorkelers snottier snottiest snotty snowboard snowboarded snowboarding snowboards snowbound snowdrop snowdrops snowman snowmen snowmobile snowmobiled snowmobiles snowmobiling snowshoe snowshoeing snowshoes snowsuit snowsuits snuffbox snuffboxes snuffers snuffle snuffled snuffles snuffling soakings soapbox soapboxed soapboxes soapboxing soapiness soapstone soapsuds soberly soberness sobriquet sobriquets sociability sociably socialistic socialite socialites societal socioeconomic sociopath sociopaths sodomite sodomites softener softeners softhearted softies softwood softwoods softy soggily sogginess soiree soirees sol solaria solarium soldierly solecism solecisms solenoid solenoids solicitation solicitations solicitously solicitude solidification solidness soliloquies soliloquy sols solstice solstices solubility solvable solvency solver solvers sombre sombrero sombreros someway someways somnambulism somnambulist somnambulists somnolence somnolent sonar sonars songbird songbirds songster songsters songwriter songwriters sonnies sonny sonority sooth soothingly soothings sooths soothsayer soothsayers sophism sophist sophistries sophists sophomoric soporific soporifics soppier soppiest soppings soppy sorbet sorbets sordidly sordidness sorehead soreheads soreness sorghum sorrel sorrels sorrowfully sorter sorters sortie sortied sortieing sorties sot sots sottish sough soughed soughing soughs soulful soulfully soulfulness soulless soundings soundless soundlessly soundness soundtracks soupcon soupcons soupier soupiest soupy sourdough sourdoughs sourly sourness sourpuss sourpusses souse soused souses sousing southbound southeasterly southeastward southernmost southwards southwester southwesterly southwesters southwestward soviet soviets sower sowers soy soybean soybeans spaceflight spaceflights spaceman spacemen spacesuit spacesuits spacewalk spacewalked spacewalking spacewalks spacey spacier spaciest spaciously spaciousness spadeful spadefuls spadework spake spandex sparely spareness spareribs sparingly sparseness sparsity spartan spasmodically spastic spastics spates spatially speakeasies speakeasy spec specie specifiable specifiers speciously speckle speckled speckles speckling specs spectral spectroscope spectroscopes spectroscopic spectroscopy speeder speeders speedily speedster speedsters speedup speedups speedway speedways spellbinder spellbinders spellers spelunker spelunkers spender spenders spermatozoa spermatozoon spermicide spermicides spheroid spheroidal spheroids sphincter sphincters spiciness spiderier spideriest spidery spiel spieled spieling spiels spiffied spiffier spiffies spiffiest spiffy spiffying spikier spikiest spiky spillage spillages spillway spillways spindle spindled spindles spindling spinet spinets spinier spiniest spinnaker spinnakers spinner spinners spinsterhood spiny spirally spirea spireas spiritless spiritualism spiritualist spiritualistic spiritualists spirituality spirituous spitball spitballs spitefully spitefulness spitfire spitfires spittoon spittoons splashdown splashdowns splashier splashiest splashy splats splatted splatting splay splayed splaying splays splenetic splicer splicers spline splines splittings splodge splotch splotched splotches splotchier splotchiest splotching splotchy splutter spluttered spluttering splutters spoilage spoiler spoilers spoilsport spoilsports spoliation sponger spongers spoonbill spoonbills spoonerism spoonerisms spoor spoored spooring spoors sporadically spored sporing sportier sportiest sportive sportscast sportscaster sportscasters sportscasting sportscasts sportsman sportsmanlike sportsmen sportswear sportswoman sportswomen sporty spotlessly spotlessness spotter spotters spottiness sprat sprats sprayer sprayers spreader spreaders sprightlier sprightliest sprightliness sprightly springiness sprite sprites spritz spritzed spritzes spritzing sprocket sprockets spryly spryness spume spumed spumes spuming spumoni spunkier spunkies spunkiest spunky spuriously spuriousness sputum spyglass spyglasses squab squabbed squabbing squabs squareness squashier squashiest squashy squattered squattering squatters squaw squaws squealer squealers squeamishly squeamishness squeegee squeegeed squeegeeing squeegees squeezer squeezers squiggle squiggled squiggles squigglier squiggliest squiggling squiggly squirmier squirmiest squirmy squish squished squishes squishier squishiest squishing squishy stabbings staccato staccatos staffer staffers stagehand stagehands stagflation staggeringly staggerings stagings staidly stainless stairwell stairwells stakeout stakeouts stalactite stalactites stalagmite stalagmites staleness stalker stalkers stalkings stamen stamens stammerer stammerers stanchion stanchions standoffish standout standouts staph staphylococci staphylococcus stargazer stargazers starkly starkness starless starlet starlets starling starlit starvings stash stashed stashes stashing statehood statehouse statehouses stateless stateliness stateroom staterooms stateside statesmanlike statewide statically stationer stationers stats statuary statuesque statuette statuettes stead steadfastly steadfastness steadiness steads steakhouse steakhouses steamboat steamboats steamer steamers steamroll steamrolled steamrolling steamrolls steamship steamships steed steeds steelier steelies steeliest steely steeplechase steeplechases steeplejack steeplejacks steeply steepness steerage stein steined steining steins stenographic stentorian stepbrother stepbrothers stepchild stepchildren stepdaughter stepdaughters stepfather stepfathers stepmother stepmothers stepparent stepparents steppe steppes steppingstone steppingstones stepsister stepsisters stepson stepsons stereophonic stereoscope stereoscopes stereotypical sterility sternum sternums steroid steroids stevedore stevedores stewardship stickiness stickleback sticklebacks stickpin stickpins stickup stickups sties stiffener stiffeners stiflings stile stiled stiles stiletto stilettos stiling stillbirth stillbirths stilt stilts stingily stingray stingrays stinker stinkers stinkings stipend stipends stipple stippled stipples stippling stirrer stirrers stirrings stoat stoats stochastic stockiness stockroom stockrooms stodginess stoic stoically stoicism stoics stoker stokers stolidity stomachache stomachaches stonewall stonewalled stonewalling stonewalls stoneware stonework stonily stooge stooges stopcock stopcocks stoplight stoplights stoppable storefront storefronts storied stormily storminess storybook storybooks storyteller storytellers stoutly stoutness stovepipe stovepipes strafe strafed strafes strafing stragglier straggliest straggly straightaway straightaways straightedge straightedges straightness straiten straitened straitening straitens stranglehold strangleholds strangler stranglers strangulate strangulated strangulates strangulating strapless straplesses strategically strategist strategists stratification streakier streakiest streaky streetlight streetlights streetwalker streetwalkers streetwise strenuousness strep streptococcal streptococci streptococcus streptomycin stretchier stretchiest stretchy striated stricture strictures strident stridently strikeout strikeouts strikingly stringed stringency stringently stringer stringers stripling strippers striptease stripteased stripteases stripteasing strobe strobes strongbox strongboxes strontium strop strophe strophes stropped stropping strops structurally strudel strudels strumpet strumpeted strumpeting strumpets strychnine stubblier stubbliest stubbly stubbornly stubbornness stucco stuccoed stuccoes stuccoing studentships studiously stuffily stuffiness stultification stultified stultifies stultify stultifying stumbler stumblers stumpier stumpiest stumpy stunningly stupefaction stupendously sturdily sturdiness sturgeon sturgeons stutterer stutterers sty stying styli stylishly stylishness stylist stylistically stylistics stylists styluses stymie stymied stymieing stymies styptic styptics suavely suavity subatomic subatomics subbasement subbasements subclass subcompact subcompacts subcontinent subcontinents subcontract subcontracted subcontracting subcontractor subcontractors subcontracts subculture subcultures subcutaneous subgroups subhead subheading subheadings subheads subhuman subhumans subjection subjectively subjectivity subjoin subjoined subjoining subjoins subjugation subjunctives sublease subleased subleases subleasing sublimate sublimated sublimates sublimating sublimation sublimely subliminal subliminally sublimity submergence submerse submersed submerses submersible submersibles submersing submitter suborbital subordination suborn subornation suborned suborning suborns subplot subplots subpoena subpoenaed subpoenaing subpoenas subprograms subservience subsidence subsoil subsoiled subsoiling subsoils subsonic subspace substantiation substantiations substantive substantives substation substations substrata substrate substratum substructure substructures subsume subsumed subsumes subsuming subsystems subteen subteens subtitle subtitled subtitles subtitling subtotal subtotals subtrahend subtrahends subtropical suburbanite suburbanites suburbia subversion succinctness succotash succulence suchlike sucrose suddenness sudsier sudsiest sudsy suet sufferance sufficiency suffocatings suffragan suffragans suffragette suffragettes suffragist suffragists suffuse suffused suffuses suffusing suffusion sugarcane sugarcoat sugarcoated sugarcoating sugarcoats sugarless suggestible suggestively sukiyaki sulfate sulfates sulfide sulfides sulkily sulkiness sullenly sullenness sullied sullies sully sullying sultana sultanas sultanate sultanates sumac summation summations summerhouse summerhouses summerier summeriest summertime summery summitry summoner summoners sumo sump sumps sunbather sunbathers sunbeam sunbeams sunblock sunblocks sunbonnet sunbonnets sunder sundered sundering sunders sunfish sunfishes sunlamp sunlamps sunless sunroof sunroofs sunspot sunspots sunstroke superabundance superabundances superabundant superannuate superannuated superannuates superannuating supercharge supercharged supercharger superchargers supercharges supercharging supercilious superconductivity superconductor superconductors superego superegos superficiality superfluity superhighway superhighways superintend superintended superintendence superintendency superintending superintends superlatively superman supermen supernova supernovae supernovas supernumeraries supernumerary superpower superpowers superstitiously supertanker supertankers supervene supervened supervenes supervening supine supped supping supplemental suppleness suppliant suppliants supplicant supplicants supplicate supplicated supplicates supplicating supplication supplications supportable supposings suppositories suppository suppurate suppurated suppurates suppurating suppuration supranational supremacist supremacists sups surcease surceased surceases surceasing surefire surefooted sureness sureties surety surfeit surfeited surfeiting surfeits surfer surfers surgically surliness surmountable surplice surplices surprisings surrealism surrealist surrealistic surrealists surreals surreptitiously surrey surreys surrogate surrogates surtax surtaxed surtaxes surtaxing susceptibility sushi suspenseful suture sutured sutures suturing svelte svelter sveltest swaddle swaddled swaddles swaddling swag swagged swagging swags swain swains swallowtail swallowtails swami swamis swank swanked swanker swankest swankier swankies swankiest swanking swanks swanky sward swards swash swashbuckler swashbucklers swashbuckling swashed swashes swashing swastika swastikas swatch swatches swath swaths swatter swattered swattering swatters swaybacked swearer swearers swearword swearwords sweatier sweatiest sweatpants sweatshirt sweatshirts sweatshop sweatshops sweetbread sweetbreads sweetbrier sweetbriers sweetener sweeteners sweetie sweeties sweetish sweetmeat sweetmeats swellhead swellheaded swellheads swelter sweltered sweltering swelterings swelters swiftness swimmer swimmers swimsuit swimsuits swinger swingers swinish swirlier swirliest swirly switchback switchbacks switchblade switchblades swordplay swordsman swordsmen sybarite sybarites sybaritic sycamore sycamores sycophant sycophantic sycophants syllabic syllabication syllabification syllabified syllabifies syllabify syllabifying syllogism syllogisms syllogistic sylph sylphs sylvan symbioses symbiosis symbiotic symbolically symmetrically symmetries symposium symposiums sync synced synchronously syncing syncopate syncopated syncopates syncopating syncopation syncs syndication synergism synergistic synergy synod synods syntactical syntactics synthetically syphilitic syphilitics syrupy systemic systemics systolic t tableau tableaux tableland tablelands tableware tabular tabulator tabulators tachometer tachometers tacitness taciturnity tackiness tackler tacklers tactically tactician tacticians tactile tactlessness tad tads taffeta taffies taffy tailcoat tailcoats tailless tailpipe tailpipes tailwind tailwinds takeaways takeout takeouts takeovers takings talkativeness tallness tallyho tallyhoed tallyhoing tallyhos tam tamable tamale tamales tamarind tamarinds tamers tamp tamped tamping tampon tampons tamps tams tanager tanagers tangelo tangelos tangibility tangibly tangier tangies tangiest tangy tankful tankfuls tanneries tanners tannery tannin tansy tapeworm tapeworms tapioca tapir tapirs taproom taprooms taproot taproots tardily tare tared tares taring tarmac tarmacked tarmacking tarmacs taro taros tarot tarots tarp tarpon tarpons tarps tarragon tarragons tartly tartness taskmaster taskmasters tastelessly tastelessness taster tasters tastiness tat tats tatted tatter tattered tattering tatters tatting tattler tattlers tattletale tattletales tattooist tattooists taupe tautly tautness tautological tautologies tawdriness taxidermist taxidermists taxidermy taxings taxonomic taxonomies taxonomy teabag teachable teakettle teakettles teal teals tearfully teargas teargases teargassed teargassing tearier teariest tearjerker tearjerkers tearoom tearooms teary teasel teasels teaser teasers teaspoonful teaspoonfuls teatime technocracy technocrat technocrats technologist technologists techs tectonics tediousness teenier teeniest teeny telecast telecaster telecasters telecasting telecasts telecommunication telecommute telecommuted telecommuter telecommuters telecommutes telecommuting teleconference teleconferenced teleconferences teleconferencing telegrapher telegraphers telegraphic telegraphy telekinesis telemarketing telemeter telemeters telemetries telemetry telepathically telephonic telephony telephoto telephotos telescopic telethon telethons teletypes teletypewriter teletypewriters televangelist televangelists telex telexed telexes telexing tellingly temblor temblors temerity temp temped tempera temperamentally temperas tempestuously tempestuousness temping templates temporally temps tempter tempters temptingly temptings temptress temptresses tempura tenability tenaciously tendentious tendentiously tendentiousness tenderfoot tenderfoots tenderhearted tenderloin tenderloins tendinitis tenfold tenfolds tenon tenons tenpin tenpins tensely tenseness tensile tensor tenuously tenuousness tequila tequilas tercentenaries tercentenary termagant termagants terminable terminations terminological tern terned terning terns terrapin terrapins terrarium terrariums terrifically terrifyingly terry tertiary testamentary testate testates testier testiest testily testiness testosterone testy tetrahedron tetrahedrons textural thalami thalamus thallium thankfulness thanklessly thanksgiving thanksgivings theatrically theed theeing thees theism theistic thematic thematically thematics thenceforth thenceforward thenceforwards theocracies theocracy theocratic theoretician theoreticians theosophy therapeutically therapeutics thereabout therefrom thereto therewith thermally thermionic thermodynamic thermonuclear thermoplastic thermoplastics thermos thermoses thermostatic thermostatics thespian thespians thiamine thickener thickeners thickenings thickset thieved thievery thieving thievish thighbone thighbones thimbleful thimblefuls thine thingamajig thingamajigs thinners thinness thirdly thirstily thistledown thither tho thoracic thorax thoraxes thorium thoroughgoing thoroughness thoughtlessness thrall thralldom thralled thralling thralls thrasher thrashers thrashings threateningly threatenings threefold threescore threescores threesome threesomes threnodies threnody thriftily thriftiness thrivings throatier throatiest throatily throatiness throaty throe throed throeing throes thromboses thrombosis throwaways thrower throwers thrum thrummed thrumming thrums thrush thrushes thruway thruways thumbnail thumbnails thumbscrew thumbscrews thunderclap thunderclaps thundercloud thunderclouds thunderhead thunderheads thundershower thundershowers thwack thwacked thwacking thwacks thymus thymuses thyself ti tibia tibiae tic ticker tickers tics tiddlywinks tidewater tidewaters tidily tidiness tidings tiebreaker tiebreakers tightfisted tigress tigresses tildes tillable tillage tiller tillers timbered timberland timberline timberlines timbre timbres timelessness timeliness timepiece timepieces timeworn timorous timorously timpani timpanist timpanists tincture tinctured tinctures tincturing tinderbox tinderboxes tinfoil tinglier tingliest tingly tinsmith tinsmiths tintinnabulation tintinnabulations tipper tippers tipple tippled tippler tipplers tipples tippling tipsily tipster tipsters tiptop tiptops tiredness tirelessly tirelessness tiresomely tiresomeness tirings titan titanic titanium titans tithe tithed tithes tithing titillation titmice titmouse tittle tittled tittles tittling titular tizzies tizzy toadied toadies toady toadying toastier toasties toastiest toastmaster toastmasters toasty tobacconist tobacconists tocsin tocsins toddies toddy toehold toeholds tofu tog togetherness toggled toggles toggling togs toiler toilers toiletries toiletry toilette toilsome toke toked tokenism tokes toking tolerantly toleration tollbooth tollbooths tollgate tollgates tom tomfooleries tomfoolery toms tonalities tonality toneless toner tonier toniest tonsillectomies tonsillectomy tonsorial tonsure tonsured tonsures tonsuring tony toolbar toolbars toolbox toolboxes toothed toothier toothiest toothless toothsome toothy topcoat topcoats topically topknot topknots topless topmast topmasts topmost topographer topographers topographic topographical topological topologically toppings topsail topsails topside topsides topsoil toque toques tor torchlight toreador toreadors torpid torpidity torpor torqued torques torquing tors torsion tort torte tortes tortoiseshell tortoiseshells torts tortuously torturer torturers torus tossup tossups totemic touche touchingly touchstone touchstones toughly tourism tourmaline tourney tourneys towhead towheaded towheads townhouse townhouses townsfolk township townships townsman townsmen towpath towpaths toxicity toxicologist toxicologists toxicology traceable tracer traceries tracers tracery trachea tracheae tracheotomies tracheotomy tracings tracker trackers tractable tradesman tradesmen traditionalists traduce traduced traduces traducing trafficker traffickers tragedian tragedians tragicomedies tragicomedy trailblazer trailblazers traipse traipsed traipses traipsing trajectories trajectory tram trammed trammel trammels tramming trams tranquilly transceiver transceivers transcendence transcendent transcendental transcendentalism transcendentalist transcendentalists transcendentally transducer transducers transept transepts transferal transferals transference transfiguration transfigure transfigured transfigures transfiguring transfinite transfix transfixed transfixes transfixing transfuse transfused transfuses transfusing transgressor transgressors transience transiency transitively transliterate transliterated transliterates transliterating transliterations translucence transmigrate transmigrated transmigrates transmigrating transmigration transmissible transmittable transmittal transmutation transmutations transmute transmuted transmutes transmuting transnational transnationals transoceanic transom transoms transpiration transplantation transponder transponders transporter transporters transposition transpositions transsexual transsexuals transship transshipment transshipped transshipping transships transubstantiation transversely transvestism transvestite transvestites trapdoors trapezoidal trappable trapshooting trashcans travail travailed travailing travails travelogue travelogues treacherously treacled treacles treacling treadle treadled treadles treadling treasonable treasonous treatable treeless treetop treetops trefoil trefoils tremolo tremolos tremulous tremulously trenchant tress tresses triad triads triage triangulation triathlon triathlons tribalism tribesman tribesmen tribune tribunes trice triceps tricepses triceratops trickiness trident tridents triennial triennials trifler triflers trifocals trig triggest triglyceride triglycerides trigonometric trike triked trikes triking trilateral trilaterals trillionth trillionths trimaran trimarans trimly trimmers trimmings trimness trinities tripartite triplied triplies triply triplying triptych triptychs trisect trisected trisecting trisects tritely triteness triumphal triumphantly triumvirate triumvirates trivet trivets trivialities trochee trochees troika troikas trollop trolloped trolloping trollops trombonist trombonists tromp tromped tromping tromps troopship troopships trope tropes tropic tropics tropism tropisms troposphere tropospheres troth trothed trothing troths trotter trotters troubadour troubadours troubleshoot troubleshooted troubleshooter troubleshooters troubleshooting troubleshoots troubleshot trouper troupers trousseau trousseaux troy troys trucker truckers truckle truckled truckles truckling truckload truckloads truculence truculent truculently trumpery trumpeter trumpeters truncheon truncheons trundle trundled trundles trundling truss trussed trusses trussing trusteeship trusteeships trustfully trustfulness trustworthiness tryst trysted trysting trysts ts tsunami tsunamis tubbier tubbiest tubby tubeless tuber tubercle tubercles tubercular tuberculous tuberous tubers tucker tuckered tuckering tuckers tugboat tugboats tulle tumbledown tumbleweed tumbleweeds tumbrel tumbrels tumid tun tunefully tuneless tunelessly tungsten tunnies tunny tuns turbid turbojet turbojets turboprop turboprops turbot turbots turbulently turd turds turgidity turgidly turmeric turmerics turnabout turnabouts turnarounds turncoat turncoats turners turnkey turnkeys turnoff turnoffs turpitude turtledove turtledoves tush tushed tushes tushing tusked tussock tussocks tutelage tutu tutus tux tuxes twaddle twaddled twaddles twaddling twain tweedier tweediest tweeds tweedy tweeter tweeters twerp twerps twiggier twiggiest twiggy twill twilled twirler twirlers twit twits twitted twitting twofer twofers twofold twofolds twosome twosomes tyke tykes tympanum tympanums typecast typecasting typecasts typefaces typescripts typesetters typewrite typewrites typewriting typewritten typewrote typo typographer typographers typographically typography typos tyrannically tyrannosaur tyrannosaurs tyrannosaurus tyrannosauruses tyrannous tyro tyros u ubiquitously ubiquity uh ukulele ukuleles ulcerate ulcerated ulcerates ulcerating ulceration ulcerous ulna ulnae ultraconservative ultraconservatives ultramarine ultras ultrasonically ultrasound ultrasounds ululate ululated ululates ululating um umbel umbels umber umbilical umbilici umbilicus umbrage umbraged umbrages umbraging umiak umiaks umlaut umlauts ump umped umping umps umpteenth unabashed unabated unabridged unabridgeds unaccented unacceptability unaccompanied unaccustomed unacknowledged unacquainted unadorned unadvised unafraid unaided unalterable unalterably unannounced unanticipated unappealing unappreciated unappreciative unapproachable unashamed unashamedly unasked unassailable unassisted unattributed unauthenticated unavailing unavoidably unbar unbarred unbarring unbars unbeaten unbeknown unbelief unbend unbending unbends unbent unbidden unbind unbinding unbinds unblushing unbolt unbolted unbolting unbolts unbosom unbosomed unbosoming unbosoms unbound unbounded unbranded unbridled unbuckle unbuckled unbuckles unbuckling unbutton unbuttoned unbuttoning unbuttons uncalled uncannily uncaring uncased uncatalogued unceasingly uncensored unceremonious unceremoniously uncertainly unchanging uncharacteristic uncharacteristically uncharitably uncharted unchecked uncivil unclaimed unclasp unclasped unclasping unclasps unclassified uncleanlier uncleanliest uncleanly uncleanness unclearer unclearest unclothe unclothed unclothes unclothing uncluttered uncoil uncoiled uncoiling uncoils uncollected uncommitted uncommonly uncommunicative uncomplaining uncompleted uncomplicated uncomplimentary uncomprehending uncompressed uncompromisingly unconcern unconcernedly unconcerning unconcerns unconquerable unconscionable unconscionably unconsciousness unconsidered uncontaminated uncontested uncontrollably unconventionally unconvincingly uncooked uncooperative uncoordinated uncork uncorked uncorking uncorks uncorrelated uncorroborated uncounted uncouple uncoupled uncouples uncoupling uncritical unction unctions unctuous unctuously unctuousness uncultivated undated undeceive undeceived undeceives undeceiving undecipherable undeclared undefeated undefended undefinable undelivered undemanding undemonstrative undependable underachieve underachieved underachiever underachievers underachieves underachieving underact underacted underacting underacts underage underarm underarmed underarming underarms underbellies underbelly underbid underbidding underbids undercarriage undercarriages undercharge undercharged undercharges undercharging underclass underclassman underclassmen underclothes underclothing undercoat undercoated undercoating undercoats underdeveloped underdone underemployed underexpose underexposed underexposes underexposing underfed underfeed underfeeding underfeeds underfunded undergrad undergrads underhand underhandedly underlains underling undermost underpaid underpay underpaying underpays underpin underpinned underpinning underpinnings underpins underplay underplayed underplaying underplays undersea underseas undersecretaries undersecretary undersell underselling undersells undershoot undershooting undershoots undershorts undershot undersign undersigned undersigning undersigns undersized underskirt underskirts undersold understaffed understandingly underused undervalue undervalued undervalues undervaluing underwriter underwriters undeservedly undeserving undesirability undetectable undetermined undeterred undies undignified undiluted undiminished undisciplined undisclosed undiscovered undiscriminating undisguised undisputed undistinguished undivided undulant undulate undulated undulates undulating undulation undulations unearned unease uneaten unedited unembarrassed unemotional unending unendurable unenforceable unenthusiastic unenviable unequally unequivocally unerringly unevenness uneventfully unexampled unexceptionable unexceptional unexciting unexplored unexpurgated unfailingly unfairness unfaithfully unfaithfulness unfamiliarity unfashionable unfathomable unfeelingly unfeigned unfetter unfettered unfettering unfetters unflagging unflappable unflattering unflinching unflinchingly unforeseeable unforgettably unforgiving unformed unfrequented unfriendliness unfrock unfrocked unfrocking unfrocks unfulfilled unfurnished ungainliness ungentlemanly ungovernable ungracious ungratefully ungratefulness ungrudging unguarded unguent unguents ungulate ungulates unhand unhanded unhanding unhands unharmed unhealthful unheeded unhesitating unhesitatingly unhindered unhinge unhinged unhinges unhinging unhitch unhitched unhitches unhitching unholier unholiest unholy unhorse unhorsed unhorses unhorsing unhurried unhurt unicameral unicycles unidentifiable unidirectional unimaginable unimpaired unimpeachable unimplementable unimplemented unimpressive uninhabitable uninhabited uninjured uninsured unintelligibly uninterpreted uninterrupted uninvited uninviting unisex unitary universality unkindness unknowable unknowing unknowingly unknowings unlace unlaced unlaces unlacing unlatch unlatched unlatches unlatching unlawfully unleaded unlearn unlearning unlearns unleavened unlettered unlicensed unlikelihood unlisted unloose unloosed unlooses unloosing unloved unluckily unmade unmake unmakes unmaking unmanageable unmanlier unmanliest unmanly unmannerly unmatched unmemorable unmentionable unmentionables unmerciful unmercifully unmindful unmoral unnaturally unneeded unnoticeable unnumbered unobjectionable unobservant unobserved unobstructed unobtrusive unobtrusively unoffensive unofficially unopened unopposed unpainted unpalatable unpardonable unpatriotic unpaved unperturbed unpin unpinned unpinning unpins unplanned unplug unplugged unplugging unplugs unplumbed unpolluted unpredictability unprejudiced unpremeditated unpretentious unpreventable unproductive unprofessional unprofitable unpromising unprompted unpronounceable unproved unpunished unquenchable unquestioned unquestioning unquestioningly unquote unquoted unquotes unquoting unreachable unreadier unreadiest unready unrealistically unreasonableness unreasoning unreconstructed unrecorded unrefined unregenerate unregistered unregulated unrehearsed unreleased unrelentingly unrelieved unremitting unrepentant unrequited unreserved unresponsive unrestrained unrewarding unripe unriper unripest unroll unrolled unrolling unrolls unromantic unruliness unsaddle unsaddled unsaddles unsaddling unsalted unsanctioned unsatisfying unsaturated unschooled unscramble unscrambled unscrambles unscrambling unscrupulously unscrupulousness unseal unsealed unsealing unseals unseasonably unseasoned unseeing unseemliness unseens unselfish unselfishly unselfishness unsent unsentimental unshakable unshaven unsheathe unsheathed unsheathes unsheathing unsightliness unskillful unsmiling unsnap unsnapped unsnapping unsnaps unsnarl unsnarled unsnarling unsnarls unsociable unsold unsparing unspeakably unspecific unspoiled unspoken unsportsmanlike unstated unsteadier unsteadiest unsteadily unsteadiness unsteady unstop unstoppable unstopped unstopping unstops unstressed unstrung unstudied unsubstantial unsubtle unsuitably unsupervised unsurpassed unsurprising unsuspected unsweetened unswerving unsympathetic untainted untamed untapped untaught untested unthinking unthinkingly untidiness untimelier untimeliest untimeliness untimely untiringly untitled untouchable untouchables untoward untreated untried untroubled untruth untruthful untruthfully untruths untutored untwist untwisted untwisting untwists unutterable unutterably unvarnished unvarying unverified unvoiced unwarier unwariest unwariness unwavering unwed unwholesome unwieldiness unwillingly unwisely unwitting unwonted unworldly unworthier unworthiest unworthiness unyielding unzip unzipped unzipping unzips upbraid upbraided upbraiding upbraids upchuck upchucked upchucking upchucks upcoming upcountry updater upfront upland uplands upliftings upmarket uppercase upperclassman upperclassmen uppercut uppercuts uppercutting uppity upraise upraised upraises upraising uproarious uproariously upscale upsides upstage upstaged upstages upstaging upstate upsurge upsurged upsurges upsurging upswing upswings uptakes urbanity urea urethra urethrae uric urinal urinals urinalyses urinalysis urinary urination urologist urologists urology usherette usherettes usurer usurers usurious usurpation usurper usurpers usury uterine utilitarians utopia utopias uttermost uvula uvular uvulars uvulas v vacantly vacationer vacationers vacillation vacillations vacuity vacuously vagrancy vainglorious vainglory vainly valance valanced valances valancing vale valedictorian valedictorians valedictories valedictory valence valences vales valiantly validations validness valorous valuation valuations vamoose vamoosed vamooses vamoosing vamp vamped vamping vamps vanadium vanishings vantage vantages vapid vapidity vapidness vaporous variability variably variances variate varicose varicoses variegate variegated variegates variegating varlet varlets varmint varmints vascular vasectomies vasectomy vassal vassalage vassaled vassaling vassals vaudeville vaulter vaulters vaunt vaunted vaunting vaunts vectored vectoring veep veeps vegan vegans vegetate vegetated vegetates vegetating vegetative veggie veggies vehemence vehicular veld velds vellum velveteen venal venality venally vendetta vendettas venereal vengefully venial venomously venous ventral ventrals ventricular ventriloquism venturesome venturous veracious verbena verbenas verdant verdigris verdigrised verdigrises verdigrising verdure verifiable verily verisimilitude veritably verities verity vermicelli vermilion verminous vermouth vernal versification versified versifies versify versifying vertebral vertex vertexes vertiginous vesicle vesicles vesper vespers vestigial vestries vestry vetch vetches vexatious viand viands vibe vibes vibrancy vibrantly vibraphone vibraphones vibrato vibrator vibrators vibratos viburnum viburnums vicarage vicarages viceroy viceroys vichyssoise viciousness vicissitude vicissitudes victoriously victual victuals vicuna vicunas videocassette videocassettes videodisc videodiscs viewfinder viewfinders viewings vigilantism vigilantly vignette vignetted vignettes vignetting vilely vileness vilification villein villeins vim vinaigrette vindication vindications vindicator vindicators vindictively vindictiveness vinegary vintner vintners viol violable violator violators violinist violinists violist violists violoncello violoncellos viols virago viragoes vireo vireos virginal virginals virgule virgules virology virtuosity virtuousness virulence virulently visage visages viscera visceral viscid viscosity viscount viscountess viscountesses viscounts viscous viscus vitiate vitiated vitiates vitiating vitiation viticulture vitreous vitreouses vitriol vituperate vituperated vituperates vituperating vituperation vituperative viva vivace vivaces vivaciousness vivaed vivaing vivas vividness vivified vivifies vivify vivifying viviparous vixen vixenish vixens vizier viziers vocalic vocalics vocally vocative vocatives vociferate vociferated vociferates vociferating vociferation voguish voiceless voile volatility vole voled voles voling voltaic voltmeter voltmeters volubility voluble volubly voluminously voluptuaries voluptuary voluptuously voluptuousness voodooism voraciously voracity votaries votary votive vouchsafe vouchsafed vouchsafes vouchsafing voyeur voyeurism voyeuristic voyeurs vs vulgarism vulgarisms vulgarly vulnerably vulva vulvae w wackier wackiest wackiness wacko wackos wacky wader waders wadi wadis waggish waggle waggled waggles waggling wainscot wainscoted wainscoting wainscotings wainscots waistband waistbands waistcoat waistcoated waistcoating waistcoats wakeful wakefulness wale waled wales waling walkway walkways wallabies wallaby wallboard walleye walleyed walleyes wallflower wallflowers wallopings wampum wanderlust wanderlusts wangle wangled wangles wangling wanly wannabe wannabes wantings wantonly wantonness wapiti wapitis warbler warblers warder wardered wardering warders wardroom wardrooms ware wares warhorse warhorses warily wariness warlock warlocks warlord warlords warmers warmhearted warmonger warmongering warmongers warship warships warthog warthogs wartier wartiest warty washbasin washbasins washboard washboards washbowl washbowls washerwoman washerwomen washstand washstands washtub washtubs waspish wassail wassailed wassailing wassails wastefulness wastepaper waster wastered wastering wasters wastrel wastrels watchband watchbands watcher watchers watchfully watchfulness watchmaker watchmakers watchtower watchtowers watercourse watercourses watercraft watercress waterfowl waterfowls waterline waterlines waterside watersides waterspout waterspouts wattage wattle wattled wattles wattling wavelet wavelets waviness waxen waxiness waxwing waxwings waxwork waxworks wayfarer wayfarers wayfaring wayfarings waywardly waywardness weakfish weakfishes weal weals wealthiness weaponless wearable wearer wearers weathercock weathercocked weathercocking weathercocks weatherman weathermen weatherproof weatherproofed weatherproofing weatherproofs website websites weeder weeders weeknight weeknights weeper weepers weepier weepies weepiest weepings weepy weevil weevils weft wefted wefting wefts weightiness weightless weightlessness weightlifter weightlifters weightlifting weir weirdly weired weiring weirs welkin wellspring wellsprings welsh welshed welshes welshing welterweight welterweights wen wench wenches wend wended wending wends wens westbound westerner westerners westernmost westwards wetback wetbacks wetland wetlands wetly wetness whalebone wham whammed whammies whamming whammy whams whatchamacallit whatchamacallits whatnot wheal wheals wheaten wheatens wheelbase wheelbases wheeler wheelwright wheelwrights wheezier wheeziest wheezy whelk whelked whelks whelp whelped whelping whelps whences whereat wherefore wherefores whereof whereon wheresoever whetstone whetstones whey whimsicality whimsically whimsier whimsies whimsiest whimsy whiner whiners whinier whiniest whiny whipcord whiplash whiplashes whippersnapper whippersnappers whippet whippets whippings whippoorwill whippoorwills whirligig whirligigs whist whistler whistlers whit whitecap whitecaps whited whitefish whitefishes whitener whiteners whiteness whitewall whitewalls whither whithered whithering whithers whiting whitings whitish whits whitter whittler whittlers whodunit whodunits wholeness wholesomeness whomever whomsoever whoopee whoopees whoosh whooshed whooshes whooshing whopping whoppings whorehouse whorehouses whorl whorled whorls whosoever wickerwork wideness widowhood wiener wieners wifelier wifeliest wifely wigeon wigeons wiggler wigglers wigglier wiggliest wiggly wight wighted wighting wights wigwag wigwagged wigwagging wigwags wildebeest wildebeests wildflower wildflowers wildfowl wile wiled wiles wiliness wiling willfulness willies willowier willowiest willowy wimp wimped wimpier wimpiest wimping wimple wimpled wimples wimpling wimps wimpy windbag windbags windbreak windbreaker windbreakers windbreaks windburn windburned windburning windburns windiness windjammer windjammers windlass windlasses windowed windowsill windowsills windsock windsocks windstorm windstorms windsurf windsurfed windsurfing windsurfs windswept windup windups windward wineglass wineglasses wineries winery winger wingless wingspan wingspans wingspread wingspreads wingtip wingtips winnow winnowed winnowing winnows wino winos winsomely wintergreen wireless wirelesses wiretap wiretapped wiretapping wiretaps wiriness wiseacre wiseacres wisher wishers wishfully wisteria wisterias wistfulness witchery withal witlessly wittily wittiness wittingly wizardry woebegone woeful woefuller woefullest woefully wolfhound wolfhounds wolfish wolfram wolverine wolverines womanish womanlier womanliest womanlike womanliness womanly womenfolk womenfolks wonderment wondrously wonted woodbine woodcarving woodcarvings woodcock woodcocks woodcraft woodcut woodcuts woodcutter woodcutters woodcutting woodenly woodenness woodiness woodman woodmen woodpile woodpiles woodshed woodsheds woodsier woodsiest woodsy woodworking woodworm wooer wooers woofer woofers woolgathering woolliness woozier wooziest wooziness woozy wordiness wordplay workaday workaholic workaholics workday workdays workfare workhorse workhorses workhouse workhouses workingman workingmen workloads workmanlike workplaces worksheet worksheets workweek workweeks worldliness wormier wormiest wormwood wormy worrier worriers worryings worrywart worrywarts worshipful worthily worthiness worthlessness wrack wraith wraiths wraparound wraparounds wrathful wrathfully wreckers wretchedly wretchedness wriggler wrigglers wrigglier wriggliest wriggly wrinklier wrinklies wrinkliest wrinkly wristband wristbands wrongful wrongfully wrongfulness wrongheaded wrongheadedly wrongheadedness wrongness wroth wryly wryness wuss wusses x xenon xenophobic xerographic xerography xylem xylophonist xylophonists y ya yachtsman yachtsmen yahoo yahoos yammer yammered yammering yammers yardage yardages yardarm yardarms yarmulke yarmulkes yaw yawed yawing yawl yawls yaws ye yea yeah yeahs yearbook yearbooks yeas yeastier yeastiest yeasty yellowish yeoman yeomen yep yeps yeshiva yeshivas yest yesteryear yieldings yip yipped yippee yippees yipping yips yo yogi yogis yon yore youngish youthfully youthfulness yttrium yucca yuccas yuck yucked yuckier yuckiest yucking yucks yucky yuk yukked yukking yuks yule yuletide yum yummier yummiest yummy yup yuppie yuppies yups z zaniness zap zapped zapping zaps zealot zealots zealously zealousness zebu zebus zed zeds zephyr zephyrs zeppelin zeppelins zestful zestfully zilch zing zinged zinger zingers zinging zings zinnia zinnias zippier zippiest zippy zircon zirconium zircons zit zither zithers zits zodiacal zonal zonked zwieback zygote zygotes """.split()) def score_scowl(word): """ >>> score_scowl('zing') 1 """ if word in SCOWL10: return 4 if word in SCOWL20: return 3 if word in SCOWL35: return 2 if word in SCOWL50: return 1 return 0 def score_scowl_substrings(word): """ >>> score_scowl_substrings('zing') 1 >>> score_scowl_substrings('totallyzonked') 15 """ result = score_scowl(word) for index in range(1, len(word)): if index > 1: # print word[:index], score(word[:index]) result += score_scowl(word[:index]) if index < len(word) - 1: # print word[index:], score(word[index:]) result += score_scowl(word[index:]) # logging.debug('%s.scowl = %d', word, result) return result if __name__ == '__main__': import doctest doctest.testmod()
susansalkeld/discsongs
refs/heads/master
discsongs/lib/python2.7/site-packages/flask/testsuite/deprecations.py
563
# -*- coding: utf-8 -*- """ flask.testsuite.deprecations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests deprecation support. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest from flask.testsuite import FlaskTestCase, catch_warnings class DeprecationsTestCase(FlaskTestCase): """not used currently""" def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DeprecationsTestCase)) return suite
openstack/solum
refs/heads/master
doc/source/conf.py
2
# 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 os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinxcontrib.pecanwsme.rest', 'sphinxcontrib.httpdomain', 'wsmeext.sphinxext', 'openstackdocstheme', ] wsme_protocols = ['restjson', 'restxml'] suppress_warnings = ['app.add_directive'] # autodoc generation is a bit aggressive and a nuisance when doing heavy # text edit cycles. # execute "export SPHINX_DEBUG=1" in your terminal to disable # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'solum' copyright = u'2014, Solum Contributors' # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'native' # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme_path = ["."] # html_theme = '_theme' html_theme = 'openstackdocs' html_static_path = ['_static'] # openstackdocstheme options openstackdocs_repo_name = 'openstack/solum' openstackdocs_pdf_link = True openstackdocs_auto_name = False openstackdocs_bug_project = 'solum' openstackdocs_bug_tag = '' # Output file base name for HTML help builder. htmlhelp_basename = '%sdoc' % project # -- Options for manual page output ------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('man/solum-db-manage', 'solum-db-manage', u'Script which helps manage specific database operations', [u'Solum Developers'], 1), ] # If true, show URL addresses after external links. man_show_urls = True # -- Options for LaTeX output ------------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'doc-solum.tex', u'Solum Documentation', u'OpenStack Foundation', 'manual'), ] latex_domain_indices = False latex_elements = { 'makeindex': '', 'printindex': '', 'preamble': r'\setcounter{tocdepth}{3}', 'maxlistdepth': '10', } # Disable usage of xindy https://bugzilla.redhat.com/show_bug.cgi?id=1643664 latex_use_xindy = False # Disable smartquotes, they don't work in latex smartquotes_excludes = {'builders': ['latex']}
sestrella/ansible
refs/heads/devel
lib/ansible/modules/cloud/rackspace/rax_dns_record.py
57
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_dns_record short_description: Manage DNS records on Rackspace Cloud DNS description: - Manage DNS records on Rackspace Cloud DNS version_added: 1.5 options: comment: description: - Brief description of the domain. Maximum length of 160 characters data: description: - IP address for A/AAAA record, FQDN for CNAME/MX/NS, or text data for SRV/TXT required: True domain: description: - Domain name to create the record in. This is an invalid option when type=PTR loadbalancer: description: - Load Balancer ID to create a PTR record for. Only used with type=PTR version_added: 1.7 name: description: - FQDN record name to create required: True overwrite: description: - Add new records if data doesn't match, instead of updating existing record with matching name. If there are already multiple records with matching name and overwrite=true, this module will fail. default: true type: bool version_added: 2.1 priority: description: - Required for MX and SRV records, but forbidden for other record types. If specified, must be an integer from 0 to 65535. server: description: - Server ID to create a PTR record for. Only used with type=PTR version_added: 1.7 state: description: - Indicate desired state of the resource choices: - present - absent default: present ttl: description: - Time to live of record in seconds default: 3600 type: description: - DNS record type choices: - A - AAAA - CNAME - MX - NS - SRV - TXT - PTR required: true notes: - "It is recommended that plays utilizing this module be run with C(serial: 1) to avoid exceeding the API request limit imposed by the Rackspace CloudDNS API" - To manipulate a C(PTR) record either C(loadbalancer) or C(server) must be supplied - As of version 1.7, the C(type) field is required and no longer defaults to an C(A) record. - C(PTR) record support was added in version 1.7 author: "Matt Martz (@sivel)" extends_documentation_fragment: - rackspace - rackspace.openstack ''' EXAMPLES = ''' - name: Create DNS Records hosts: all gather_facts: False tasks: - name: Create A record local_action: module: rax_dns_record credentials: ~/.raxpub domain: example.org name: www.example.org data: "{{ rax_accessipv4 }}" type: A register: a_record - name: Create PTR record local_action: module: rax_dns_record credentials: ~/.raxpub server: "{{ rax_id }}" name: "{{ inventory_hostname }}" region: DFW register: ptr_record ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.rax import (rax_argument_spec, rax_find_loadbalancer, rax_find_server, rax_required_together, rax_to_dict, setup_rax_module, ) def rax_dns_record_ptr(module, data=None, comment=None, loadbalancer=None, name=None, server=None, state='present', ttl=7200): changed = False results = [] dns = pyrax.cloud_dns if not dns: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') if loadbalancer: item = rax_find_loadbalancer(module, pyrax, loadbalancer) elif server: item = rax_find_server(module, pyrax, server) if state == 'present': current = dns.list_ptr_records(item) for record in current: if record.data == data: if record.ttl != ttl or record.name != name: try: dns.update_ptr_record(item, record, name, data, ttl) changed = True except Exception as e: module.fail_json(msg='%s' % e.message) record.ttl = ttl record.name = name results.append(rax_to_dict(record)) break else: results.append(rax_to_dict(record)) break if not results: record = dict(name=name, type='PTR', data=data, ttl=ttl, comment=comment) try: results = dns.add_ptr_records(item, [record]) changed = True except Exception as e: module.fail_json(msg='%s' % e.message) module.exit_json(changed=changed, records=results) elif state == 'absent': current = dns.list_ptr_records(item) for record in current: if record.data == data: results.append(rax_to_dict(record)) break if results: try: dns.delete_ptr_records(item, data) changed = True except Exception as e: module.fail_json(msg='%s' % e.message) module.exit_json(changed=changed, records=results) def rax_dns_record(module, comment=None, data=None, domain=None, name=None, overwrite=True, priority=None, record_type='A', state='present', ttl=7200): """Function for manipulating record types other than PTR""" changed = False dns = pyrax.cloud_dns if not dns: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') if state == 'present': if not priority and record_type in ['MX', 'SRV']: module.fail_json(msg='A "priority" attribute is required for ' 'creating a MX or SRV record') try: domain = dns.find(name=domain) except Exception as e: module.fail_json(msg='%s' % e.message) try: if overwrite: record = domain.find_record(record_type, name=name) else: record = domain.find_record(record_type, name=name, data=data) except pyrax.exceptions.DomainRecordNotUnique as e: module.fail_json(msg='overwrite=true and there are multiple matching records') except pyrax.exceptions.DomainRecordNotFound as e: try: record_data = { 'type': record_type, 'name': name, 'data': data, 'ttl': ttl } if comment: record_data.update(dict(comment=comment)) if priority and record_type.upper() in ['MX', 'SRV']: record_data.update(dict(priority=priority)) record = domain.add_records([record_data])[0] changed = True except Exception as e: module.fail_json(msg='%s' % e.message) update = {} if comment != getattr(record, 'comment', None): update['comment'] = comment if ttl != getattr(record, 'ttl', None): update['ttl'] = ttl if priority != getattr(record, 'priority', None): update['priority'] = priority if data != getattr(record, 'data', None): update['data'] = data if update: try: record.update(**update) changed = True record.get() except Exception as e: module.fail_json(msg='%s' % e.message) elif state == 'absent': try: domain = dns.find(name=domain) except Exception as e: module.fail_json(msg='%s' % e.message) try: record = domain.find_record(record_type, name=name, data=data) except pyrax.exceptions.DomainRecordNotFound as e: record = {} except pyrax.exceptions.DomainRecordNotUnique as e: module.fail_json(msg='%s' % e.message) if record: try: record.delete() changed = True except Exception as e: module.fail_json(msg='%s' % e.message) module.exit_json(changed=changed, record=rax_to_dict(record)) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( comment=dict(), data=dict(required=True), domain=dict(), loadbalancer=dict(), name=dict(required=True), overwrite=dict(type='bool', default=True), priority=dict(type='int'), server=dict(), state=dict(default='present', choices=['present', 'absent']), ttl=dict(type='int', default=3600), type=dict(required=True, choices=['A', 'AAAA', 'CNAME', 'MX', 'NS', 'SRV', 'TXT', 'PTR']) ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together(), mutually_exclusive=[ ['server', 'loadbalancer', 'domain'], ], required_one_of=[ ['server', 'loadbalancer', 'domain'], ], ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') comment = module.params.get('comment') data = module.params.get('data') domain = module.params.get('domain') loadbalancer = module.params.get('loadbalancer') name = module.params.get('name') overwrite = module.params.get('overwrite') priority = module.params.get('priority') server = module.params.get('server') state = module.params.get('state') ttl = module.params.get('ttl') record_type = module.params.get('type') setup_rax_module(module, pyrax, False) if record_type.upper() == 'PTR': if not server and not loadbalancer: module.fail_json(msg='one of the following is required: ' 'server,loadbalancer') rax_dns_record_ptr(module, data=data, comment=comment, loadbalancer=loadbalancer, name=name, server=server, state=state, ttl=ttl) else: rax_dns_record(module, comment=comment, data=data, domain=domain, name=name, overwrite=overwrite, priority=priority, record_type=record_type, state=state, ttl=ttl) if __name__ == '__main__': main()
andreparrish/python-for-android
refs/heads/master
python-build/python-libs/gdata/tests/gdata_tests/youtube/service_test.py
89
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jhartmann@gmail.com (Jochen Hartmann)' import getpass import time import StringIO import random import unittest import atom import gdata.youtube import gdata.youtube.service YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' class YouTubeServiceTest(unittest.TestCase): def setUp(self): self.client = gdata.youtube.service.YouTubeService() self.client.email = username self.client.password = password self.client.source = YOUTUBE_TEST_CLIENT_ID self.client.developer_key = developer_key self.client.client_id = YOUTUBE_TEST_CLIENT_ID self.client.ProgrammaticLogin() def testRetrieveVideoFeed(self): feed = self.client.GetYouTubeVideoFeed( 'http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured'); self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) for entry in feed.entry: self.assert_(entry.title.text != '') def testRetrieveTopRatedVideoFeed(self): feed = self.client.GetTopRatedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostViewedVideoFeed(self): feed = self.client.GetMostViewedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveRecentlyFeaturedVideoFeed(self): feed = self.client.GetRecentlyFeaturedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveWatchOnMobileVideoFeed(self): feed = self.client.GetWatchOnMobileVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveTopFavoritesVideoFeed(self): feed = self.client.GetTopFavoritesVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostRecentVideoFeed(self): feed = self.client.GetMostRecentVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostDiscussedVideoFeed(self): feed = self.client.GetMostDiscussedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostLinkedVideoFeed(self): feed = self.client.GetMostLinkedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostRespondedVideoFeed(self): feed = self.client.GetMostRespondedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveVideoEntryByUri(self): entry = self.client.GetYouTubeVideoEntry( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k') self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry)) self.assert_(entry.title.text != '') def testRetrieveVideoEntryByVideoId(self): entry = self.client.GetYouTubeVideoEntry(video_id='Ncakifd_16k') self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry)) self.assert_(entry.title.text != '') def testRetrieveUserVideosbyUri(self): feed = self.client.GetYouTubeUserFeed( 'http://gdata.youtube.com/feeds/users/gdpython/uploads') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveUserVideosbyUsername(self): feed = self.client.GetYouTubeUserFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testSearchWithVideoQuery(self): query = gdata.youtube.service.YouTubeVideoQuery() query.vq = 'google' query.max_results = 8 feed = self.client.YouTubeQuery(query) self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assertEquals(len(feed.entry), 8) def testDirectVideoUploadStatusUpdateAndDeletion(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos'), player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) # Set Geo location to 37,-122 lat, long where = gdata.geo.Where() where.set_location((37.0,-122.0)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group, geo=where) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) new_entry = self.client.InsertVideoEntry(video_entry, video_file_location) self.assert_(isinstance(new_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(new_entry.title.text, test_video_title) self.assertEquals(new_entry.media.description.text, test_video_description) self.assert_(new_entry.id.text) # check upload status also upload_status = self.client.CheckUploadStatus(new_entry) self.assert_(upload_status[0] != '') # test updating entry meta-data new_video_description = 'description ' + str(random.randint(1000,5000)) new_entry.media.description.text = new_video_description updated_entry = self.client.UpdateVideoEntry(new_entry) self.assert_(isinstance(updated_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(updated_entry.media.description.text, new_video_description) # sleep for 10 seconds time.sleep(10) # test to delete the entry value = self.client.DeleteVideoEntry(updated_entry) if not value: # sleep more and try again time.sleep(20) # test to delete the entry value = self.client.DeleteVideoEntry(updated_entry) self.assert_(value == True) def testDirectVideoUploadWithDeveloperTags(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) test_developer_tag_01 = 'tag' + str(random.randint(1000,5000)) test_developer_tag_02 = 'tag' + str(random.randint(1000,5000)) test_developer_tag_03 = 'tag' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = [gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos')], player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) original_developer_tags = [test_developer_tag_01, test_developer_tag_02, test_developer_tag_03] dev_tags = video_entry.AddDeveloperTags(original_developer_tags) for dev_tag in dev_tags: self.assert_(dev_tag.text in original_developer_tags) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) new_entry = self.client.InsertVideoEntry(video_entry, video_file_location) self.assert_(isinstance(new_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(new_entry.title.text, test_video_title) self.assertEquals(new_entry.media.description.text, test_video_description) self.assert_(new_entry.id.text) developer_tags_from_new_entry = new_entry.GetDeveloperTags() for dev_tag in developer_tags_from_new_entry: self.assert_(dev_tag.text in original_developer_tags) self.assertEquals(len(developer_tags_from_new_entry), len(original_developer_tags)) # sleep for 10 seconds time.sleep(10) # test to delete the entry value = self.client.DeleteVideoEntry(new_entry) if not value: # sleep more and try again time.sleep(20) # test to delete the entry value = self.client.DeleteVideoEntry(new_entry) self.assert_(value == True) def testBrowserBasedVideoUpload(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos'), player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) response = self.client.GetFormUploadToken(video_entry) self.assert_(response[0].startswith( 'http://uploads.gdata.youtube.com/action/FormDataUpload/')) self.assert_(len(response[0]) > 55) self.assert_(len(response[1]) > 100) def testRetrieveRelatedVideoFeedByUri(self): feed = self.client.GetYouTubeRelatedVideoFeed( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k/related') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveRelatedVideoFeedById(self): feed = self.client.GetYouTubeRelatedVideoFeed(video_id = 'Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveResponseVideoFeedByUri(self): feed = self.client.GetYouTubeVideoResponseFeed( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k/responses') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoResponseFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveResponseVideoFeedById(self): feed = self.client.GetYouTubeVideoResponseFeed(video_id='Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoResponseFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveVideoCommentFeedByUri(self): feed = self.client.GetYouTubeVideoCommentFeed( 'http://gdata.youtube.com/feeds/api/videos/Ncakifd_16k/comments') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoCommentFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveVideoCommentFeedByVideoId(self): feed = self.client.GetYouTubeVideoCommentFeed(video_id='Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoCommentFeed)) self.assert_(len(feed.entry) > 0) def testAddComment(self): video_id = '9g6buYJTt_g' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id) random_comment_text = 'test_comment_' + str(random.randint(1000,50000)) self.client.AddComment(comment_text=random_comment_text, video_entry=video_entry) comment_feed = self.client.GetYouTubeVideoCommentFeed(video_id=video_id) comment_found = False for item in comment_feed.entry: if (item.content.text == random_comment_text): comment_found = True self.assertEquals(comment_found, True) def testAddRating(self): video_id_to_rate = 'Ncakifd_16k' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id_to_rate) response = self.client.AddRating(3, video_entry) self.assert_(isinstance(response, gdata.GDataEntry)) def testRetrievePlaylistFeedByUri(self): feed = self.client.GetYouTubePlaylistFeed( 'http://gdata.youtube.com/feeds/users/gdpython/playlists') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistFeed)) self.assert_(len(feed.entry) > 0) def testRetrievePlaylistListFeedByUsername(self): feed = self.client.GetYouTubePlaylistFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistFeed)) self.assert_(len(feed.entry) > 0) def testRetrievePlaylistVideoFeed(self): feed = self.client.GetYouTubePlaylistVideoFeed( 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistVideoFeed)) self.assert_(len(feed.entry) > 0) self.assert_(isinstance(feed.entry[0], gdata.youtube.YouTubePlaylistVideoEntry)) def testAddUpdateAndDeletePlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) new_playlist_title = 'my updated playlist ' + str(random.randint(1000,4000)) new_playlist_description = 'my updated playlist ' playlist_entry_id = response.id.text.split('/')[-1] updated_playlist = self.client.UpdatePlaylist(playlist_entry_id, new_playlist_title, new_playlist_description) playlist_feed = self.client.GetYouTubePlaylistFeed() update_successful = False for playlist_entry in playlist_feed.entry: if playlist_entry.title.text == new_playlist_title: update_successful = True break self.assertEquals(update_successful, True) # wait time.sleep(10) # delete it playlist_uri = updated_playlist.id.text response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testAddUpdateAndDeletePrivatePlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description, playlist_private=True) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) new_playlist_title = 'my updated playlist ' + str(random.randint(1000,4000)) new_playlist_description = 'my updated playlist ' playlist_entry_id = response.id.text.split('/')[-1] updated_playlist = self.client.UpdatePlaylist(playlist_entry_id, new_playlist_title, new_playlist_description, playlist_private=True) playlist_feed = self.client.GetYouTubePlaylistFeed() update_successful = False playlist_still_private = False for playlist_entry in playlist_feed.entry: if playlist_entry.title.text == new_playlist_title: update_successful = True if playlist_entry.private is not None: playlist_still_private = True self.assertEquals(update_successful, True) self.assertEquals(playlist_still_private, True) # wait time.sleep(10) # delete it playlist_uri = updated_playlist.id.text response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testAddEditAndDeleteVideoFromPlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) custom_video_title = 'my test video on my test playlist' custom_video_description = 'this is a test video on my test playlist' video_id = 'Ncakifd_16k' playlist_uri = response.feed_link[0].href time.sleep(10) response = self.client.AddPlaylistVideoEntryToPlaylist( playlist_uri, video_id, custom_video_title, custom_video_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistVideoEntry)) playlist_entry_id = response.id.text.split('/')[-1] playlist_uri = response.id.text.split(playlist_entry_id)[0][:-1] new_video_title = 'video number ' + str(random.randint(1000,3000)) new_video_description = 'test video' time.sleep(10) response = self.client.UpdatePlaylistVideoEntryMetaData( playlist_uri, playlist_entry_id, new_video_title, new_video_description, 1) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistVideoEntry)) time.sleep(10) playlist_entry_id = response.id.text.split('/')[-1] # remove video from playlist response = self.client.DeletePlaylistVideoEntry(playlist_uri, playlist_entry_id) self.assertEquals(response, True) time.sleep(10) # delete the playlist response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testRetrieveSubscriptionFeedByUri(self): feed = self.client.GetYouTubeSubscriptionFeed( 'http://gdata.youtube.com/feeds/users/gdpython/subscriptions') self.assert_(isinstance(feed, gdata.youtube.YouTubeSubscriptionFeed)) self.assert_(len(feed.entry) == 3) subscription_to_channel_found = False subscription_to_favorites_found = False subscription_to_query_found = False all_types_found = False for entry in feed.entry: self.assert_(isinstance(entry, gdata.youtube.YouTubeSubscriptionEntry)) subscription_type = entry.GetSubscriptionType() if subscription_type == 'channel': subscription_to_channel_found = True elif subscription_type == 'favorites': subscription_to_favorites_found = True elif subscription_type == 'query': subscription_to_query_found = True if (subscription_to_channel_found and subscription_to_favorites_found and subscription_to_query_found): all_types_found = True self.assertEquals(all_types_found, True) def testRetrieveSubscriptionFeedByUsername(self): feed = self.client.GetYouTubeSubscriptionFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeSubscriptionFeed)) self.assert_(len(feed.entry) == 3) subscription_to_channel_found = False subscription_to_favorites_found = False subscription_to_query_found = False all_types_found = False for entry in feed.entry: self.assert_(isinstance(entry, gdata.youtube.YouTubeSubscriptionEntry)) subscription_type = entry.GetSubscriptionType() if subscription_type == 'channel': subscription_to_channel_found = True elif subscription_type == 'favorites': subscription_to_favorites_found = True elif subscription_type == 'query': subscription_to_query_found = True if (subscription_to_channel_found and subscription_to_favorites_found and subscription_to_query_found): all_types_found = True self.assertEquals(all_types_found, True) def testRetrieveUserProfileByUri(self): user = self.client.GetYouTubeUserEntry( 'http://gdata.youtube.com/feeds/users/gdpython') self.assert_(isinstance(user, gdata.youtube.YouTubeUserEntry)) self.assertEquals(user.location.text, 'US') def testRetrieveUserProfileByUsername(self): user = self.client.GetYouTubeUserEntry(username='gdpython') self.assert_(isinstance(user, gdata.youtube.YouTubeUserEntry)) self.assertEquals(user.location.text, 'US') def testRetrieveUserFavoritesFeed(self): feed = self.client.GetUserFavoritesFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveDefaultUserFavoritesFeed(self): feed = self.client.GetUserFavoritesFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testAddAndDeleteVideoFromFavorites(self): video_id = 'Ncakifd_16k' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id) response = self.client.AddVideoEntryToFavorites(video_entry) self.assert_(isinstance(response, gdata.GDataEntry)) time.sleep(10) response = self.client.DeleteVideoEntryFromFavorites(video_id) self.assertEquals(response, True) def testRetrieveContactFeedByUri(self): feed = self.client.GetYouTubeContactFeed( 'http://gdata.youtube.com/feeds/users/gdpython/contacts') self.assert_(isinstance(feed, gdata.youtube.YouTubeContactFeed)) self.assertEquals(len(feed.entry), 1) def testRetrieveContactFeedByUsername(self): feed = self.client.GetYouTubeContactFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeContactFeed)) self.assertEquals(len(feed.entry), 1) if __name__ == '__main__': print ('NOTE: Please run these tests only with a test account. ' 'The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() developer_key = raw_input('Please enter your developer key: ') video_file_location = raw_input( 'Please enter the absolute path to a video file: ') unittest.main()
klinger/volunteer_planner
refs/heads/develop
organizations/migrations/0006_auto_20151022_1445.py
6
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('organizations', '0005_auto_20151021_1153'), ] operations = [ migrations.AlterField( model_name='facilitymembership', name='role', field=models.PositiveIntegerField(default=2, verbose_name='role', choices=[(0, 'admin'), (1, 'manager'), (2, 'member')]), ), migrations.AlterField( model_name='organizationmembership', name='role', field=models.PositiveIntegerField(default=2, verbose_name='role', choices=[(0, 'admin'), (1, 'manager'), (2, 'member')]), ), ]