repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
deepesch/scikit-learn
sklearn/datasets/lfw.py
141
19372
"""Loader for the Labeled Faces in the Wild (LFW) dataset This dataset is a collection of JPEG pictures of famous people collected over the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. The typical task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. An alternative task, Face Recognition or Face Identification is: given the picture of the face of an unknown person, identify the name of the person by referring to a gallery of previously seen pictures of identified persons. Both Face Verification and Face Recognition are tasks that are typically performed on the output of a model trained to perform Face Detection. The most popular model for Face Detection is called Viola-Johns and is implemented in the OpenCV library. The LFW faces were extracted by this face detector from various online websites. """ # Copyright (c) 2011 Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause from os import listdir, makedirs, remove from os.path import join, exists, isdir from sklearn.utils import deprecated import logging import numpy as np try: import urllib.request as urllib # for backwards compatibility except ImportError: import urllib from .base import get_data_home, Bunch from ..externals.joblib import Memory from ..externals.six import b logger = logging.getLogger(__name__) BASE_URL = "http://vis-www.cs.umass.edu/lfw/" ARCHIVE_NAME = "lfw.tgz" FUNNELED_ARCHIVE_NAME = "lfw-funneled.tgz" TARGET_FILENAMES = [ 'pairsDevTrain.txt', 'pairsDevTest.txt', 'pairs.txt', ] def scale_face(face): """Scale back to 0-1 range in case of normalization for plotting""" scaled = face - face.min() scaled /= scaled.max() return scaled # # Common private utilities for data fetching from the original LFW website # local disk caching, and image decoding. # def check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True): """Helper function to download any missing LFW data""" data_home = get_data_home(data_home=data_home) lfw_home = join(data_home, "lfw_home") if funneled: archive_path = join(lfw_home, FUNNELED_ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw_funneled") archive_url = BASE_URL + FUNNELED_ARCHIVE_NAME else: archive_path = join(lfw_home, ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw") archive_url = BASE_URL + ARCHIVE_NAME if not exists(lfw_home): makedirs(lfw_home) for target_filename in TARGET_FILENAMES: target_filepath = join(lfw_home, target_filename) if not exists(target_filepath): if download_if_missing: url = BASE_URL + target_filename logger.warning("Downloading LFW metadata: %s", url) urllib.urlretrieve(url, target_filepath) else: raise IOError("%s is missing" % target_filepath) if not exists(data_folder_path): if not exists(archive_path): if download_if_missing: logger.warning("Downloading LFW data (~200MB): %s", archive_url) urllib.urlretrieve(archive_url, archive_path) else: raise IOError("%s is missing" % target_filepath) import tarfile logger.info("Decompressing the data archive to %s", data_folder_path) tarfile.open(archive_path, "r:gz").extractall(path=lfw_home) remove(archive_path) return lfw_home, data_folder_path def _load_imgs(file_paths, slice_, color, resize): """Internally used to load images""" # Try to import imread and imresize from PIL. We do this here to prevent # the whole sklearn.datasets module from depending on PIL. try: try: from scipy.misc import imread except ImportError: from scipy.misc.pilutil import imread from scipy.misc import imresize except ImportError: raise ImportError("The Python Imaging Library (PIL)" " is required to load data from jpeg files") # compute the portion of the images to load to respect the slice_ parameter # given by the caller default_slice = (slice(0, 250), slice(0, 250)) if slice_ is None: slice_ = default_slice else: slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice)) h_slice, w_slice = slice_ h = (h_slice.stop - h_slice.start) // (h_slice.step or 1) w = (w_slice.stop - w_slice.start) // (w_slice.step or 1) if resize is not None: resize = float(resize) h = int(resize * h) w = int(resize * w) # allocate some contiguous memory to host the decoded image slices n_faces = len(file_paths) if not color: faces = np.zeros((n_faces, h, w), dtype=np.float32) else: faces = np.zeros((n_faces, h, w, 3), dtype=np.float32) # iterate over the collected file path to load the jpeg files as numpy # arrays for i, file_path in enumerate(file_paths): if i % 1000 == 0: logger.info("Loading face #%05d / %05d", i + 1, n_faces) # Checks if jpeg reading worked. Refer to issue #3594 for more # details. img = imread(file_path) if img.ndim is 0: raise RuntimeError("Failed to read the image file %s, " "Please make sure that libjpeg is installed" % file_path) face = np.asarray(img[slice_], dtype=np.float32) face /= 255.0 # scale uint8 coded colors to the [0.0, 1.0] floats if resize is not None: face = imresize(face, resize) if not color: # average the color channels to compute a gray levels # representaion face = face.mean(axis=2) faces[i, ...] = face return faces # # Task #1: Face Identification on picture with names # def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0): """Perform the actual data loading for the lfw people dataset This operation is meant to be cached by a joblib wrapper. """ # scan the data folder content to retain people with more that # `min_faces_per_person` face pictures person_names, file_paths = [], [] for person_name in sorted(listdir(data_folder_path)): folder_path = join(data_folder_path, person_name) if not isdir(folder_path): continue paths = [join(folder_path, f) for f in listdir(folder_path)] n_pictures = len(paths) if n_pictures >= min_faces_per_person: person_name = person_name.replace('_', ' ') person_names.extend([person_name] * n_pictures) file_paths.extend(paths) n_faces = len(file_paths) if n_faces == 0: raise ValueError("min_faces_per_person=%d is too restrictive" % min_faces_per_person) target_names = np.unique(person_names) target = np.searchsorted(target_names, person_names) faces = _load_imgs(file_paths, slice_, color, resize) # shuffle the faces with a deterministic RNG scheme to avoid having # all faces of the same person in a row, as it would break some # cross validation and learning algorithms such as SGD and online # k-means that make an IID assumption indices = np.arange(n_faces) np.random.RandomState(42).shuffle(indices) faces, target = faces[indices], target[indices] return faces, target, target_names def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, min_faces_per_person=0, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) people dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Recognition (or Identification): given the picture of a face, find the name of the person given a training set (gallery). The original images are 250 x 250 pixels, but the default slice and resize arguments reduce them to 62 x 74. Parameters ---------- data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled : boolean, optional, default: True Download and use the funneled variant of the dataset. resize : float, optional, default 0.5 Ratio used to resize the each face picture. min_faces_per_person : int, optional, default None The extracted dataset will only retain pictures of people that have at least `min_faces_per_person` different pictures. color : boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_ : optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns ------- dataset : dict-like object with the following attributes: dataset.data : numpy array of shape (13233, 2914) Each row corresponds to a ravelled face image of original size 62 x 47 pixels. Changing the ``slice_`` or resize parameters will change the shape of the output. dataset.images : numpy array of shape (13233, 62, 47) Each row is a face image corresponding to one of the 5749 people in the dataset. Changing the ``slice_`` or resize parameters will change the shape of the output. dataset.target : numpy array of shape (13233,) Labels associated to each face image. Those labels range from 0-5748 and correspond to the person IDs. dataset.DESCR : string Description of the Labeled Faces in the Wild (LFW) dataset. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading LFW people faces from %s', lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_people) # load and memoize the pairs as np arrays faces, target, target_names = load_func( data_folder_path, resize=resize, min_faces_per_person=min_faces_per_person, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=faces.reshape(len(faces), -1), images=faces, target=target, target_names=target_names, DESCR="LFW faces dataset") # # Task #2: Face Verification on pairs of face pictures # def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, color=False, resize=None): """Perform the actual data loading for the LFW pairs dataset This operation is meant to be cached by a joblib wrapper. """ # parse the index file to find the number of pairs to be able to allocate # the right amount of memory before starting to decode the jpeg files with open(index_file_path, 'rb') as index_file: split_lines = [ln.strip().split(b('\t')) for ln in index_file] pair_specs = [sl for sl in split_lines if len(sl) > 2] n_pairs = len(pair_specs) # interating over the metadata lines for each pair to find the filename to # decode and load in memory target = np.zeros(n_pairs, dtype=np.int) file_paths = list() for i, components in enumerate(pair_specs): if len(components) == 3: target[i] = 1 pair = ( (components[0], int(components[1]) - 1), (components[0], int(components[2]) - 1), ) elif len(components) == 4: target[i] = 0 pair = ( (components[0], int(components[1]) - 1), (components[2], int(components[3]) - 1), ) else: raise ValueError("invalid line %d: %r" % (i + 1, components)) for j, (name, idx) in enumerate(pair): try: person_folder = join(data_folder_path, name) except TypeError: person_folder = join(data_folder_path, str(name, 'UTF-8')) filenames = list(sorted(listdir(person_folder))) file_path = join(person_folder, filenames[idx]) file_paths.append(file_path) pairs = _load_imgs(file_paths, slice_, color, resize) shape = list(pairs.shape) n_faces = shape.pop(0) shape.insert(0, 2) shape.insert(0, n_faces // 2) pairs.shape = shape return pairs, target, np.array(['Different persons', 'Same person']) @deprecated("Function 'load_lfw_people' has been deprecated in 0.17 and will be " "removed in 0.19." "Use fetch_lfw_people(download_if_missing=False) instead.") def load_lfw_people(download_if_missing=False, **kwargs): """Alias for fetch_lfw_people(download_if_missing=False) Check fetch_lfw_people.__doc__ for the documentation and parameter list. """ return fetch_lfw_people(download_if_missing=download_if_missing, **kwargs) def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) pairs dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. In the official `README.txt`_ this task is described as the "Restricted" task. As I am not sure as to implement the "Unrestricted" variant correctly, I left it as unsupported for now. .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt The original images are 250 x 250 pixels, but the default slice and resize arguments reduce them to 62 x 74. Read more in the :ref:`User Guide <labeled_faces_in_the_wild>`. Parameters ---------- subset : optional, default: 'train' Select the dataset to load: 'train' for the development training set, 'test' for the development test set, and '10_folds' for the official evaluation set that is meant to be used with a 10-folds cross validation. data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled : boolean, optional, default: True Download and use the funneled variant of the dataset. resize : float, optional, default 0.5 Ratio used to resize the each face picture. color : boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_ : optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns ------- The data is returned as a Bunch object with the following attributes: data : numpy array of shape (2200, 5828) Each row corresponds to 2 ravel'd face images of original size 62 x 47 pixels. Changing the ``slice_`` or resize parameters will change the shape of the output. pairs : numpy array of shape (2200, 2, 62, 47) Each row has 2 face images corresponding to same or different person from the dataset containing 5749 people. Changing the ``slice_`` or resize parameters will change the shape of the output. target : numpy array of shape (13233,) Labels associated to each pair of images. The two label values being different persons or the same person. DESCR : string Description of the Labeled Faces in the Wild (LFW) dataset. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading %s LFW pairs from %s', subset, lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_pairs) # select the right metadata file according to the requested subset label_filenames = { 'train': 'pairsDevTrain.txt', 'test': 'pairsDevTest.txt', '10_folds': 'pairs.txt', } if subset not in label_filenames: raise ValueError("subset='%s' is invalid: should be one of %r" % ( subset, list(sorted(label_filenames.keys())))) index_file_path = join(lfw_home, label_filenames[subset]) # load and memoize the pairs as np arrays pairs, target, target_names = load_func( index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=pairs.reshape(len(pairs), -1), pairs=pairs, target=target, target_names=target_names, DESCR="'%s' segment of the LFW pairs dataset" % subset) @deprecated("Function 'load_lfw_pairs' has been deprecated in 0.17 and will be " "removed in 0.19." "Use fetch_lfw_pairs(download_if_missing=False) instead.") def load_lfw_pairs(download_if_missing=False, **kwargs): """Alias for fetch_lfw_pairs(download_if_missing=False) Check fetch_lfw_pairs.__doc__ for the documentation and parameter list. """ return fetch_lfw_pairs(download_if_missing=download_if_missing, **kwargs)
bsd-3-clause
jfunction/capetown_loadshedding_map
convert_json.py
1
1792
#!/usr/bin/env python # -*- coding: utf-8 -*- # # convert_json.py # # Copyright 2014 Jared <jarednorman@hotmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import json import collections def main(): with open('capetown_tables_json_1.json','rb') as f_in: d = json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(f_in.read()) stages = sorted(d.keys()) for stage in stages: time_dict = d[stage] times = sorted(time_dict.keys()) for time in times: days_dict = time_dict[time] start_time = int(time.split(':00 to ')[0]) #end_time = start_time + 2.5 days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] for i, day in enumerate(days): shedding_zones = str(days_dict[day]) if not shedding_zones: shedding_zones = [] else: shedding_zones = shedding_zones.split(', ') days_dict[day] = shedding_zones #time_dict[start_time] = time_dict.pop(time) with open('capetown_tables_json_2.json','wb') as f_out: f_out.write(json.dumps(d,indent=2)) return 0 if __name__ == '__main__': main()
gpl-2.0
kirca/odoo
addons/auth_oauth/controllers/main.py
30
7624
import functools import logging import simplejson import urlparse import werkzeug.utils from werkzeug.exceptions import BadRequest import openerp from openerp import SUPERUSER_ID from openerp import http from openerp.http import request from openerp.addons.web.controllers.main import db_monodb, ensure_db, set_cookie_and_redirect, login_and_redirect from openerp.modules.registry import RegistryManager from openerp.tools.translate import _ _logger = logging.getLogger(__name__) #---------------------------------------------------------- # helpers #---------------------------------------------------------- def fragment_to_query_string(func): @functools.wraps(func) def wrapper(self, *a, **kw): if not kw: return """<html><head><script> var l = window.location; var q = l.hash.substring(1); var r = l.pathname + l.search; if(q.length !== 0) { var s = l.search ? (l.search === '?' ? '' : '&') : '?'; r = l.pathname + l.search + s + q; } if (r == l.pathname) { r = '/'; } window.location = r; </script></head><body></body></html>""" return func(self, *a, **kw) return wrapper #---------------------------------------------------------- # Controller #---------------------------------------------------------- class OAuthLogin(openerp.addons.web.controllers.main.Home): def list_providers(self): try: provider_obj = request.registry.get('auth.oauth.provider') providers = provider_obj.search_read(request.cr, SUPERUSER_ID, [('enabled', '=', True)]) except Exception: providers = [] for provider in providers: return_url = request.httprequest.url_root + 'auth_oauth/signin' state = self.get_state(provider) params = dict( debug=request.debug, response_type='token', client_id=provider['client_id'], redirect_uri=return_url, scope=provider['scope'], state=simplejson.dumps(state), ) provider['auth_link'] = provider['auth_endpoint'] + '?' + werkzeug.url_encode(params) return providers def get_state(self, provider): state = dict( d=request.session.db, p=provider['id'], r=request.httprequest.full_path ) token = request.params.get('token') if token: state['t'] = token return state @http.route() def web_login(self, *args, **kw): ensure_db() if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'): # Redirect if already logged in and redirect param is present return http.redirect_with_hash(request.params.get('redirect')) providers = self.list_providers() response = super(OAuthLogin, self).web_login(*args, **kw) if response.is_qweb: error = request.params.get('oauth_error') if error == '1': error = _("Sign up is not allowed on this database.") elif error == '2': error = _("Access Denied") elif error == '3': error = _("You do not have access to this database or your invitation has expired. Please ask for an invitation and be sure to follow the link in your invitation email.") else: error = None response.qcontext['providers'] = providers if error: response.qcontext['error'] = error return response @http.route() def web_auth_signup(self, *args, **kw): providers = self.list_providers() if len(providers) == 1: werkzeug.exceptions.abort(werkzeug.utils.redirect(providers[0]['auth_link'], 303)) response = super(OAuthLogin, self).web_auth_signup(*args, **kw) response.qcontext.update(providers=providers) return response @http.route() def web_auth_reset_password(self, *args, **kw): providers = self.list_providers() if len(providers) == 1: werkzeug.exceptions.abort(werkzeug.utils.redirect(providers[0]['auth_link'], 303)) response = super(OAuthLogin, self).web_auth_reset_password(*args, **kw) response.qcontext.update(providers=providers) return response class OAuthController(http.Controller): @http.route('/auth_oauth/signin', type='http', auth='none') @fragment_to_query_string def signin(self, **kw): state = simplejson.loads(kw['state']) dbname = state['d'] provider = state['p'] context = state.get('c', {}) registry = RegistryManager.get(dbname) with registry.cursor() as cr: try: u = registry.get('res.users') credentials = u.auth_oauth(cr, SUPERUSER_ID, provider, kw, context=context) cr.commit() action = state.get('a') menu = state.get('m') redirect = state.get('r') url = '/web' if redirect and not redirect.startswith('/auth_oauth/signin') and \ (not redirect.startswith('/web/login') or 'redirect' in urlparse.urlsplit(redirect).query): url = redirect elif action: url = '/web#action=%s' % action elif menu: url = '/web#menu_id=%s' % menu return login_and_redirect(*credentials, redirect_url=url) except AttributeError: # auth_signup is not installed _logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,)) url = "/web/login?oauth_error=1" except openerp.exceptions.AccessDenied: # oauth credentials not valid, user could be on a temporary session _logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies') url = "/web/login?oauth_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect except Exception, e: # signup error _logger.exception("OAuth2: %s" % str(e)) url = "/web/login?oauth_error=2" return set_cookie_and_redirect(url) @http.route('/auth_oauth/oea', type='http', auth='none') def oea(self, **kw): """login user via OpenERP Account provider""" dbname = kw.pop('db', None) if not dbname: dbname = db_monodb() if not dbname: return BadRequest() registry = RegistryManager.get(dbname) with registry.cursor() as cr: IMD = registry['ir.model.data'] try: model, provider_id = IMD.get_object_reference(cr, SUPERUSER_ID, 'auth_oauth', 'provider_openerp') except ValueError: return set_cookie_and_redirect('/web?db=%s' % dbname) assert model == 'auth.oauth.provider' state = { 'd': dbname, 'p': provider_id, 'c': {'no_user_creation': True}, } kw['state'] = simplejson.dumps(state) return self.signin(**kw) # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
felixma/nova
nova/db/sqlalchemy/migrate_repo/versions/247_nullable_mismatch.py
48
1692
# Copyright 2014 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. from sqlalchemy import MetaData, Table def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) quota_usages = Table('quota_usages', meta, autoload=True) quota_usages.c.resource.alter(nullable=False) pci_devices = Table('pci_devices', meta, autoload=True) # NOTE(mriedem): The deleted column is in a UniqueConstraint so making # it nullable breaks DB2 with an SQL0542N error, so skip for DB2. There is # a FKey in 246 so we're kind of stuck with DB2 since we can't create the # FKey without the unique constraint and we can't have a unique constraint # on a nullable column. # TODO(mriedem): Revisit this once the deleted column (inherited from the # SoftDeleteMixin in oslo.db) is non-null on all tables, which is going # to be a non-trivial effort. if migrate_engine.name != 'ibm_db_sa': pci_devices.c.deleted.alter(nullable=True) pci_devices.c.product_id.alter(nullable=False) pci_devices.c.vendor_id.alter(nullable=False) pci_devices.c.dev_type.alter(nullable=False)
apache-2.0
enthought/traitsgui
enthought/pyface/workbench/i_view.py
1
4139
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ """ The interface for workbench views. """ # Standard library imports. import logging # Enthought library imports. from enthought.pyface.api import ImageResource from enthought.traits.api import Bool, Enum, Float, Instance, List, Str, \ implements from enthought.util.camel_case import camel_case_to_words # Local imports. from i_perspective_item import IPerspectiveItem from i_workbench_part import IWorkbenchPart, MWorkbenchPart from perspective_item import PerspectiveItem # Logging. logger = logging.getLogger(__name__) class IView(IWorkbenchPart, IPerspectiveItem): """ The interface for workbench views. """ # Is the view busy? (i.e., should the busy cursor (often an hourglass) be # displayed?). busy = Bool(False) # The category that the view belongs to (this can used to group views when # they are displayed to the user). category = Str('General') # An image used to represent the view to the user (shown in the view tab # and in the view chooser etc). image = Instance(ImageResource) # Whether the view is visible or not. visible = Bool(False) ########################################################################### # 'IView' interface. ########################################################################### def activate(self): """ Activate the view. """ def hide(self): """ Hide the view. """ def show(self): """ Show the view. """ class MView(MWorkbenchPart, PerspectiveItem): """ Mixin containing common code for toolkit-specific implementations. """ implements(IView) #### 'IView' interface #################################################### # Is the view busy? (i.e., should the busy cursor (often an hourglass) be # displayed?). busy = Bool(False) # The category that the view belongs to (this can be used to group views # when they are displayed to the user). category = Str('General') # An image used to represent the view to the user (shown in the view tab # and in the view chooser etc). image = Instance(ImageResource) # Whether the view is visible or not. visible = Bool(False) ########################################################################### # 'IWorkbenchPart' interface. ########################################################################### def _id_default(self): """ Trait initializer. """ id = '%s.%s' % (type(self).__module__, type(self).__name__) logger.warn('view %s has no Id - using <%s>' % (self, id)) # If no Id is specified then use the name. return id def _name_default(self): """ Trait initializer. """ name = camel_case_to_words(type(self).__name__) logger.warn('view %s has no name - using <%s>' % (self, name)) return name ########################################################################### # 'IView' interface. ########################################################################### def activate(self): """ Activate the view. """ self.window.activate_view(self) return def hide(self): """ Hide the view. """ self.window.hide_view(self) return def show(self): """ Show the view. """ self.window.show_view(self) return #### EOF ######################################################################
bsd-3-clause
gyllstar/appleseed
pox/openflow/libopenflow_01.py
1
126928
# Copyright 2011 James McCauley # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. # This file was originally based on pyopenflow.py from NOX, which was # autogenerated from openflow.h via a program by KK Yap. It has been # substantially altered since then. import struct import operator import collections import sys from pox.lib.packet.packet_base import packet_base from pox.lib.packet.ethernet import ethernet from pox.lib.packet.vlan import vlan from pox.lib.packet.ipv4 import ipv4 from pox.lib.packet.udp import udp from pox.lib.packet.tcp import tcp from pox.lib.packet.icmp import icmp from pox.lib.packet.arp import arp from pox.lib.addresses import * from pox.lib.util import assert_type from pox.lib.util import initHelper from pox.lib.util import hexdump _PAD = b'\x00' _PAD2 = _PAD*2 _PAD3 = _PAD*3 _PAD4 = _PAD*4 _PAD6 = _PAD*6 EMPTY_ETH = EthAddr(None) MAX_XID = 0x7fFFffFF _nextXID = 1 #USE_MPLS_MATCH = False def generateXID (): global _nextXID r = _nextXID _nextXID += 1 _nextXID = (_nextXID + 1) % (MAX_XID + 1) return r def xid_generator(start=1): """ generate a xid sequence. Wraps at 2**31-1 """ n = start % (MAX_XID + 1) while True: yield n n = ( n + 1 ) % (MAX_XID + 1) def _format_body (body, prefix): if hasattr(body, 'show'): #TODO: Check this (spacing may well be wrong) return body.show(prefix + ' ') else: return prefix + hexdump(body).replace("\n", "\n" + prefix) TABLE_ALL = 0xff TABLE_EMERGENCY = 0xfe # Structure definitions #1. Openflow Header class ofp_header (object): def __init__ (self, **kw): self.version = OFP_VERSION self.header_type = 0 self.length = 8 self.xid = None initHelper(self, kw) def _assert (self): if self.header_type not in ofp_type_map: return (False, "type is not a known message type") return (True, None) def pack (self, assertstruct=True): if self.xid is None: self.xid = generateXID() if(assertstruct): if(not ofp_header._assert(self)[0]): raise RuntimeError("assertstruct failed") packed = "" packed += struct.pack("!BBHL", self.version, self.header_type, self.length, self.xid) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.version, self.header_type, self.length, self.xid) = struct.unpack_from("!BBHL", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.version != other.version: return False if self.header_type != other.header_type: return False if self.length != other.length: return False if self.xid != other.xid: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'version: ' + str(self.version) + '\n' outstr += prefix + 'type: ' + str(self.header_type)# + '\n' outstr += " (" + ofp_type_map.get(self.header_type, "Unknown") + ")\n" outstr += prefix + 'length: ' + str(self.length) + '\n' outstr += prefix + 'xid: ' + str(self.xid) + '\n' return outstr def __str__ (self): return self.__class__.__name__ + "\n " + self.show(' ').strip() #2. Common Structures ##2.1 Port Structures class ofp_phy_port (object): def __init__ (self, **kw): self.port_no = 0 self.hw_addr = EMPTY_ETH self.name = "" self.config = 0 self.state = 0 self.curr = 0 self.advertised = 0 self.supported = 0 self.peer = 0 initHelper(self, kw) def _assert (self): if not isinstance(self.hw_addr, bytes) and not isinstance(self.hw_addr, EthAddr): return (False, "hw_addr is not bytes or EthAddr") if(len(self.hw_addr) != 6): return (False, "hw_addr is not of size 6") if(not isinstance(self.name, str)): return (False, "name is not string") if(len(self.name) > 16): return (False, "name is not of size 16") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!H", self.port_no) packed += self.hw_addr if isinstance(self.hw_addr, bytes) else self.hw_addr.toRaw() packed += self.name.ljust(16,'\0') packed += struct.pack("!LLLLLL", self.config, self.state, self.curr, self.advertised, self.supported, self.peer) return packed def unpack (self, binaryString): if (len(binaryString) < 48): return binaryString (self.port_no,) = struct.unpack_from("!H", binaryString, 0) self.hw_addr = EthAddr(binaryString[2:8]) self.name = binaryString[8:24].replace("\0","") (self.config, self.state, self.curr, self.advertised, self.supported, self.peer) = struct.unpack_from("!LLLLLL", binaryString, 24) return binaryString[48:] def __len__ (self): return 48 def __eq__ (self, other): if type(self) != type(other): return False if self.port_no != other.port_no: return False if self.hw_addr != other.hw_addr: return False if self.name != other.name: return False if self.config != other.config: return False if self.state != other.state: return False if self.curr != other.curr: return False if self.advertised != other.advertised: return False if self.supported != other.supported: return False if self.peer != other.peer: return False return True def __ne__ (self, other): return not self.__eq__(other) def __hash__(self, *args, **kwargs): return self.port_no.__hash__() + self.hw_addr.toInt().__hash__() + \ self.name.__hash__() + self.config.__hash__() + \ self.state.__hash__() + self.curr.__hash__() + \ self.advertised.__hash__() + self.supported.__hash__() + \ self.peer.__hash__() def show (self, prefix=''): outstr = '' outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' outstr += prefix + 'hw_addr: ' + str(EthAddr(self.hw_addr)) + '\n' outstr += prefix + 'name: ' + str(self.name) + '\n' outstr += prefix + 'config: ' + str(self.config) + '\n' outstr += prefix + 'state: ' + str(self.state) + '\n' outstr += prefix + 'curr: ' + str(self.curr) + '\n' outstr += prefix + 'advertised: ' + str(self.advertised) + '\n' outstr += prefix + 'supported: ' + str(self.supported) + '\n' outstr += prefix + 'peer: ' + str(self.peer) + '\n' return outstr def __repr__(self): return self.show() ofp_port_config_rev_map = { 'OFPPC_PORT_DOWN' : 1, 'OFPPC_NO_STP' : 2, 'OFPPC_NO_RECV' : 4, 'OFPPC_NO_RECV_STP' : 8, 'OFPPC_NO_FLOOD' : 16, 'OFPPC_NO_FWD' : 32, 'OFPPC_NO_PACKET_IN' : 64, } ofp_port_state_rev_map = { 'OFPPS_STP_LISTEN' : 0, 'OFPPS_LINK_DOWN' : 1, 'OFPPS_STP_LEARN' : 256, 'OFPPS_STP_FORWARD' : 512, 'OFPPS_STP_BLOCK' : 768, } OFPPS_STP_MASK = 768 ofp_port_features_rev_map = { 'OFPPF_10MB_HD' : 1, 'OFPPF_10MB_FD' : 2, 'OFPPF_100MB_HD' : 4, 'OFPPF_100MB_FD' : 8, 'OFPPF_1GB_HD' : 16, 'OFPPF_1GB_FD' : 32, 'OFPPF_10GB_FD' : 64, 'OFPPF_COPPER' : 128, 'OFPPF_FIBER' : 256, 'OFPPF_AUTONEG' : 512, 'OFPPF_PAUSE' : 1024, 'OFPPF_PAUSE_ASYM' : 2048, } ##2.2 Queue Structures class ofp_packet_queue (object): def __init__ (self, **kw): self.queue_id = 0 self.length = 0 self.properties = [] initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!LH", self.queue_id, self.length) packed += _PAD2 # Pad for i in self.properties: packed += i.pack(assertstruct) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.queue_id, self.length) = struct.unpack_from("!LH", binaryString, 0) return binaryString[8:] def __len__ (self): l = 8 for i in self.properties: l += len(i) return l def __eq__ (self, other): if type(self) != type(other): return False if self.queue_id != other.queue_id: return False if self.length != other.length: return False if self.properties != other.properties: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'queue_id: ' + str(self.queue_id) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'properties: \n' for obj in self.properties: outstr += obj.show(prefix + ' ') return outstr ofp_queue_properties_rev_map = { 'OFPQT_MIN_RATE' : 0, } OFPQT_NONE = 0 class ofp_queue_prop_header (object): def __init__ (self, **kw): self.property = 0 self.length = 8 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HH", self.property, self.length) packed += _PAD4 # Pad return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.property, self.length) = struct.unpack_from("!HH", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.property != other.property: return False if self.length != other.length: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'property: ' + str(self.property) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' return outstr class ofp_queue_prop_min_rate (object): def __init__ (self, **kw): self.prop_header = ofp_queue_prop_header() self.rate = 0 initHelper(self, kw) def _assert (self): if(not isinstance(self.prop_header, ofp_queue_prop_header)): return (False, "prop_header is not class ofp_queue_prop_header") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += self.prop_header.pack() packed += struct.pack("!H", self.rate) packed += _PAD6 return packed def unpack (self, binaryString): if (len(binaryString) < 16): return binaryString self.prop_header.unpack(binaryString[0:]) (self.rate,) = struct.unpack_from("!H", binaryString, 8) return binaryString[16:] def __len__ (self): return 16 def __eq__ (self, other): if type(self) != type(other): return False if self.prop_header != other.prop_header: return False if self.rate != other.rate: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'prop_header: \n' self.prop_header.show(prefix + ' ') outstr += prefix + 'rate: ' + str(self.rate) + '\n' return outstr ##2.3 Flow Match Structures class ofp_match (object): @classmethod def from_packet (cls, packet, in_port = None): """ get a match that matches this packet, asuming it came in on in_port in_port @param packet an instance of 'ethernet' """ assert_type("packet", packet, ethernet, none_ok=False) match = cls() if in_port is not None: match.in_port = in_port match.dl_src = packet.src match.dl_dst = packet.dst match.dl_type = packet.type p = packet.next # if isinstance(p, mpls): # match.mpls_label = p.label # match.mpls_tc = p.tc # else: # match.mpls_label = 0 # match.mpls_tc = 0 if isinstance(p, vlan): match.dl_vlan = p.id match.dl_vlan_pcp = p.pcp p = p.next else: match.dl_vlan = OFP_VLAN_NONE match.dl_vlan_pcp = 0 if isinstance(p, ipv4): match.nw_src = p.srcip match.nw_dst = p.dstip match.nw_proto = p.protocol match.nw_tos = p.tos p = p.next if isinstance(p, udp) or isinstance(p, tcp): match.tp_src = p.srcport match.tp_dst = p.dstport elif isinstance(p, icmp): match.tp_src = p.type match.tp_dst = p.code elif isinstance(p, arp): if p.opcode <= 255: match.nw_proto = p.opcode match.nw_src = p.protosrc match.nw_dst = p.protodst return match def optimize (self): """ Reduce the number of wildcards used. """ #TODO: Fix for optional cases (i.e. ARP) if self.dl_vlan == OFP_VLAN_NONE: self.dl_vlan_pcp = 0 #TODO: What do we do when something is "behind" a wildcard? # e.g., does nw_src count if dl_type is wild or only if it's 0x0800? if self.dl_type is not None: if self.dl_type != 0x0800: # Not IP if self.dl_type != 0x0806: # Not IP or ARP self.nw_src = IPAddr(0) self.nw_dst = IPAddr(0) eelf.nw_proto = 0 self.nw_tos = 0 self.tp_src = 0 self.tp_dst = 0 else: # It's IP if self.nw_proto != 6 and self.nw_proto != 17 and self.nw_proto != 1: # Not TCP, UDP, or ICMP self.tp_src = 0 self.tp_dst = 0 self.wildcards = self._normalize_wildcards(self.wildcards) return self # for chaining def clone (self): n = ofp_match() for k,v in ofp_match_data.iteritems(): setattr(n, '_' + k, getattr(self, '_' + k)) n.wildcards = self.wildcards return n def __init__ (self, **kw): for k,v in ofp_match_data.iteritems(): setattr(self, '_' + k, v[0]) self.wildcards = self._normalize_wildcards(OFPFW_ALL) # This is basically initHelper(), but tweaked slightly since this # class does some magic of its own. for k,v in kw.iteritems(): if not hasattr(self, '_'+k) and not hasattr(self, k): raise TypeError(self.__class__.__name__ + " constructor got " + "unexpected keyword argument '" + k + "'") setattr(self, k, v) def get_nw_dst (self): if (self.wildcards & OFPFW_NW_DST_ALL) == OFPFW_NW_DST_ALL: return (None, 0) w = (self.wildcards & OFPFW_NW_DST_MASK) >> OFPFW_NW_DST_SHIFT return (self._nw_dst,32-w if w <= 32 else 0) def get_nw_src (self): if (self.wildcards & OFPFW_NW_SRC_ALL) == OFPFW_NW_SRC_ALL: return (None, 0) w = (self.wildcards & OFPFW_NW_SRC_MASK) >> OFPFW_NW_SRC_SHIFT return (self._nw_src,32-w if w <= 32 else 0) def set_nw_dst (self, *args, **kw): a = self._make_addr(*args, **kw) if a == None: self._nw_src = ofp_match_data['nw_dst'][0] self.wildcards &= ~OFPFW_NW_DST_MASK self.wildcards |= ofp_match_data['nw_dst'][1] return self._nw_dst = a[0] self.wildcards &= ~OFPFW_NW_DST_MASK self.wildcards |= ((32-a[1]) << OFPFW_NW_DST_SHIFT) def set_nw_src (self, *args, **kw): a = self._make_addr(*args, **kw) # self.internal_links.add(Link(edge, edge.ports[port_no], host, host.interfaces[0])) if a == None: self._nw_src = ofp_match_data['nw_src'][0] self.wildcards &= ~OFPFW_NW_SRC_MASK self.wildcards |= ofp_match_data['nw_src'][1] return self._nw_src = a[0] self.wildcards &= ~OFPFW_NW_SRC_MASK self.wildcards |= ((32-a[1]) << OFPFW_NW_SRC_SHIFT) def _make_addr (self, ipOrIPAndBits, bits=None): if ipOrIPAndBits == None: return None b = None if type(ipOrIPAndBits) is tuple: ip = ipOrIPAndBits[0] b = int(ipOrIPAndBits[1]) if (type(ipOrIPAndBits) is str) and (len(ipOrIPAndBits) != 4): if ipOrIPAndBits.find('/') != -1: s = ipOrIPAndBits.split('/') ip = s[0] b = int(s[1]) if b is None else b else: ip = ipOrIPAndBits b = 32 if b is None else b else: ip = ipOrIPAndBits b = 32 if b is None else b if type(ip) is str: ip = IPAddr(ip) if bits != None: b = bits if b > 32: b = 32 elif b < 0: b = 0 return (ip, b) def __setattr__ (self, name, value): if name not in ofp_match_data: self.__dict__[name] = value return if name == 'nw_dst' or name == 'nw_src': # Special handling getattr(self, 'set_' + name)(value) return value if value is None: setattr(self, '_' + name, ofp_match_data[name][0]) self.wildcards |= ofp_match_data[name][1] else: setattr(self, '_' + name, value) self.wildcards = self.wildcards & ~ofp_match_data[name][1] return value def __getattr__ (self, name): if name in ofp_match_data: if (self.wildcards & ofp_match_data[name][1]) == ofp_match_data[name][1]: # It's wildcarded -- always return None return None if name == 'nw_dst' or name == 'nw_src': # Special handling return getattr(self, 'get_' + name)()[0] return self.__dict__['_' + name] raise AttributeError("attribute not found: "+name) def _assert (self): #if not isinstance(self._dl_src, list): # return "self.dl_src is not list" #if len(self._dl_src) != 6: # return "self.dl_src is not of size 6" #if not isinstance(self._dl_dst, list): # return "self.dl_dst is not list" if len(self._dl_dst) != 6: return "self.dl_dst is not of size 6" return None def pack (self, assertstruct=True, flow_mod=False): if(assertstruct): if self._assert() is not None: raise RuntimeError(self._assert()) packed = "" packed += struct.pack("!LH", self._wire_wildcards(self.wildcards) if flow_mod else self.wildcards, self.in_port or 0) if self.dl_src == None: packed += EMPTY_ETH.toRaw() elif type(self.dl_src) is bytes: packed += self.dl_src else: packed += self.dl_src.toRaw() if self.dl_dst == None: packed += EMPTY_ETH.toRaw() elif type(self.dl_dst) is bytes: packed += self.dl_dst else: packed += self.dl_dst.toRaw() def check_ip(val): return (val or 0) if self.dl_type == 0x0800 else 0 def check_ip_or_arp(val): return (val or 0) if self.dl_type == 0x0800 or self.dl_type == 0x0806 else 0 def check_tp(val): return (val or 0) if self.dl_type == 0x0800 and self.nw_proto in (1,6,17) else 0 packed += struct.pack("!HB", self.dl_vlan or 0, self.dl_vlan_pcp or 0) packed += _PAD # Hardcode padding packed += struct.pack("!HBB", self.dl_type or 0, check_ip(self.nw_tos), check_ip_or_arp(self.nw_proto)) packed += _PAD2 # Hardcode padding def fix (addr): if addr is None: return 0 if type(addr) is int: return addr & 0xffFFffFF if type(addr) is long: return addr & 0xffFFffFF return addr.toUnsigned() packed += struct.pack("!LLHH", check_ip_or_arp(fix(self.nw_src)), check_ip_or_arp(fix(self.nw_dst)), check_tp(self.tp_src), check_tp(self.tp_dst)) # if USE_MPLS_MATCH: # packed += struct.pack("!IBxxx", self.mpls_label or 0, self.mpls_tc or 0) return packed def _normalize_wildcards (self, wildcards): """ nw_src and nw_dst values greater than 32 mean the same thing as 32. We normalize them here just to be clean and so that comparisons act as you'd want them to. """ if ((wildcards & OFPFW_NW_SRC_MASK) >> OFPFW_NW_SRC_SHIFT) > 32: wildcards &= ~OFPFW_NW_SRC_MASK wildcards |= (32 << OFPFW_NW_SRC_SHIFT) if ((wildcards & OFPFW_NW_DST_MASK) >> OFPFW_NW_DST_SHIFT) > 32: wildcards &= ~OFPFW_NW_DST_MASK wildcards |= (32 << OFPFW_NW_DST_SHIFT) return wildcards def _wire_wildcards(self, wildcards): """ Normallize the wildcard bits to the openflow wire representation. Note this atrocity from the OF1.1 spec: Protocol-specific fields within ofp_match will be ignored within a single table when the corresponding protocol is not specified in the match. The MPLS match fields will be ignored unless the Ethertype is specified as MPLS. Likewise, the IP header and transport header fields will be ignored unless the Ethertype is specified as either IPv4 or ARP. The tp_src and tp_dst fields will be ignored unless the network protocol specified is as TCP, UDP or SCTP. Fields that are ignored don't need to be wildcarded and should be set to 0. """ if self.dl_type == 0x0800: # IP if self.nw_proto not in (1,6,17): # not TCP/UDP/ICMP -> Clear TP wildcards for the wire return wildcards & ~(OFPFW_TP_SRC | OFPFW_TP_DST) else: return wildcards elif self.dl_type == 0x0806: # ARP: clear NW_TOS / TP wildcards for the wire return wildcards & ~( OFPFW_NW_TOS | OFPFW_TP_SRC | OFPFW_TP_DST) else: # not even IP. Clear NW/TP wildcards for the wire return wildcards & ~( OFPFW_NW_TOS | OFPFW_NW_PROTO | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_TP_SRC | OFPFW_TP_DST) def _unwire_wildcards(self, wildcards): """ Normallize the wildcard bits from the openflow wire representation. Note this atrocity from the OF1.1 spec: Protocol-specific fields within ofp_match will be ignored within a single table when the corresponding protocol is not specified in the match. The MPLS match fields will be ignored unless the Ethertype is specified as MPLS. Likewise, the IP header and transport header fields will be ignored unless the Ethertype is specified as either IPv4 or ARP. The tp_src and tp_dst fields will be ignored unless the network protocol specified is as TCP, UDP or SCTP. Fields that are ignored don't need to be wildcarded and should be set to 0. """ if self._dl_type == 0x0800: # IP if self._nw_proto not in (1,6,17): # not TCP/UDP/ICMP -> Set TP wildcards for the object return wildcards | (OFPFW_TP_SRC | OFPFW_TP_DST) else: return wildcards elif self._dl_type == 0x0806: # ARP: Set NW_TOS / TP wildcards for the object return wildcards | ( OFPFW_NW_TOS | OFPFW_TP_SRC | OFPFW_TP_DST) else: # not even IP. Set NW/TP wildcards for the object return wildcards | ( OFPFW_NW_TOS | OFPFW_NW_PROTO | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_TP_SRC | OFPFW_TP_DST) @property def is_wildcarded (self): return self.wildcards & OFPFW_ALL != 0 @property def is_exact (self): return not self.is_wildcarded def unpack (self, binaryString, flow_mod=False): if (len(binaryString) < self.__len__()): return binaryString (wildcards, self._in_port) = struct.unpack_from("!LH", binaryString, 0) self._dl_src = EthAddr(struct.unpack_from("!BBBBBB", binaryString, 6)) self._dl_dst = EthAddr(struct.unpack_from("!BBBBBB", binaryString, 12)) (self._dl_vlan, self._dl_vlan_pcp) = struct.unpack_from("!HB", binaryString, 18) (self._dl_type, self._nw_tos, self._nw_proto) = struct.unpack_from("!HBB", binaryString, 22) (self._nw_src, self._nw_dst, self._tp_src, self._tp_dst) = struct.unpack_from("!LLHH", binaryString, 28) self._nw_src = IPAddr(self._nw_src) self._nw_dst = IPAddr(self._nw_dst) # if USE_MPLS_MATCH: # (self.mpls_label, self.mpls_tc) = struct.unpack_from("!IBxxx", binaryString, 40) self.wildcards = self._normalize_wildcards(self._unwire_wildcards(wildcards) if flow_mod else wildcards) # Overide return binaryString[self.__len__():] def __len__ (self): # if USE_MPLS_MATCH: # return 48 return 40 def hash_code (self): ''' ofp_match is not properly hashable since it is mutable, but it can still be useful to easily generate a hash code. ''' h = self.wildcards for f in ofp_match_data: v = getattr(self, f) if type(v) is int: h ^= v elif type(v) is long: h ^= v return int(h & 0x7fFFffFF) def matches_with_wildcards (self, other, consider_other_wildcards=True): """ Test whether /this/ match completely encompasses the other match. Important for non-strict modify flow_mods etc. """ assert_type("other", other, ofp_match, none_ok=False) # short cut for equal matches if(self == other): return True # only candidate if all wildcard bits in the *other* match are also set in this match (i.e., a submatch) # first compare the bitmask part if(consider_other_wildcards): self_bits = self.wildcards & ~(OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK) other_bits = other.wildcards & ~(OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK) if( self_bits | other_bits != self_bits): return False def match_fail(mine, others): return mine != None and mine != others if match_fail(self.in_port, other.in_port): return False if match_fail(self.dl_vlan, other.dl_vlan): return False if match_fail(self.dl_src, other.dl_src): return False if match_fail(self.dl_dst, other.dl_dst): return False if match_fail(self.dl_type, other.dl_type): return False if match_fail(self.nw_proto, other.nw_proto): return False if match_fail(self.tp_src, other.tp_src): return False if match_fail(self.tp_dst, other.tp_dst): return False if match_fail(self.dl_vlan_pcp, other.dl_vlan_pcp): return False if match_fail(self.nw_tos, other.nw_tos): return False self_nw_src = self.get_nw_src() if(self_nw_src[0] != None): other_nw_src = other.get_nw_src() if self_nw_src[1] > other_nw_src[1] or not IPAddr(other_nw_src[0]).inNetwork((self_nw_src[0], 32-self_nw_src[1])): return False self_nw_dst = self.get_nw_dst() if(self_nw_dst[0] != None): other_nw_dst = other.get_nw_dst() if self_nw_dst[1] > other_nw_dst[1] or not IPAddr(other_nw_dst[0]).inNetwork((self_nw_dst[0], 32-self_nw_dst[1])): return False return True def __eq__ (self, other): if type(self) != type(other): return False if self.wildcards != other.wildcards: return False if self.in_port != other.in_port: return False if self.dl_src != other.dl_src: return False if self.dl_dst != other.dl_dst: return False if self.dl_vlan != other.dl_vlan: return False if self.dl_vlan_pcp != other.dl_vlan_pcp: return False if self.dl_type != other.dl_type: return False if self.nw_tos != other.nw_tos: return False if self.nw_proto != other.nw_proto: return False if self.nw_src != other.nw_src: return False if self.nw_dst != other.nw_dst: return False if self.tp_src != other.tp_src: return False if self.tp_dst != other.tp_dst: return False return True def __ne__ (self, other): return not self.__eq__(other) def __str__ (self): return self.__class__.__name__ + "\n " + self.show(' ').strip() def show (self, prefix=''): def binstr (n): s = '' while True: s = ('1' if n & 1 else '0') + s n >>= 1 if n == 0: break return s def safehex(n): if n == None: return "(None)" else: return hex(n) def show_wildcards(w): parts = [ k.lower()[len("OFPFW_"):] for (k,v) in ofp_flow_wildcards_rev_map.iteritems() if v & w == v ] nw_src_bits = (w & OFPFW_NW_SRC_MASK) >> OFPFW_NW_SRC_SHIFT if(nw_src_bits > 0): parts.append("nw_src(/%d)" % (32 - nw_src_bits)) nw_dst_bits = (w & OFPFW_NW_DST_MASK) >> OFPFW_NW_DST_SHIFT if(nw_dst_bits > 0): parts.append("nw_dst(/%d)" % (32 - nw_dst_bits)) return "|".join(parts) outstr = '' outstr += prefix + 'wildcards: ' + show_wildcards(self.wildcards) + ' (' + binstr(self.wildcards) + ' = ' + hex(self.wildcards) + ')\n' def append (f, formatter=str): v = self.__getattr__(f) if v is None: return '' return prefix + f + ": " + formatter(v) + "\n" outstr += append('in_port') outstr += append('dl_src') outstr += append('dl_dst') outstr += append('dl_vlan') outstr += append('dl_vlan_pcp') outstr += append('dl_type', safehex) outstr += append('nw_tos') outstr += append('nw_proto') outstr += append('nw_src') outstr += append('nw_dst') outstr += append('tp_src') outstr += append('tp_dst') # outstr += append('mpls_label') # outstr += append('mpls_tc') return outstr ofp_flow_wildcards_rev_map = { 'OFPFW_IN_PORT' : 1, 'OFPFW_DL_VLAN' : 2, 'OFPFW_DL_SRC' : 4, 'OFPFW_DL_DST' : 8, 'OFPFW_DL_TYPE' : 16, 'OFPFW_NW_PROTO' : 32, 'OFPFW_TP_SRC' : 64, 'OFPFW_TP_DST' : 128, # 'OFPFW_MPLS_LABEL' : 1 << 21, # 'OFPFW_MPLS_TC' : 1 << 22, 'OFPFW_DL_VLAN_PCP' : 1048576, 'OFPFW_NW_TOS' : 1<<21, } OFPFW_NW_DST_BITS = 6 OFPFW_NW_SRC_BITS = 6 OFPFW_NW_SRC_SHIFT = 8 OFPFW_NW_DST_SHIFT = 14 OFPFW_NW_SRC_ALL = 8192 OFPFW_NW_SRC_MASK = 16128 OFPFW_NW_DST_ALL = 524288 OFPFW_NW_DST_MASK = 1032192 # Note: Need to handle all flags that are set in this # glob-all masks in the packet handling methods. (Esp. ofp_match.from_packet) # Otherwise, packets are not being matched as they should OFPFW_ALL = ((1 << 22) - 1) ##2.4 Flow Action Structures ofp_action_type_rev_map = { 'OFPAT_OUTPUT' : 0, 'OFPAT_SET_VLAN_VID' : 1, 'OFPAT_SET_VLAN_PCP' : 2, 'OFPAT_STRIP_VLAN' : 3, 'OFPAT_SET_DL_SRC' : 4, 'OFPAT_SET_DL_DST' : 5, 'OFPAT_SET_NW_SRC' : 6, 'OFPAT_SET_NW_DST' : 7, 'OFPAT_SET_NW_TOS' : 8, 'OFPAT_SET_TP_SRC' : 9, 'OFPAT_SET_TP_DST' : 10, 'OFPAT_ENQUEUE' : 11, 'OFPAT_SET_MPLS_LABEL':13, 'OFPAT_SET_MPLS_TC' : 14, 'OFPAT_SET_MPLS_TTL' : 15, 'OFPAT_DEC_MPLS_TTL' : 16, 'OFPAT_PUSH_MPLS' : 19, 'OFPAT_POP_MPLS' : 20, 'OFPAT_RESUBMIT' : 21, 'OFPAT_VENDOR' : 65535, } class ofp_action_header (object): def __init__ (self, **kw): self.type = None # Purposely bad self.length = 8 self.data = b'' initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HH", self.type, self.length) packed += _PAD4 # Pad return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length) = struct.unpack_from("!HH", binaryString, 0) if len(binaryString) < self.length: return binaryString self.data = binaryString[8:8+self.length] return binaryString[self.length:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' return outstr class ofp_action_output (object): def __init__ (self, **kw): self.type = OFPAT_OUTPUT self.length = 8 self.port = None # Purposely bad -- require specification self.max_len = 0xffFF initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if self.port != OFPP_CONTROLLER: self.max_len = 0 if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHHH", self.type, self.length, self.port, self.max_len) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.port, self.max_len) = struct.unpack_from("!HHHH", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.port != other.port: return False if self.max_len != other.max_len: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'port: ' + str(self.port) + '\n' outstr += prefix + 'max_len: ' + str(self.max_len) + '\n' return outstr def __repr__(self): return "ofp_action_output(port=%s)" % str(self.port) class ofp_action_enqueue (object): def __init__ (self, **kw): self.type = OFPAT_ENQUEUE self.length = 16 self.port = 0 self.queue_id = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHH", self.type, self.length, self.port) packed += _PAD6 # Pad packed += struct.pack("!L", self.queue_id) return packed def unpack (self, binaryString): if (len(binaryString) < 16): return binaryString (self.type, self.length, self.port) = struct.unpack_from("!HHH", binaryString, 0) (self.queue_id,) = struct.unpack_from("!L", binaryString, 12) return binaryString[16:] def __len__ (self): return 16 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.port != other.port: return False if self.queue_id != other.queue_id: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'port: ' + str(self.port) + '\n' outstr += prefix + 'queue_id: ' + str(self.queue_id) + '\n' return outstr class ofp_action_push_mpls (object): """ For now a push mpls action, but we can use this for push vlan too some day""" unicast_mpls_ethertype = 0x8847 multicast_mpls_ethertype = 0x8848 def __init__ (self, **kw): self.type = OFPAT_PUSH_MPLS self.length = 8 self.ethertype = ofp_action_push_mpls.unicast_mpls_ethertype initHelper(self, kw) def _assert(self): return ((self.ethertype == ofp_action_push_mpls.unicast_mpls_ethertype or self.ethertype == ofp_action_push_mpls.multicast_mpls_ethertype), None) def pack (self, assertstruct = True): if (assertstruct): if not (self._assert()[0]): return None packed = "" packed += struct.pack("!HHHxx", self.type, self.length, self.ethertype) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.ethertype) = struct.unpack_from("!HHH", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.ethertype != other.ethertype: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix = ''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'ethertype: ' + str(self.ethertype) + '\n' return outstr class ofp_action_mpls_label (object): def __init__ (self, **kw): self.type = OFPAT_SET_MPLS_LABEL self.length = 8 self.mpls_label = 0 initHelper(self, kw) def _assert(self): return (True, None) def pack (self, assertstruct = True): if (assertstruct): if not (self._assert()[0]): return None packed = "" packed += struct.pack("!HHI", self.type, self.length, self.mpls_label) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.mpls_label) = struct.unpack_from("!HHI", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.mpls_label != other.mpls_label: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix = ''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'label: ' + str(self.mpls_label) + '\n' return outstr class ofp_action_mpls_tc (object): def __init__ (self, **kw): self.type = OFPAT_SET_MPLS_TC self.length = 8 self.mpls_tc = 0 initHelper(self, kw) def _assert(self): return (True, None) def pack (self, assertstruct = True): if (assertstruct): if not (self._assert()[0]): return None packed = "" packed += struct.pack("!HHBxxx", self.type, self.length, self.mpls_tc) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.mpls_tc) = struct.unpack_from("!HHB", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.mpls_tc != other.mpls_tc: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix = ''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'tc: ' + str(self.mpls_tc) + '\n' return outstr class ofp_action_mpls_ttl (object): def __init__ (self, **kw): self.type = OFPAT_SET_MPLS_TTL self.length = 8 self.mpls_ttl = 0 initHelper(self, kw) def _assert(self): return (True, None) def pack (self, assertstruct = True): if (assertstruct): if not (self._assert()[0]): return None packed = "" packed += struct.pack("!HHBxxx", self.type, self.length, self.mpls_ttl) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.mpls_ttl) = struct.unpack_from("!HHB", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.mpls_ttl != other.mpls_ttl: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix = ''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'ttl: ' + str(self.mpls_ttl) + '\n' return outstr class ofp_action_mpls_dec_ttl (ofp_action_header): def __init__ (self, **kw): super(ofp_action_mpls_dec_ttl, self).__init__(**kw) self.type = OFPAT_DEC_MPLS_TTL class ofp_action_resubmit (ofp_action_header): def __init__ (self, **kw): super(ofp_action_resubmit, self).__init__(**kw) self.type = OFPAT_RESUBMIT class ofp_action_pop_mpls (object): def __init__ (self, **kw): self.type = OFPAT_POP_MPLS self.length = 8 self.ethertype = 0 initHelper(self, kw) def _assert(self): return (True, None) def pack (self, assertstruct = True): if (assertstruct): if not (self._assert()[0]): return None packed = "" packed += struct.pack("!HHHxx", self.type, self.length, self.ethertype) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.ethertype) = struct.unpack_from("!HHH", binaryString, 0) return binaryString[8:] def __len__ (self): return self.length def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.ethertype != other.ethertype: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix = ''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'ethertype: ' + str(self.ethertype) + '\n' return outstr class ofp_action_vlan_vid (object): def __init__ (self, **kw): self.type = OFPAT_SET_VLAN_VID self.length = 8 self.vlan_vid = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHH", self.type, self.length, self.vlan_vid) packed += _PAD2 # Pad return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.vlan_vid) = struct.unpack_from("!HHH", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.vlan_vid != other.vlan_vid: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'vlan_vid: ' + str(self.vlan_vid) + '\n' return outstr class ofp_action_vlan_pcp (object): def __init__ (self, **kw): self.type = OFPAT_SET_VLAN_PCP self.length = 8 self.vlan_pcp = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHB", self.type, self.length, self.vlan_pcp) packed += _PAD3 # Pad return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.vlan_pcp) = struct.unpack_from("!HHB", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.vlan_pcp != other.vlan_pcp: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'vlan_pcp: ' + str(self.vlan_pcp) + '\n' return outstr class ofp_action_dl_addr (object): @classmethod def set_dst (cls, dl_addr = None): return cls(OFPAT_SET_DL_DST, dl_addr) @classmethod def set_src (cls, dl_addr = None): return cls(OFPAT_SET_DL_SRC, dl_addr) def __init__ (self, type = None, dl_addr = None): """ 'type' should be OFPAT_SET_DL_SRC or OFPAT_SET_DL_DST. """ self.type = type self.length = 16 self.dl_addr = EMPTY_ETH if dl_addr is not None: self.dl_addr = EthAddr(dl_addr) def _assert (self): if not isinstance(self.dl_addr, EthAddr) and not isinstance(self.dl_addr, bytes): return (False, "dl_addr is not string or EthAddr") if isinstance(self.dl_addr, bytes) and len(self.dl_addr) != 6: return (False, "dl_addr is not of size 6") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HH", self.type, self.length) if isinstance(self.dl_addr, EthAddr): packed += self.dl_addr.toRaw() else: packed += self.dl_addr packed += _PAD6 return packed def unpack (self, binaryString): if (len(binaryString) < 16): return binaryString (self.type, self.length) = struct.unpack_from("!HH", binaryString, 0) self.dl_addr = EthAddr(struct.unpack_from("!BBBBBB", binaryString, 4)) return binaryString[16:] def __len__ (self): return 16 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.dl_addr != other.dl_addr: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'dl_addr: ' + str(self.dl_addr) + '\n' return outstr class ofp_action_nw_addr (object): @classmethod def set_dst (cls, nw_addr = None): return cls(OFPAT_SET_NW_DST, nw_addr) @classmethod def set_src (cls, nw_addr = None): return cls(OFPAT_SET_NW_SRC, nw_addr) def __init__ (self, type = None, nw_addr = None): """ 'type' should be OFPAT_SET_NW_SRC or OFPAT_SET_NW_DST """ self.type = type self.length = 8 if nw_addr is not None: self.nw_addr = IPAddr(nw_addr) else: self.nw_addr = IPAddr(0) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHl", self.type, self.length, self.nw_addr.toSigned()) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.nw_addr) = struct.unpack_from("!HHL", binaryString, 0) self.nw_addr = IPAddr(self.nw_addr, networkOrder=False) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.nw_addr != other.nw_addr: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'nw_addr: ' + str(self.nw_addr) + '\n' return outstr class ofp_action_nw_tos (object): def __init__ (self, nw_tos = 0): self.type = OFPAT_SET_NW_TOS self.length = 8 self.nw_tos = nw_tos def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHB", self.type, self.length, self.nw_tos) packed += _PAD3 return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.nw_tos) = struct.unpack_from("!HHB", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.nw_tos != other.nw_tos: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'nw_tos: ' + str(self.nw_tos) + '\n' return outstr class ofp_action_tp_port (object): @classmethod def set_dst (cls, tp_port = None): return cls(OFPAT_SET_TP_DST, tp_port) @classmethod def set_src (cls, tp_port = None): return cls(OFPAT_SET_TP_SRC, tp_port) def __init__ (self, type=None, tp_port = 0): """ 'type' is OFPAT_SET_TP_SRC/DST """ self.type = type self.length = 8 self.tp_port = tp_port def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHH", self.type, self.length, self.tp_port) packed += _PAD2 return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.tp_port) = struct.unpack_from("!HHH", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.tp_port != other.tp_port: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'tp_port: ' + str(self.tp_port) + '\n' return outstr class ofp_action_vendor_header (object): def __init__ (self, **kw): self.type = OFPAT_VENDOR self.length = 8 self.vendor = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HHL", self.type, self.length, self.vendor) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.type, self.length, self.vendor) = struct.unpack_from("!HHL", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.type != other.type: return False if self.length != other.length: return False if self.vendor != other.vendor: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'len: ' + str(self.length) + '\n' outstr += prefix + 'vendor: ' + str(self.vendor) + '\n' return outstr #3. Controller-to-Switch Messages ##3.1 Handshake # was ofp_switch_features class ofp_features_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.datapath_id = 0 self.n_buffers = 0 self.n_tables = 0 self.capabilities = 0 self.actions = 0 self.ports = [] initHelper(self, kw) self.header_type = OFPT_FEATURES_REPLY self.length = len(self) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!QLB", self.datapath_id, self.n_buffers, self.n_tables) packed += _PAD3 packed += struct.pack("!LL", self.capabilities, self.actions) for i in self.ports: packed += i.pack(assertstruct) return packed def unpack (self, binaryString): if (len(binaryString) < 32): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.datapath_id, self.n_buffers, self.n_tables) = struct.unpack_from("!QLB", binaryString, 8) (self.capabilities, self.actions) = struct.unpack_from("!LL", binaryString, 24) portCount = (self.length - 32) / OFP_PHY_PORT_BYTES self.ports = [] for i in xrange(0, portCount): p = ofp_phy_port() p.unpack(binaryString[32+i*OFP_PHY_PORT_BYTES:]) self.ports.append(p) return binaryString[self.length:] def __len__ (self): l = 32 for _ in self.ports: l += OFP_PHY_PORT_BYTES return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.datapath_id != other.datapath_id: return False if self.n_buffers != other.n_buffers: return False if self.n_tables != other.n_tables: return False if self.capabilities != other.capabilities: return False if self.actions != other.actions: return False if self.ports != other.ports: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'datapath_id: ' + str(self.datapath_id) + '\n' outstr += prefix + 'n_buffers: ' + str(self.n_buffers) + '\n' outstr += prefix + 'n_tables: ' + str(self.n_tables) + '\n' outstr += prefix + 'capabilities: ' + str(self.capabilities) + '\n' outstr += prefix + 'actions: ' + str(self.actions) + '\n' outstr += prefix + 'ports: \n' for obj in self.ports: outstr += obj.show(prefix + ' ') return outstr ofp_switch_features = ofp_features_reply ofp_capabilities_rev_map = { 'OFPC_FLOW_STATS' : 1, 'OFPC_TABLE_STATS' : 2, 'OFPC_PORT_STATS' : 4, 'OFPC_STP' : 8, 'OFPC_RESERVED' : 16, 'OFPC_IP_REASM' : 32, 'OFPC_QUEUE_STATS' : 64, 'OFPC_ARP_MATCH_IP' : 128, } ##3.2 Switch Configuration class ofp_switch_config (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_SET_CONFIG self.length = 12 self.flags = 0 self.miss_send_len = OFP_DEFAULT_MISS_SEND_LEN initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.flags, self.miss_send_len) return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.flags, self.miss_send_len) = struct.unpack_from("!HH", binaryString, 8) return binaryString[12:] def __len__ (self): l = 12 return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.flags != other.flags: return False if self.miss_send_len != other.miss_send_len: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'miss_send_len: ' + str(self.miss_send_len) + '\n' return outstr ofp_config_flags_rev_map = { 'OFPC_FRAG_NORMAL' : 0, 'OFPC_FRAG_DROP' : 1, 'OFPC_FRAG_REASM' : 2, 'OFPC_FRAG_MASK' : 3, } ##3.3 Modify State Messages class ofp_flow_mod (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_FLOW_MOD if 'match' in kw: self.match = None else: self.match = ofp_match() self.cookie = 0 self.command = OFPFC_ADD self.idle_timeout = 0 self.hard_timeout = 0 self.priority = OFP_DEFAULT_PRIORITY self.buffer_id = -1 self.out_port = OFPP_NONE self.flags = 0 self.actions = [] # ofp_flow_mod and ofp_packet_out do some special handling of 'actions'... # Allow "action" as a synonym for "actions" if 'action' in kw and 'actions' not in kw: kw['actions'] = kw['action'] del kw['action'] initHelper(self, kw) # Allow use of actions=<a single action> for kw args. if not hasattr(self.actions, '__getitem__'): self.actions = [self.actions] def _assert (self): if(not isinstance(self.match, ofp_match)): return (False, "match is not class ofp_match") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" self.length = len(self) packed += ofp_header.pack(self) packed += self.match.pack(flow_mod=True) packed += struct.pack("!QHHHHLHH", self.cookie, self.command, self.idle_timeout, self.hard_timeout, self.priority, self.buffer_id & 0xffffffff, self.out_port, self.flags) for i in self.actions: packed += i.pack(assertstruct) return packed def unpack (self, binaryString): if (len(binaryString) < 72): return binaryString ofp_header.unpack(self, binaryString[0:]) self.match.unpack(binaryString[8:], flow_mod=True) (self.cookie, self.command, self.idle_timeout, self.hard_timeout, self.priority, self.buffer_id, self.out_port, self.flags) = struct.unpack_from("!QHHHHLHH", binaryString, 8 + len(self.match)) if self.buffer_id == 0xffffffff: self.buffer_id = -1 self.actions, offset = _unpack_actions(binaryString, self.length-(32 + len(self.match)), 32 + len(self.match)) assert offset == self.length return binaryString[offset:] def __len__ (self): l = 32 + len(self.match) for i in self.actions: l += len(i)#.length() return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.match != other.match: return False if self.cookie != other.cookie: return False if self.command != other.command: return False if self.idle_timeout != other.idle_timeout: return False if self.hard_timeout != other.hard_timeout: return False if self.priority != other.priority: return False if self.buffer_id != other.buffer_id: return False if self.out_port != other.out_port: return False if self.flags != other.flags: return False if self.actions != other.actions: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'match: \n' outstr += self.match.show(prefix + ' ') outstr += prefix + 'cookie: ' + str(self.cookie) + '\n' outstr += prefix + 'command: ' + str(self.command) + '\n' outstr += prefix + 'idle_timeout: ' + str(self.idle_timeout) + '\n' outstr += prefix + 'hard_timeout: ' + str(self.hard_timeout) + '\n' outstr += prefix + 'priority: ' + str(self.priority) + '\n' outstr += prefix + 'buffer_id: ' + str(self.buffer_id) + '\n' outstr += prefix + 'out_port: ' + str(self.out_port) + '\n' outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'actions: \n' for obj in self.actions: outstr += obj.show(prefix + ' ') return outstr ofp_flow_mod_command_rev_map = { 'OFPFC_ADD' : 0, 'OFPFC_MODIFY' : 1, 'OFPFC_MODIFY_STRICT' : 2, 'OFPFC_DELETE' : 3, 'OFPFC_DELETE_STRICT' : 4, } ofp_flow_mod_flags_rev_map = { 'OFPFF_SEND_FLOW_REM' : 1, 'OFPFF_CHECK_OVERLAP' : 2, 'OFPFF_EMERG' : 4, } class ofp_port_mod (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_PORT_MOD self.port_no = 0 self.hw_addr = EMPTY_ETH self.config = 0 self.mask = 0 self.advertise = 0 self.length = 32 initHelper(self, kw) def _assert (self): if not isinstance(self.hw_addr, bytes) and not isinstance(self.hw_addr, EthAddr): return (False, "hw_addr is not bytes or EthAddr") if len(self.hw_addr) != 6: return (False, "hw_addr is not of size 6") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!H", self.port_no) if isinstance(self.hw_addr, bytes): packed += self.hw_addr else: packed += self.hw_addr.toRaw() packed += struct.pack("!LLL", self.config, self.mask, self.advertise) packed += _PAD4 return packed def unpack (self, binaryString): if (len(binaryString) < 32): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.port_no,) = struct.unpack_from("!H", binaryString, 8) self.hw_addr = EthAddr(binaryString[10:16]) (self.config, self.mask, self.advertise) = struct.unpack_from("!LLL", binaryString, 16) return binaryString[32:] def __len__ (self): return 32 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.port_no != other.port_no: return False if self.hw_addr != other.hw_addr: return False if self.config != other.config: return False if self.mask != other.mask: return False if self.advertise != other.advertise: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' outstr += prefix + 'hw_addr: ' + str(EthAddr(self.hw_addr)) + '\n' outstr += prefix + 'config: ' + str(self.config) + '\n' outstr += prefix + 'mask: ' + str(self.mask) + '\n' outstr += prefix + 'advertise: ' + str(self.advertise) + '\n' return outstr ##3.4 Queue Configuration Messages class ofp_queue_get_config_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_QUEUE_GET_CONFIG_REQUEST self.port = 0 self.length = 12 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!H", self.port) packed += _PAD2 return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.port,) = struct.unpack_from("!H", binaryString, 8) return binaryString[12:] def __len__ (self): return 12 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.port != other.port: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'port: ' + str(self.port) + '\n' return outstr class ofp_queue_get_config_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_QUEUE_GET_CONFIG_REPLY self.length = 16 self.port = 0 self.queues = [] initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!H", self.port) packed += _PAD6 for i in self.queues: packed += i.pack(assertstruct) return packed def unpack (self, binaryString): if (len(binaryString) < 16): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.port,) = struct.unpack_from("!H", binaryString, 8) return binaryString[16:] def __len__ (self): l = 16 for i in self.queues: l += len(i) return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.port != other.port: return False if self.queues != other.queues: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'port: ' + str(self.port) + '\n' outstr += prefix + 'queues: \n' for obj in self.queues: outstr += obj.show(prefix + ' ') return outstr ##3.5 Read State Messages class ofp_stats_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_STATS_REQUEST self.type = None # Try to guess self.flags = 0 self.body = b'' self._body_data = (None, None) initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): self.length = len(self) if self.type is None: if isinstance(self.body, ofp_flow_stats_request): self.type = OFPST_FLOW elif isinstance(self.body, ofp_aggregate_stats_request): self.type = OFPST_AGGREGATE elif self.body_data == b'': self.type = OFPST_DESC # Maybe shouldn't assume this? if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.type, self.flags) packed += self.body_data return packed @property def body_data (self): if self._body_data[0] is not self.body: if hasattr(self.body, 'pack'): self._body_data = (self.body, self.body.pack()) else: self._body_data = (self.body, self.body) return self._body_data[1] def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.type, self.flags) = struct.unpack_from("!HH", binaryString, 8) self.body = binaryString[12:self.length] assert self.length == len(self) return binaryString[self.length:] def __len__ (self): return 12 + len(self.body_data) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.type != other.type: return False if self.flags != other.flags: return False if self.body_data != other.body_data: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'body:\n' + _format_body(self.body, prefix + ' ') + '\n' return outstr class ofp_stats_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_STATS_REPLY self.type = 0 self.flags = 0 self.body = b'' self._body_data = (None, None) initHelper(self, kw) def _assert (self): return (True, None) @property def body_data (self): if self._body_data[0] is not self.body: def _pack(b): return b.pack() if hasattr(b, 'pack') else b data = b'' if isinstance(self.body, collections.Iterable): for b in self.body: data += _pack(b) else: data = _pack(self.body) self._body_data = (self.body, data) return self._body_data[1] def pack (self, assertstruct=True): if type == None or type == 0 and type(self.body) in ofp_stats_reply_class_to_type_map: self.type = ofp_stats_reply_class_to_type_map[type(self.body)] self.length = len(self) if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.type, self.flags) packed += self.body_data return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.type, self.flags) = struct.unpack_from("!HH", binaryString, 8) self.body = binaryString[12:self.length] return binaryString[self.length:] def __len__ (self): l = 12 l += len(self.body) return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.type != other.type: return False if self.flags != other.flags: return False if self.body != other.body: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'type: ' + str(self.type) + '\n' outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'body:\n' + _format_body(self.body, prefix + ' ') + '\n' return outstr ofp_stats_types_rev_map = { 'OFPST_DESC' : 0, 'OFPST_FLOW' : 1, 'OFPST_AGGREGATE' : 2, 'OFPST_TABLE' : 3, 'OFPST_PORT' : 4, 'OFPST_QUEUE' : 5, 'OFPST_VENDOR' : 65535, } ofp_stats_reply_flags_rev_map = { 'OFPSF_REPLY_MORE' : 1, } class ofp_desc_stats (object): def __init__ (self, **kw): self.mfr_desc= "" self.hw_desc= "" self.sw_desc= "" self.serial_num= "" self.dp_desc= "" initHelper(self, kw) def _assert (self): if(not isinstance(self.mfr_desc, str)): return (False, "mfr_desc is not string") if(len(self.mfr_desc) > 256): return (False, "mfr_desc is not of size 256") if(not isinstance(self.hw_desc, str)): return (False, "hw_desc is not string") if(len(self.hw_desc) > 256): return (False, "hw_desc is not of size 256") if(not isinstance(self.sw_desc, str)): return (False, "sw_desc is not string") if(len(self.sw_desc) > 256): return (False, "sw_desc is not of size 256") if(not isinstance(self.serial_num, str)): return (False, "serial_num is not string") if(len(self.serial_num) > 32): return (False, "serial_num is not of size 32") if(not isinstance(self.dp_desc, str)): return (False, "dp_desc is not string") if(len(self.dp_desc) > 256): return (False, "dp_desc is not of size 256") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += self.mfr_desc.ljust(256,'\0') packed += self.hw_desc.ljust(256,'\0') packed += self.sw_desc.ljust(256,'\0') packed += self.serial_num.ljust(32,'\0') packed += self.dp_desc.ljust(256,'\0') return packed def unpack (self, binaryString): if (len(binaryString) < 1056): return binaryString self.mfr_desc = binaryString[0:256].replace("\0","") self.hw_desc = binaryString[256:512].replace("\0","") self.sw_desc = binaryString[512:768].replace("\0","") self.serial_num = binaryString[768:800].replace("\0","") self.dp_desc = binaryString[800:1056].replace("\0","") return binaryString[1056:] def __len__ (self): return 1056 def __eq__ (self, other): if type(self) != type(other): return False if self.mfr_desc != other.mfr_desc: return False if self.hw_desc != other.hw_desc: return False if self.sw_desc != other.sw_desc: return False if self.serial_num != other.serial_num: return False if self.dp_desc != other.dp_desc: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'mfr_desc: ' + str(self.mfr_desc) + '\n' outstr += prefix + 'hw_desc: ' + str(self.hw_desc) + '\n' outstr += prefix + 'sw_desc: ' + str(self.sw_desc) + '\n' outstr += prefix + 'serial_num: ' + str(self.serial_num) + '\n' outstr += prefix + 'dp_desc: ' + str(self.dp_desc) + '\n' return outstr class ofp_flow_stats_request (object): def __init__ (self, **kw): self.match = ofp_match() self.table_id = TABLE_ALL self.out_port = OFPP_NONE initHelper(self, kw) def _assert (self): if(not isinstance(self.match, ofp_match)): return (False, "match is not class ofp_match") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += self.match.pack() packed += struct.pack("!BBH", self.table_id, 0, self.out_port) return packed def unpack (self, binaryString): if (len(binaryString) < 44): return binaryString self.match.unpack(binaryString[0:]) (self.table_id, pad, self.out_port) = struct.unpack_from("!BBH", binaryString, len(self.match)) return binaryString[len(self)] def __len__ (self): return 4 + len(self.match) def __eq__ (self, other): if type(self) != type(other): return False if self.match != other.match: return False if self.table_id != other.table_id: return False if self.out_port != other.out_port: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'match: \n' self.match.show(prefix + ' ') outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' outstr += prefix + 'out_port: ' + str(self.out_port) + '\n' return outstr class ofp_flow_stats (object): def __init__ (self, **kw): self.length = 0 self.table_id = 0 self.match = ofp_match() self.duration_sec = 0 self.duration_nsec = 0 self.priority = OFP_DEFAULT_PRIORITY self.idle_timeout = 0 self.hard_timeout = 0 self.cookie = 0 self.packet_count = 0 self.byte_count = 0 self.actions = [] initHelper(self, kw) def _assert (self): if(not isinstance(self.match, ofp_match)): return (False, "match is not class ofp_match") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!HBB", self.length, self.table_id, 0) packed += self.match.pack() packed += struct.pack("!LLHHH", self.duration_sec, self.duration_nsec, self.priority, self.idle_timeout, self.hard_timeout) packed += _PAD6 # Pad packed += struct.pack("!QQQ", self.cookie, self.packet_count, self.byte_count) for i in self.actions: packed += i.pack(assertstruct) return packed def unpack (self, binaryString): if (len(binaryString) < 48 + len(self.match)): return binaryString (self.length, self.table_id, pad) = struct.unpack_from("!HBB", binaryString, 0) self.match.unpack(binaryString[4:]) (self.duration_sec, self.duration_nsec, self.priority, self.idle_timeout, self.hard_timeout) = struct.unpack_from("!LLHHH", binaryString, 4 + len(self.match)) (self.cookie, self.packet_count, self.byte_count) = struct.unpack_from("!QQQ", binaryString, 24 + len(self.match)) self.actions,offset = _unpack_actions(binaryString, self.length - (48 + len(self.match)), 48 + len(self.match)) assert offset == self.length assert self.length == len(self) return binaryString[offset:] def __len__ (self): l = 48 + len(self.match) for i in self.actions: l += len(i) return l def __eq__ (self, other): if type(self) != type(other): return False if self.length != other.length: return False if self.table_id != other.table_id: return False if self.match != other.match: return False if self.duration_sec != other.duration_sec: return False if self.duration_nsec != other.duration_nsec: return False if self.priority != other.priority: return False if self.idle_timeout != other.idle_timeout: return False if self.hard_timeout != other.hard_timeout: return False if self.cookie != other.cookie: return False if self.packet_count != other.packet_count: return False if self.byte_count != other.byte_count: return False if self.actions != other.actions: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'length: ' + str(self.length) + '\n' outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' outstr += prefix + 'match: \n' self.match.show(prefix + ' ') outstr += prefix + 'duration_sec: ' + str(self.duration_sec) + '\n' outstr += prefix + 'duration_nsec: ' + str(self.duration_nsec) + '\n' outstr += prefix + 'priority: ' + str(self.priority) + '\n' outstr += prefix + 'idle_timeout: ' + str(self.idle_timeout) + '\n' outstr += prefix + 'hard_timeout: ' + str(self.hard_timeout) + '\n' outstr += prefix + 'cookie: ' + str(self.cookie) + '\n' outstr += prefix + 'packet_count: ' + str(self.packet_count) + '\n' outstr += prefix + 'byte_count: ' + str(self.byte_count) + '\n' outstr += prefix + 'actions: \n' for obj in self.actions: outstr += obj.show(prefix + ' ') return outstr class ofp_aggregate_stats_request (object): def __init__ (self, **kw): self.match = ofp_match() self.table_id = TABLE_ALL self.out_port = OFPP_NONE initHelper(self, kw) def _assert (self): if(not isinstance(self.match, ofp_match)): return (False, "match is not class ofp_match") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += self.match.pack() packed += struct.pack("!BBH", self.table_id, 0, self.out_port) return packed def unpack (self, binaryString): if (len(binaryString) < 4 + len(self.match)): return binaryString self.match.unpack(binaryString[0:]) (self.table_id, pad, self.out_port) = struct.unpack_from("!BBH", binaryString, len(self.match)) return binaryString[44:] def __len__ (self): return 44 def __eq__ (self, other): if type(self) != type(other): return False if self.match != other.match: return False if self.table_id != other.table_id: return False if self.out_port != other.out_port: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'match: \n' self.match.show(prefix + ' ') outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' outstr += prefix + 'out_port: ' + str(self.out_port) + '\n' return outstr class ofp_aggregate_stats (object): def __init__ (self, **kw): self.packet_count = 0 self.byte_count = 0 self.flow_count = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!QQL", self.packet_count, self.byte_count, self.flow_count) packed += _PAD4 # Pad return packed def unpack (self, binaryString): if (len(binaryString) < 24): return binaryString (self.packet_count, self.byte_count, self.flow_count) = struct.unpack_from("!QQL", binaryString, 0) return binaryString[24:] def __len__ (self): return 24 def __eq__ (self, other): if type(self) != type(other): return False if self.packet_count != other.packet_count: return False if self.byte_count != other.byte_count: return False if self.flow_count != other.flow_count: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'packet_count: ' + str(self.packet_count) + '\n' outstr += prefix + 'byte_count: ' + str(self.byte_count) + '\n' outstr += prefix + 'flow_count: ' + str(self.flow_count) + '\n' return outstr ofp_aggregate_stats_reply = ofp_aggregate_stats class ofp_table_stats (object): def __init__ (self, **kw): self.table_id = 0 self.name= "" self.wildcards = 0 self.max_entries = 0 self.active_count = 0 self.lookup_count = 0 self.matched_count = 0 initHelper(self, kw) def _assert (self): if(not isinstance(self.name, str)): return (False, "name is not string") if(len(self.name) > 32): return (False, "name is not of size 32") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!B", self.table_id) packed += _PAD3 packed += self.name.ljust(32,'\0') packed += struct.pack("!LLLQQ", self.wildcards, self.max_entries, self.active_count, self.lookup_count, self.matched_count) return packed def unpack (self, binaryString): if (len(binaryString) < 64): return binaryString (self.table_id,) = struct.unpack_from("!B", binaryString, 0) self.name = binaryString[4:36].replace("\0","") (self.wildcards, self.max_entries, self.active_count, self.lookup_count, self.matched_count) = struct.unpack_from("!LLLQQ", binaryString, 36) return binaryString[64:] def __len__ (self): return 64 def __eq__ (self, other): if type(self) != type(other): return False if self.table_id != other.table_id: return False if self.name != other.name: return False if self.wildcards != other.wildcards: return False if self.max_entries != other.max_entries: return False if self.active_count != other.active_count: return False if self.lookup_count != other.lookup_count: return False if self.matched_count != other.matched_count: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' outstr += prefix + 'name: ' + str(self.name) + '\n' outstr += prefix + 'wildcards: ' + str(self.wildcards) + '\n' outstr += prefix + 'max_entries: ' + str(self.max_entries) + '\n' outstr += prefix + 'active_count: ' + str(self.active_count) + '\n' outstr += prefix + 'lookup_count: ' + str(self.lookup_count) + '\n' outstr += prefix + 'matched_count: ' + str(self.matched_count) + '\n' return outstr class ofp_port_stats_request (object): def __init__ (self, **kw): self.port_no = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!H", self.port_no) packed += _PAD6 return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.port_no,) = struct.unpack_from("!H", binaryString, 0) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.port_no != other.port_no: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' return outstr class ofp_port_stats (object): def __init__ (self, **kw): self.port_no = 0 self.rx_packets = 0 self.tx_packets = 0 self.rx_bytes = 0 self.tx_bytes = 0 self.rx_dropped = 0 self.tx_dropped = 0 self.rx_errors = 0 self.tx_errors = 0 self.rx_frame_err = 0 self.rx_over_err = 0 self.rx_crc_err = 0 self.collisions = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!H", self.port_no) packed += _PAD6 packed += struct.pack("!QQQQQQQQQQQQ", self.rx_packets, self.tx_packets, self.rx_bytes, self.tx_bytes, self.rx_dropped, self.tx_dropped, self.rx_errors, self.tx_errors, self.rx_frame_err, self.rx_over_err, self.rx_crc_err, self.collisions) return packed def unpack (self, binaryString): if (len(binaryString) < 104): return binaryString (self.port_no,) = struct.unpack_from("!H", binaryString, 0) (self.rx_packets, self.tx_packets, self.rx_bytes, self.tx_bytes, self.rx_dropped, self.tx_dropped, self.rx_errors, self.tx_errors, self.rx_frame_err, self.rx_over_err, self.rx_crc_err, self.collisions) = struct.unpack_from("!QQQQQQQQQQQQ", binaryString, 8) return binaryString[104:] def __len__ (self): return 104 def __eq__ (self, other): if type(self) != type(other): return False if self.port_no != other.port_no: return False if self.rx_packets != other.rx_packets: return False if self.tx_packets != other.tx_packets: return False if self.rx_bytes != other.rx_bytes: return False if self.tx_bytes != other.tx_bytes: return False if self.rx_dropped != other.rx_dropped: return False if self.tx_dropped != other.tx_dropped: return False if self.rx_errors != other.rx_errors: return False if self.tx_errors != other.tx_errors: return False if self.rx_frame_err != other.rx_frame_err: return False if self.rx_over_err != other.rx_over_err: return False if self.rx_crc_err != other.rx_crc_err: return False if self.collisions != other.collisions: return False return True def __ne__ (self, other): return not self.__eq__(other) def __add__(self, other): if type(self) != type(other): raise NotImplemented() return ofp_port_stats( port_no=OFPP_NONE, rx_packets = self.rx_packets + other.rx_packets, tx_packets = self.tx_packets + other.tx_packets, rx_bytes = self.rx_bytes + other.rx_bytes, tx_bytes = self.tx_bytes + other.tx_bytes, rx_dropped = self.rx_dropped + other.rx_dropped, tx_dropped = self.tx_dropped + other.tx_dropped, rx_errors = self.rx_errors + other.rx_errors, tx_errors = self.tx_errors + other.tx_errors, rx_frame_err = self.rx_frame_err + other.rx_frame_err, rx_over_err = self.rx_over_err + other.rx_over_err, rx_crc_err = self.rx_crc_err + other.rx_crc_err, collisions = self.collisions + other.collisions) def show (self, prefix=''): outstr = '' outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' outstr += prefix + 'rx_packets: ' + str(self.rx_packets) + '\n' outstr += prefix + 'tx_packets: ' + str(self.tx_packets) + '\n' outstr += prefix + 'rx_bytes: ' + str(self.rx_bytes) + '\n' outstr += prefix + 'tx_bytes: ' + str(self.tx_bytes) + '\n' outstr += prefix + 'rx_dropped: ' + str(self.rx_dropped) + '\n' outstr += prefix + 'tx_dropped: ' + str(self.tx_dropped) + '\n' outstr += prefix + 'rx_errors: ' + str(self.rx_errors) + '\n' outstr += prefix + 'tx_errors: ' + str(self.tx_errors) + '\n' outstr += prefix + 'rx_frame_err: ' + str(self.rx_frame_err) + '\n' outstr += prefix + 'rx_over_err: ' + str(self.rx_over_err) + '\n' outstr += prefix + 'rx_crc_err: ' + str(self.rx_crc_err) + '\n' outstr += prefix + 'collisions: ' + str(self.collisions) + '\n' return outstr class ofp_queue_stats_request (object): def __init__ (self, **kw): self.port_no = 0 self.queue_id = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!H", self.port_no) packed += _PAD2 packed += struct.pack("!L", self.queue_id) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString (self.port_no,) = struct.unpack_from("!H", binaryString, 0) (self.queue_id,) = struct.unpack_from("!L", binaryString, 4) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if self.port_no != other.port_no: return False if self.queue_id != other.queue_id: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' outstr += prefix + 'queue_id: ' + str(self.queue_id) + '\n' return outstr class ofp_queue_stats (object): def __init__ (self, **kw): self.port_no = 0 self.queue_id = 0 self.tx_bytes = 0 self.tx_packets = 0 self.tx_errors = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += struct.pack("!H", self.port_no) packed += _PAD2 packed += struct.pack("!LQQQ", self.queue_id, self.tx_bytes, self.tx_packets, self.tx_errors) return packed def unpack (self, binaryString): if (len(binaryString) < 32): return binaryString (self.port_no,) = struct.unpack_from("!H", binaryString, 0) (self.queue_id, self.tx_bytes, self.tx_packets, self.tx_errors) = struct.unpack_from("!LQQQ", binaryString, 4) return binaryString[32:] def __len__ (self): return 32 def __eq__ (self, other): if type(self) != type(other): return False if self.port_no != other.port_no: return False if self.queue_id != other.queue_id: return False if self.tx_bytes != other.tx_bytes: return False if self.tx_packets != other.tx_packets: return False if self.tx_errors != other.tx_errors: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'port_no: ' + str(self.port_no) + '\n' outstr += prefix + 'queue_id: ' + str(self.queue_id) + '\n' outstr += prefix + 'tx_bytes: ' + str(self.tx_bytes) + '\n' outstr += prefix + 'tx_packets: ' + str(self.tx_packets) + '\n' outstr += prefix + 'tx_errors: ' + str(self.tx_errors) + '\n' return outstr ofp_stats_reply_class_to_type_map = { ofp_desc_stats : ofp_stats_types_rev_map['OFPST_DESC'], ofp_flow_stats : ofp_stats_types_rev_map['OFPST_FLOW'], ofp_aggregate_stats : ofp_stats_types_rev_map['OFPST_AGGREGATE'], ofp_table_stats : ofp_stats_types_rev_map['OFPST_TABLE'], ofp_port_stats : ofp_stats_types_rev_map['OFPST_PORT'], ofp_queue_stats : ofp_stats_types_rev_map['OFPST_QUEUE'] } ##3.6 Send Packet Message class ofp_packet_out (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_PACKET_OUT self.buffer_id = -1 self.in_port = OFPP_NONE self.actions = [] self._data = '' # ofp_flow_mod and ofp_packet_out do some special handling of 'actions'... # Allow "action" as a synonym for "actions" if 'action' in kw and 'actions' not in kw: kw['actions'] = kw['action'] del kw['action'] initHelper(self, kw) # Allow use of actions=<a single action> for kw args. if not hasattr(self.actions, '__getitem__'): self.actions = [self.actions] def _set_data(self, data): assert_type("data", data, (packet_base, str)) if data is None: self._data = '' elif isinstance(data, packet_base): self._data = data.pack() else: self._data = data def _get_data(self): return self._data data = property(_get_data, _set_data) def _assert (self): if self.buffer_id != -1 and self.data != '': return "can not have both buffer_id and data set" return True def pack (self, assertstruct=True): if(assertstruct): if self._assert() is not True: raise RuntimeError(self._assert()) actions = b''.join((i.pack(assertstruct) for i in self.actions)) actions_len = len(actions) self.length = 16 + actions_len if self.data is not None: self.length += len(self.data) if self.data is not None: return b''.join((ofp_header.pack(self), struct.pack("!LHH", self.buffer_id & 0xffFFffFF, self.in_port, actions_len), actions, self.data)) else: return b''.join((ofp_header.pack(self), struct.pack("!LHH", self.buffer_id & 0xffFFffFF, self.in_port, actions_len), actions)) def unpack (self, binaryString): if (len(binaryString) < 16): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.buffer_id, self.in_port, actions_len) = struct.unpack_from("!LHH", binaryString, 8) if self.buffer_id == 0xffFFffFF: self.buffer_id = -1 self.actions,offset = _unpack_actions(binaryString, actions_len, 16) self.data = binaryString[offset:self.length] if offset < self.length else None return binaryString[self.length:] def __len__ (self): return 16 + reduce(operator.add, (a.length for a in self.actions), 0) + (len(self.data) if self.data else 0) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.buffer_id != other.buffer_id: return False if self.in_port != other.in_port: return False if self.actions != other.actions: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'buffer_id: ' + str(self.buffer_id) + '\n' outstr += prefix + 'in_port: ' + str(self.in_port) + '\n' outstr += prefix + 'actions_len: ' + str(len(self.actions)) + '\n' outstr += prefix + 'actions: \n' for obj in self.actions: if obj is None: raise RuntimeError("An element of self.actions was None! Bad formatting...") outstr += obj.show(prefix + ' ') return outstr ##3.7 Barrier Message class ofp_barrier_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_BARRIER_REPLY initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): raise RuntimeError("assertstruct failed") packed = "" packed += ofp_header.pack(self) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') return outstr class ofp_barrier_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_BARRIER_REQUEST initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') return outstr #4 Asynchronous Messages class ofp_packet_in (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.in_port = OFPP_NONE self.buffer_id = -1 self.reason = 0 self.data = None initHelper(self, kw) self.header_type = OFPT_PACKET_IN self._total_len = 0 def _set_data(self, data): assert_type("data", data, (packet_base, str)) if data is None: self._data = '' elif isinstance(data, packet_base): self._data = data.pack() else: self._data = data def _get_data(self): return self._data data = property(_get_data, _set_data) def _assert (self): if not isinstance(self.data, str): return (False, "ofp_packet_in: data should be raw byte string, not %s" % str(type(self.data))) return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): raise AssertionError(self._assert()[1]) packed = "" # need to update the self.length field for ofp_header.pack to put the correct value in the packed # array. this sucks. self.length = len(self) self._total_len = len(self) # TODO: Is this correct? packed += ofp_header.pack(self) packed += struct.pack("!LHHBB", self.buffer_id & 0xffFFffFF, self._total_len, self.in_port, self.reason, 0) packed += self.data return packed def unpack (self, binaryString): if (len(binaryString) < 18): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.buffer_id, self._total_len, self.in_port, self.reason, pad) = struct.unpack_from("!LHHBB", binaryString, 8) if self.buffer_id == 0xFFffFFff: self.buffer_id = -1 if (len(binaryString) < self.length): return binaryString self.data = binaryString[18:self.length] return binaryString[self.length:] def __len__ (self): l = 18 l += len(self.data)*1 return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.buffer_id != other.buffer_id: return False if self._total_len != other._total_len: return False if self.in_port != other.in_port: return False if self.reason != other.reason: return False if self.data != other.data: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'buffer_id: ' + str(self.buffer_id) + '\n' outstr += prefix + '_total_len: ' + str(self._total_len) + '\n' outstr += prefix + 'in_port: ' + str(self.in_port) + '\n' outstr += prefix + 'reason: ' + str(self.reason) + '\n' outstr += prefix + 'data: ' + repr(self.data) + '\n' return outstr ofp_packet_in_reason_rev_map = { 'OFPR_NO_MATCH' : 0, 'OFPR_ACTION' : 1, } class ofp_flow_removed (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_FLOW_REMOVED self.match = ofp_match() self.cookie = 0 self.priority = 0 self.reason = 0 self.duration_sec = 0 self.duration_nsec = 0 self.idle_timeout = 0 self.packet_count = 0 self.byte_count = 0 self.length = len(self) initHelper(self, kw) def _assert (self): if(not isinstance(self.match, ofp_match)): return (False, "match is not class ofp_match") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += self.match.pack() packed += struct.pack("!QHB", self.cookie, self.priority, self.reason) packed += _PAD packed += struct.pack("!LLH", self.duration_sec, self.duration_nsec, self.idle_timeout) packed += _PAD2 packed += struct.pack("!QQ", self.packet_count, self.byte_count) return packed def unpack (self, binaryString): if (len(binaryString) < len(self)): return binaryString ofp_header.unpack(self, binaryString[0:]) self.match.unpack(binaryString[8:]) (self.cookie, self.priority, self.reason) = struct.unpack_from("!QHB", binaryString, 8 + len(self.match)) (self.duration_sec, self.duration_nsec, self.idle_timeout) = struct.unpack_from("!LLH", binaryString, 20 + len(self.match)) (self.packet_count, self.byte_count) = struct.unpack_from("!QQ", binaryString, 32 + len(self.match)) return binaryString[len(self):] def __len__ (self): return 48 + len(self.match) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.match != other.match: return False if self.cookie != other.cookie: return False if self.priority != other.priority: return False if self.reason != other.reason: return False if self.duration_sec != other.duration_sec: return False if self.duration_nsec != other.duration_nsec: return False if self.idle_timeout != other.idle_timeout: return False if self.packet_count != other.packet_count: return False if self.byte_count != other.byte_count: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'match: \n' self.match.show(prefix + ' ') outstr += prefix + 'cookie: ' + str(self.cookie) + '\n' outstr += prefix + 'priority: ' + str(self.priority) + '\n' outstr += prefix + 'reason: ' + str(self.reason) + '\n' outstr += prefix + 'duration_sec: ' + str(self.duration_sec) + '\n' outstr += prefix + 'duration_nsec: ' + str(self.duration_nsec) + '\n' outstr += prefix + 'idle_timeout: ' + str(self.idle_timeout) + '\n' outstr += prefix + 'packet_count: ' + str(self.packet_count) + '\n' outstr += prefix + 'byte_count: ' + str(self.byte_count) + '\n' return outstr ofp_flow_removed_reason_rev_map = { 'OFPRR_IDLE_TIMEOUT' : 0, 'OFPRR_HARD_TIMEOUT' : 1, 'OFPRR_DELETE' : 2, } class ofp_port_status (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_PORT_STATUS self.reason = 0 self.desc = ofp_phy_port() self.length = 64 initHelper(self, kw) def _assert (self): if(not isinstance(self.desc, ofp_phy_port)): return (False, "desc is not class ofp_phy_port") return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!B", self.reason) packed += _PAD * 7 # Pad packed += self.desc.pack() return packed def unpack (self, binaryString): if (len(binaryString) < 64): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.reason,) = struct.unpack_from("!B", binaryString, 8) self.desc.unpack(binaryString[16:]) return binaryString[64:] def __len__ (self): return 64 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.reason != other.reason: return False if self.desc != other.desc: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'reason: ' + str(self.reason) + '\n' outstr += prefix + 'desc: \n' self.desc.show(prefix + ' ') return outstr ofp_port_reason_rev_map = { 'OFPPR_ADD' : 0, 'OFPPR_DELETE' : 1, 'OFPPR_MODIFY' : 2, } class ofp_error (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_ERROR self.type = 0 self.code = 0 self.data = [] initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None self.length = len(self) packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.type, self.code) for i in self.data: packed += struct.pack("!B",i) return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.type, self.code) = struct.unpack_from("!HH", binaryString, 8) return binaryString[12:] def __len__ (self): l = 12 l += len(self.data)*1 return l def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.type != other.type: return False if self.code != other.code: return False if self.data != other.data: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') t = self.type c = self.code if t < len(ofp_error_type): n = ofp_error_type_map[t] t = "%s (%i)" % (n, t) n = 'ofp' + n.lower()[5:] + '_code_map' if n in sys.modules[__name__].__dict__: if c in sys.modules[__name__].__dict__[n]: c = "%s (%i)" % (sys.modules[__name__].__dict__[n][c], c) outstr += prefix + 'type: ' + str(t) + '\n' outstr += prefix + 'code: ' + str(c) + '\n' if len(self.data): outstr += prefix + 'data: ' + str(self.data) + '\n' return outstr.strip() ofp_error_type_rev_map = { 'OFPET_HELLO_FAILED' : 0, 'OFPET_BAD_REQUEST' : 1, 'OFPET_BAD_ACTION' : 2, 'OFPET_FLOW_MOD_FAILED' : 3, 'OFPET_PORT_MOD_FAILED' : 4, 'OFPET_QUEUE_OP_FAILED' : 5, } ofp_hello_failed_code_rev_map = { 'OFPHFC_INCOMPATIBLE' : 0, 'OFPHFC_EPERM' : 1, } ofp_bad_request_code_rev_map = { 'OFPBRC_BAD_VERSION' : 0, 'OFPBRC_BAD_TYPE' : 1, 'OFPBRC_BAD_STAT' : 2, 'OFPBRC_BAD_VENDOR' : 3, 'OFPBRC_BAD_SUBTYPE' : 4, 'OFPBRC_EPERM' : 5, 'OFPBRC_BAD_LEN' : 6, 'OFPBRC_BUFFER_EMPTY' : 7, 'OFPBRC_BUFFER_UNKNOWN' : 8, } ofp_bad_action_code_rev_map = { 'OFPBAC_BAD_TYPE' : 0, 'OFPBAC_BAD_LEN' : 1, 'OFPBAC_BAD_VENDOR' : 2, 'OFPBAC_BAD_VENDOR_TYPE' : 3, 'OFPBAC_BAD_OUT_PORT' : 4, 'OFPBAC_BAD_ARGUMENT' : 5, 'OFPBAC_EPERM' : 6, 'OFPBAC_TOO_MANY' : 7, 'OFPBAC_BAD_QUEUE' : 8, } ofp_flow_mod_failed_code_rev_map = { 'OFPFMFC_ALL_TABLES_FULL' : 0, 'OFPFMFC_OVERLAP' : 1, 'OFPFMFC_EPERM' : 2, 'OFPFMFC_BAD_EMERG_TIMEOUT' : 3, 'OFPFMFC_BAD_COMMAND' : 4, 'OFPFMFC_UNSUPPORTED' : 5, } ofp_port_mod_failed_code_rev_map = { 'OFPPMFC_BAD_PORT' : 0, 'OFPPMFC_BAD_HW_ADDR' : 1, } ofp_queue_op_failed_code_rev_map = { 'OFPQOFC_BAD_PORT' : 0, 'OFPQOFC_BAD_QUEUE' : 1, 'OFPQOFC_EPERM' : 2, } #5. Symmetric Messages class ofp_hello (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_HELLO self.length = len(self) initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') return outstr class ofp_echo_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_ECHO_REQUEST self.body = b'' initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = b"" packed += ofp_header.pack(self) packed += self.body return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) # Note that we trust the header to be correct here if len(binaryString) < self.length: return binaryString l = self.length - 8 self.body = binaryString[8:8+l] return binaryString[8 + l:] def __len__ (self): return 8 + len(self.body) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.body != other.body: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'body:\n' + _format_body(self.body, prefix + ' ') + '\n' return outstr class ofp_echo_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_ECHO_REPLY self.body = b'' initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = b"" packed += ofp_header.pack(self) packed += self.body return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) # Note that we trust the header to be correct here if len(binaryString) < self.length: return binaryString l = self.length - 8 self.body = binaryString[8:8+l] return binaryString[8 + l:] def __len__ (self): return 8 + len(self.body) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.body != other.body: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'body:\n' + _format_body(self.body, prefix + ' ') + '\n' return outstr class ofp_vendor_header (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_VENDOR self.vendor = 0 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!L", self.vendor) return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.vendor,) = struct.unpack_from("!L", binaryString, 8) return binaryString[12:] def __len__ (self): return 12 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.vendor != other.vendor: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'vendor: ' + str(self.vendor) + '\n' return outstr class ofp_vendor (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_VENDOR self.vendor = 0 self.data = b'' self.length = 12 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None self.length = 12 + len(self.data) packed = "" packed += ofp_header.pack(self) packed += struct.pack("!L", self.vendor) if hasattr(self.data, "pack"): packed += self.data.pack() else: packed += self.data return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.vendor,) = struct.unpack_from("!L", binaryString, 8) if len(binaryString) < self.length: return binaryString self.data = binaryString[12:self.length] return binaryString[self.length:] def __len__ (self): return 12 + len(self.data) def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.vendor != other.vendor: return False if self.data != other.data: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'vendor: ' + str(self.vendor) + '\n' outstr += prefix + 'data: ' + ( repr(self.data[:8]) if len(self.data) < 8 else "[%d bytes]"%len(self.data) ) + '\n' return outstr class ofp_features_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_FEATURES_REQUEST self.length = 8 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') return outstr class ofp_get_config_request (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_GET_CONFIG_REQUEST initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) return packed def unpack (self, binaryString): if (len(binaryString) < 8): return binaryString ofp_header.unpack(self, binaryString[0:]) return binaryString[8:] def __len__ (self): return 8 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') return outstr class ofp_get_config_reply (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_GET_CONFIG_REPLY self.flags = 0 self.miss_send_len = OFP_DEFAULT_MISS_SEND_LEN self.length = 12 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.flags, self.miss_send_len) return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.flags, self.miss_send_len) = struct.unpack_from("!HH", binaryString, 8) return binaryString[12:] def __len__ (self): return 12 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.flags != other.flags: return False if self.miss_send_len != other.miss_send_len: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'miss_send_len: ' + str(self.miss_send_len) + '\n' return outstr class ofp_set_config (ofp_header): def __init__ (self, **kw): ofp_header.__init__(self) self.header_type = OFPT_SET_CONFIG self.flags = 0 self.miss_send_len = OFP_DEFAULT_MISS_SEND_LEN self.length = 12 initHelper(self, kw) def _assert (self): return (True, None) def pack (self, assertstruct=True): if(assertstruct): if(not self._assert()[0]): return None packed = "" packed += ofp_header.pack(self) packed += struct.pack("!HH", self.flags, self.miss_send_len) return packed def unpack (self, binaryString): if (len(binaryString) < 12): return binaryString ofp_header.unpack(self, binaryString[0:]) (self.flags, self.miss_send_len) = struct.unpack_from("!HH", binaryString, 8) return binaryString[12:] def __len__ (self): return 12 def __eq__ (self, other): if type(self) != type(other): return False if not ofp_header.__eq__(self, other): return False if self.flags != other.flags: return False if self.miss_send_len != other.miss_send_len: return False return True def __ne__ (self, other): return not self.__eq__(other) def show (self, prefix=''): outstr = '' outstr += prefix + 'header: \n' outstr += ofp_header.show(self, prefix + ' ') outstr += prefix + 'flags: ' + str(self.flags) + '\n' outstr += prefix + 'miss_send_len: ' + str(self.miss_send_len) + '\n' return outstr ofp_port_rev_map = { 'OFPP_MAX' : 65280, 'OFPP_IN_PORT' : 65528, 'OFPP_TABLE' : 65529, 'OFPP_NORMAL' : 65530, 'OFPP_FLOOD' : 65531, 'OFPP_ALL' : 65532, 'OFPP_CONTROLLER' : 65533, 'OFPP_LOCAL' : 65534, 'OFPP_NONE' : 65535, } ofp_type_rev_map = { 'OFPT_HELLO' : 0, 'OFPT_ERROR' : 1, 'OFPT_ECHO_REQUEST' : 2, 'OFPT_ECHO_REPLY' : 3, 'OFPT_VENDOR' : 4, 'OFPT_FEATURES_REQUEST' : 5, 'OFPT_FEATURES_REPLY' : 6, 'OFPT_GET_CONFIG_REQUEST' : 7, 'OFPT_GET_CONFIG_REPLY' : 8, 'OFPT_SET_CONFIG' : 9, 'OFPT_PACKET_IN' : 10, 'OFPT_FLOW_REMOVED' : 11, 'OFPT_PORT_STATUS' : 12, 'OFPT_PACKET_OUT' : 13, 'OFPT_FLOW_MOD' : 14, 'OFPT_PORT_MOD' : 15, 'OFPT_STATS_REQUEST' : 16, 'OFPT_STATS_REPLY' : 17, 'OFPT_BARRIER_REQUEST' : 18, 'OFPT_BARRIER_REPLY' : 19, 'OFPT_QUEUE_GET_CONFIG_REQUEST' : 20, 'OFPT_QUEUE_GET_CONFIG_REPLY' : 21, } # Table that maps an action type to a callable that creates that type # (This is filled in by _init after the globals have been created) _action_map = {} def _unpack_actions (b, length, offset=0): """ Parses actions from a buffer b is a buffer (bytes) offset, if specified is where in b to start decoding returns ([Actions], next_offset) """ if (len(b) - offset) < length: return ([], offset) actions = [] end = length + offset while offset < end: (t,l) = struct.unpack_from("!HH", b, offset) if (len(b) - offset) < l: return ([], offset) a = _action_map.get(t) if a is None: # Use generic action header for unknown type a = ofp_action_header() else: a = a() a.unpack(b[offset:offset+l]) assert len(a) == l actions.append(a) offset += l return (actions, offset) def _init (): def formatMap (name, m): o = name + " = {\n" vk = sorted([(v,k) for k,v in m.iteritems()]) maxlen = 2 + len(reduce(lambda a,b: a if len(a)>len(b) else b, (v for k,v in vk))) fstr = " %-" + str(maxlen) + "s : %s,\n" for v,k in vk: o += fstr % ("'" + k + "'",v) o += "}" return o """ maps = [] for k,v in globals().iteritems(): if k.startswith("ofp_") and k.endswith("_map") and type(v) == dict: maps.append((k,v)) for name,m in maps: rev = {} name = name[:-4] names = globals()[name] for n in names: rev[n] = globals()[n] globals()[name + '_rev_map'] = rev print formatMap(name + "_rev_map", rev) return """ maps = [] for k,v in globals().iteritems(): if k.startswith("ofp_") and k.endswith("_rev_map") and type(v) == dict: maps.append((k[:-8],v)) for name,m in maps: # Try to generate forward maps forward = dict(((v,k) for k,v in m.iteritems())) if len(forward) == len(m): globals()[name + "_map"] = forward else: print name + "_rev_map is not a map" # Try to generate lists v = m.values() v.sort() if v[-1] != len(v)-1: # Allow ones where the last value is a special value (e.g., VENDOR) del v[-1] if len(v) > 0 and v[0] == 0 and v[-1] == len(v)-1: globals()[name] = v # Generate gobals for k,v in m.iteritems(): globals()[k] = v _init() # Fill in the action-to-class table #TODO: Use the factory functions? _action_map.update({ #TODO: special type for OFPAT_STRIP_VLAN? OFPAT_OUTPUT : ofp_action_output, OFPAT_SET_VLAN_VID : ofp_action_vlan_vid, OFPAT_SET_VLAN_PCP : ofp_action_vlan_pcp, OFPAT_SET_DL_SRC : ofp_action_dl_addr, OFPAT_SET_DL_DST : ofp_action_dl_addr, OFPAT_SET_NW_SRC : ofp_action_nw_addr, OFPAT_SET_NW_DST : ofp_action_nw_addr, OFPAT_SET_NW_TOS : ofp_action_nw_tos, OFPAT_SET_TP_SRC : ofp_action_tp_port, OFPAT_SET_TP_DST : ofp_action_tp_port, OFPAT_ENQUEUE : ofp_action_enqueue, OFPAT_PUSH_MPLS : ofp_action_push_mpls, OFPAT_POP_MPLS : ofp_action_pop_mpls, OFPAT_SET_MPLS_LABEL : ofp_action_mpls_label, OFPAT_SET_MPLS_TC : ofp_action_mpls_tc, OFPAT_SET_MPLS_TTL : ofp_action_mpls_ttl, OFPAT_DEC_MPLS_TTL : ofp_action_mpls_dec_ttl, OFPAT_RESUBMIT : ofp_action_resubmit }) # Values from macro definitions OFP_FLOW_PERMANENT = 0 OFP_DL_TYPE_ETH2_CUTOFF = 0x0600 DESC_STR_LEN = 256 OFPFW_ICMP_CODE = OFPFW_TP_DST OFPQ_MIN_RATE_UNCFG = 0xffff OFP_VERSION = 0x01 OFP_MAX_TABLE_NAME_LEN = 32 OFP_DL_TYPE_NOT_ETH_TYPE = 0x05ff OFP_DEFAULT_MISS_SEND_LEN = 128 OFP_MAX_PORT_NAME_LEN = 16 OFP_SSL_PORT = 6633 OFPFW_ICMP_TYPE = OFPFW_TP_SRC OFP_TCP_PORT = 6633 SERIAL_NUM_LEN = 32 OFP_DEFAULT_PRIORITY = 0x8000 OFP_ETH_ALEN = 6 OFP_VLAN_NONE = 0xffff OFPQ_ALL = 0xffffffff # Basic structure size definitions. OFP_ACTION_DL_ADDR_BYTES = 16 OFP_ACTION_ENQUEUE_BYTES = 16 OFP_ACTION_HEADER_BYTES = 8 OFP_ACTION_NW_ADDR_BYTES = 8 OFP_ACTION_NW_TOS_BYTES = 8 OFP_ACTION_OUTPUT_BYTES = 8 OFP_ACTION_TP_PORT_BYTES = 8 OFP_ACTION_VENDOR_HEADER_BYTES = 8 OFP_ACTION_VLAN_PCP_BYTES = 8 OFP_ACTION_VLAN_VID_BYTES = 8 OFP_AGGREGATE_STATS_REPLY_BYTES = 24 OFP_AGGREGATE_STATS_REQUEST_BYTES = 44 OFP_DESC_STATS_BYTES = 1056 OFP_ERROR_MSG_BYTES = 12 OFP_FLOW_MOD_BYTES = 72 OFP_FLOW_REMOVED_BYTES = 88 OFP_FLOW_STATS_BYTES = 88 OFP_FLOW_STATS_REQUEST_BYTES = 44 OFP_HEADER_BYTES = 8 OFP_HELLO_BYTES = 8 OFP_MATCH_BYTES = 40 OFP_PACKET_IN_BYTES = 18 OFP_PACKET_OUT_BYTES = 16 OFP_PACKET_QUEUE_BYTES = 8 OFP_PHY_PORT_BYTES = 48 OFP_PORT_MOD_BYTES = 32 OFP_PORT_STATS_BYTES = 104 OFP_PORT_STATS_REQUEST_BYTES = 8 OFP_PORT_STATUS_BYTES = 64 OFP_QUEUE_GET_CONFIG_REPLY_BYTES = 16 OFP_QUEUE_GET_CONFIG_REQUEST_BYTES = 12 OFP_QUEUE_PROP_HEADER_BYTES = 8 OFP_QUEUE_PROP_MIN_RATE_BYTES = 16 OFP_QUEUE_STATS_BYTES = 32 OFP_QUEUE_STATS_REQUEST_BYTES = 8 OFP_STATS_REPLY_BYTES = 12 OFP_STATS_REQUEST_BYTES = 12 OFP_SWITCH_CONFIG_BYTES = 12 OFP_SWITCH_FEATURES_BYTES = 32 OFP_TABLE_STATS_BYTES = 64 OFP_VENDOR_HEADER_BYTES = 12 NO_BUFFER = 4294967295 ofp_match_data = { # 'wildcards' : (0, 0), 'in_port' : (0, OFPFW_IN_PORT), 'dl_src' : (EMPTY_ETH, OFPFW_DL_SRC), 'dl_dst' : (EMPTY_ETH, OFPFW_DL_DST), 'dl_vlan' : (0, OFPFW_DL_VLAN), 'dl_vlan_pcp' : (0, OFPFW_DL_VLAN_PCP), #'pad1' : (_PAD, 0), 'dl_type' : (0, OFPFW_DL_TYPE), 'nw_tos' : (0, OFPFW_NW_TOS), 'nw_proto' : (0, OFPFW_NW_PROTO), #'pad2' : (_PAD2, 0), 'nw_src' : (0, OFPFW_NW_SRC_ALL), 'nw_dst' : (0, OFPFW_NW_DST_ALL), 'tp_src' : (0, OFPFW_TP_SRC), 'tp_dst' : (0, OFPFW_TP_DST), # 'mpls_label': (0, OFPFW_MPLS_LABEL), # 'mpls_tc': (0, OFPFW_MPLS_TC), }
gpl-3.0
HolgerPeters/scikit-learn
sklearn/ensemble/gradient_boosting.py
5
73159
"""Gradient Boosted Regression Trees This module contains methods for fitting gradient boosted regression trees for both classification and regression. The module structure is the following: - The ``BaseGradientBoosting`` base class implements a common ``fit`` method for all the estimators in the module. Regression and classification only differ in the concrete ``LossFunction`` used. - ``GradientBoostingClassifier`` implements gradient boosting for classification problems. - ``GradientBoostingRegressor`` implements gradient boosting for regression problems. """ # Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti, # Arnaud Joly, Jacob Schreiber # License: BSD 3 clause from __future__ import print_function from __future__ import division from abc import ABCMeta from abc import abstractmethod from .base import BaseEnsemble from ..base import BaseEstimator from ..base import ClassifierMixin from ..base import RegressorMixin from ..externals import six from ._gradient_boosting import predict_stages from ._gradient_boosting import predict_stage from ._gradient_boosting import _random_sample_mask import numbers import numpy as np from scipy import stats from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import issparse from time import time from ..tree.tree import DecisionTreeRegressor from ..tree._tree import DTYPE from ..tree._tree import TREE_LEAF from ..utils import check_random_state from ..utils import check_array from ..utils import check_X_y from ..utils import column_or_1d from ..utils import check_consistent_length from ..utils.extmath import logsumexp from ..utils.fixes import expit from ..utils.fixes import bincount from ..utils import deprecated from ..utils.stats import _weighted_percentile from ..utils.validation import check_is_fitted from ..utils.multiclass import check_classification_targets from ..exceptions import NotFittedError class QuantileEstimator(BaseEstimator): """An estimator predicting the alpha-quantile of the training targets.""" def __init__(self, alpha=0.9): if not 0 < alpha < 1.0: raise ValueError("`alpha` must be in (0, 1.0) but was %r" % alpha) self.alpha = alpha def fit(self, X, y, sample_weight=None): if sample_weight is None: self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0) else: self.quantile = _weighted_percentile(y, sample_weight, self.alpha * 100.0) def predict(self, X): check_is_fitted(self, 'quantile') y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.quantile) return y class MeanEstimator(BaseEstimator): """An estimator predicting the mean of the training targets.""" def fit(self, X, y, sample_weight=None): if sample_weight is None: self.mean = np.mean(y) else: self.mean = np.average(y, weights=sample_weight) def predict(self, X): check_is_fitted(self, 'mean') y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.mean) return y class LogOddsEstimator(BaseEstimator): """An estimator predicting the log odds ratio.""" scale = 1.0 def fit(self, X, y, sample_weight=None): # pre-cond: pos, neg are encoded as 1, 0 if sample_weight is None: pos = np.sum(y) neg = y.shape[0] - pos else: pos = np.sum(sample_weight * y) neg = np.sum(sample_weight * (1 - y)) if neg == 0 or pos == 0: raise ValueError('y contains non binary labels.') self.prior = self.scale * np.log(pos / neg) def predict(self, X): check_is_fitted(self, 'prior') y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.prior) return y class ScaledLogOddsEstimator(LogOddsEstimator): """Log odds ratio scaled by 0.5 -- for exponential loss. """ scale = 0.5 class PriorProbabilityEstimator(BaseEstimator): """An estimator predicting the probability of each class in the training data. """ def fit(self, X, y, sample_weight=None): if sample_weight is None: sample_weight = np.ones_like(y, dtype=np.float64) class_counts = bincount(y, weights=sample_weight) self.priors = class_counts / class_counts.sum() def predict(self, X): check_is_fitted(self, 'priors') y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64) y[:] = self.priors return y class ZeroEstimator(BaseEstimator): """An estimator that simply predicts zero. """ def fit(self, X, y, sample_weight=None): if np.issubdtype(y.dtype, int): # classification self.n_classes = np.unique(y).shape[0] if self.n_classes == 2: self.n_classes = 1 else: # regression self.n_classes = 1 def predict(self, X): check_is_fitted(self, 'n_classes') y = np.empty((X.shape[0], self.n_classes), dtype=np.float64) y.fill(0.0) return y class LossFunction(six.with_metaclass(ABCMeta, object)): """Abstract base class for various loss functions. Attributes ---------- K : int The number of regression trees to be induced; 1 for regression and binary classification; ``n_classes`` for multi-class classification. """ is_multi_class = False def __init__(self, n_classes): self.K = n_classes def init_estimator(self): """Default ``init`` estimator for loss function. """ raise NotImplementedError() @abstractmethod def __call__(self, y, pred, sample_weight=None): """Compute the loss of prediction ``pred`` and ``y``. """ @abstractmethod def negative_gradient(self, y, y_pred, **kargs): """Compute the negative gradient. Parameters --------- y : np.ndarray, shape=(n,) The target labels. y_pred : np.ndarray, shape=(n,): The predictions. """ def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Update the terminal regions (=leaves) of the given tree and updates the current predictions of the model. Traverses tree and invokes template method `_update_terminal_region`. Parameters ---------- tree : tree.Tree The tree object. X : ndarray, shape=(n, m) The data array. y : ndarray, shape=(n,) The target labels. residual : ndarray, shape=(n,) The residuals (usually the negative gradient). y_pred : ndarray, shape=(n,) The predictions. sample_weight : ndarray, shape=(n,) The weight of each sample. sample_mask : ndarray, shape=(n,) The sample mask to be used. learning_rate : float, default=0.1 learning rate shrinks the contribution of each tree by ``learning_rate``. k : int, default 0 The index of the estimator being updated. """ # compute leaf for each sample in ``X``. terminal_regions = tree.apply(X) # mask all which are not in sample mask. masked_terminal_regions = terminal_regions.copy() masked_terminal_regions[~sample_mask] = -1 # update each leaf (= perform line search) for leaf in np.where(tree.children_left == TREE_LEAF)[0]: self._update_terminal_region(tree, masked_terminal_regions, leaf, X, y, residual, y_pred[:, k], sample_weight) # update predictions (both in-bag and out-of-bag) y_pred[:, k] += (learning_rate * tree.value[:, 0, 0].take(terminal_regions, axis=0)) @abstractmethod def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): """Template method for updating terminal regions (=leaves). """ class RegressionLossFunction(six.with_metaclass(ABCMeta, LossFunction)): """Base class for regression loss functions. """ def __init__(self, n_classes): if n_classes != 1: raise ValueError("``n_classes`` must be 1 for regression but " "was %r" % n_classes) super(RegressionLossFunction, self).__init__(n_classes) class LeastSquaresError(RegressionLossFunction): """Loss function for least squares (LS) estimation. Terminal regions need not to be updated for least squares. """ def init_estimator(self): return MeanEstimator() def __call__(self, y, pred, sample_weight=None): if sample_weight is None: return np.mean((y - pred.ravel()) ** 2.0) else: return (1.0 / sample_weight.sum() * np.sum(sample_weight * ((y - pred.ravel()) ** 2.0))) def negative_gradient(self, y, pred, **kargs): return y - pred.ravel() def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # update predictions y_pred[:, k] += learning_rate * tree.predict(X).ravel() def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): pass class LeastAbsoluteError(RegressionLossFunction): """Loss function for least absolute deviation (LAD) regression. """ def init_estimator(self): return QuantileEstimator(alpha=0.5) def __call__(self, y, pred, sample_weight=None): if sample_weight is None: return np.abs(y - pred.ravel()).mean() else: return (1.0 / sample_weight.sum() * np.sum(sample_weight * np.abs(y - pred.ravel()))) def negative_gradient(self, y, pred, **kargs): """1.0 if y - pred > 0.0 else -1.0""" pred = pred.ravel() return 2.0 * (y - pred > 0.0) - 1.0 def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): """LAD updates terminal regions to median estimates. """ terminal_region = np.where(terminal_regions == leaf)[0] sample_weight = sample_weight.take(terminal_region, axis=0) diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0) tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50) class HuberLossFunction(RegressionLossFunction): """Huber loss function for robust regression. M-Regression proposed in Friedman 2001. References ---------- J. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. """ def __init__(self, n_classes, alpha=0.9): super(HuberLossFunction, self).__init__(n_classes) self.alpha = alpha self.gamma = None def init_estimator(self): return QuantileEstimator(alpha=0.5) def __call__(self, y, pred, sample_weight=None): pred = pred.ravel() diff = y - pred gamma = self.gamma if gamma is None: if sample_weight is None: gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100) else: gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100) gamma_mask = np.abs(diff) <= gamma if sample_weight is None: sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0) lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0)) loss = (sq_loss + lin_loss) / y.shape[0] else: sq_loss = np.sum(0.5 * sample_weight[gamma_mask] * diff[gamma_mask] ** 2.0) lin_loss = np.sum(gamma * sample_weight[~gamma_mask] * (np.abs(diff[~gamma_mask]) - gamma / 2.0)) loss = (sq_loss + lin_loss) / sample_weight.sum() return loss def negative_gradient(self, y, pred, sample_weight=None, **kargs): pred = pred.ravel() diff = y - pred if sample_weight is None: gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100) else: gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100) gamma_mask = np.abs(diff) <= gamma residual = np.zeros((y.shape[0],), dtype=np.float64) residual[gamma_mask] = diff[gamma_mask] residual[~gamma_mask] = gamma * np.sign(diff[~gamma_mask]) self.gamma = gamma return residual def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): terminal_region = np.where(terminal_regions == leaf)[0] sample_weight = sample_weight.take(terminal_region, axis=0) gamma = self.gamma diff = (y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)) median = _weighted_percentile(diff, sample_weight, percentile=50) diff_minus_median = diff - median tree.value[leaf, 0] = median + np.mean( np.sign(diff_minus_median) * np.minimum(np.abs(diff_minus_median), gamma)) class QuantileLossFunction(RegressionLossFunction): """Loss function for quantile regression. Quantile regression allows to estimate the percentiles of the conditional distribution of the target. """ def __init__(self, n_classes, alpha=0.9): super(QuantileLossFunction, self).__init__(n_classes) assert 0 < alpha < 1.0 self.alpha = alpha self.percentile = alpha * 100.0 def init_estimator(self): return QuantileEstimator(self.alpha) def __call__(self, y, pred, sample_weight=None): pred = pred.ravel() diff = y - pred alpha = self.alpha mask = y > pred if sample_weight is None: loss = (alpha * diff[mask].sum() - (1.0 - alpha) * diff[~mask].sum()) / y.shape[0] else: loss = ((alpha * np.sum(sample_weight[mask] * diff[mask]) - (1.0 - alpha) * np.sum(sample_weight[~mask] * diff[~mask])) / sample_weight.sum()) return loss def negative_gradient(self, y, pred, **kargs): alpha = self.alpha pred = pred.ravel() mask = y > pred return (alpha * mask) - ((1.0 - alpha) * ~mask) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): terminal_region = np.where(terminal_regions == leaf)[0] diff = (y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)) sample_weight = sample_weight.take(terminal_region, axis=0) val = _weighted_percentile(diff, sample_weight, self.percentile) tree.value[leaf, 0] = val class ClassificationLossFunction(six.with_metaclass(ABCMeta, LossFunction)): """Base class for classification loss functions. """ def _score_to_proba(self, score): """Template method to convert scores to probabilities. the does not support probabilites raises AttributeError. """ raise TypeError('%s does not support predict_proba' % type(self).__name__) @abstractmethod def _score_to_decision(self, score): """Template method to convert scores to decisions. Returns int arrays. """ class BinomialDeviance(ClassificationLossFunction): """Binomial deviance loss function for binary classification. Binary classification is a special case; here, we only need to fit one tree instead of ``n_classes`` trees. """ def __init__(self, n_classes): if n_classes != 2: raise ValueError("{0:s} requires 2 classes.".format( self.__class__.__name__)) # we only need to fit one tree for binary clf. super(BinomialDeviance, self).__init__(1) def init_estimator(self): return LogOddsEstimator() def __call__(self, y, pred, sample_weight=None): """Compute the deviance (= 2 * negative log-likelihood). """ # logaddexp(0, v) == log(1.0 + exp(v)) pred = pred.ravel() if sample_weight is None: return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred)) else: return (-2.0 / sample_weight.sum() * np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred)))) def negative_gradient(self, y, pred, **kargs): """Compute the residual (= negative gradient). """ return y - expit(pred.ravel()) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): """Make a single Newton-Raphson step. our node estimate is given by: sum(w * (y - prob)) / sum(w * prob * (1 - prob)) we take advantage that: y - prob = residual """ terminal_region = np.where(terminal_regions == leaf)[0] residual = residual.take(terminal_region, axis=0) y = y.take(terminal_region, axis=0) sample_weight = sample_weight.take(terminal_region, axis=0) numerator = np.sum(sample_weight * residual) denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual)) if denominator == 0.0: tree.value[leaf, 0, 0] = 0.0 else: tree.value[leaf, 0, 0] = numerator / denominator def _score_to_proba(self, score): proba = np.ones((score.shape[0], 2), dtype=np.float64) proba[:, 1] = expit(score.ravel()) proba[:, 0] -= proba[:, 1] return proba def _score_to_decision(self, score): proba = self._score_to_proba(score) return np.argmax(proba, axis=1) class MultinomialDeviance(ClassificationLossFunction): """Multinomial deviance loss function for multi-class classification. For multi-class classification we need to fit ``n_classes`` trees at each stage. """ is_multi_class = True def __init__(self, n_classes): if n_classes < 3: raise ValueError("{0:s} requires more than 2 classes.".format( self.__class__.__name__)) super(MultinomialDeviance, self).__init__(n_classes) def init_estimator(self): return PriorProbabilityEstimator() def __call__(self, y, pred, sample_weight=None): # create one-hot label encoding Y = np.zeros((y.shape[0], self.K), dtype=np.float64) for k in range(self.K): Y[:, k] = y == k if sample_weight is None: return np.sum(-1 * (Y * pred).sum(axis=1) + logsumexp(pred, axis=1)) else: return np.sum(-1 * sample_weight * (Y * pred).sum(axis=1) + logsumexp(pred, axis=1)) def negative_gradient(self, y, pred, k=0, **kwargs): """Compute negative gradient for the ``k``-th class. """ return y - np.nan_to_num(np.exp(pred[:, k] - logsumexp(pred, axis=1))) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): """Make a single Newton-Raphson step. """ terminal_region = np.where(terminal_regions == leaf)[0] residual = residual.take(terminal_region, axis=0) y = y.take(terminal_region, axis=0) sample_weight = sample_weight.take(terminal_region, axis=0) numerator = np.sum(sample_weight * residual) numerator *= (self.K - 1) / self.K denominator = np.sum(sample_weight * (y - residual) * (1.0 - y + residual)) if denominator == 0.0: tree.value[leaf, 0, 0] = 0.0 else: tree.value[leaf, 0, 0] = numerator / denominator def _score_to_proba(self, score): return np.nan_to_num( np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis]))) def _score_to_decision(self, score): proba = self._score_to_proba(score) return np.argmax(proba, axis=1) class ExponentialLoss(ClassificationLossFunction): """Exponential loss function for binary classification. Same loss as AdaBoost. References ---------- Greg Ridgeway, Generalized Boosted Models: A guide to the gbm package, 2007 """ def __init__(self, n_classes): if n_classes != 2: raise ValueError("{0:s} requires 2 classes.".format( self.__class__.__name__)) # we only need to fit one tree for binary clf. super(ExponentialLoss, self).__init__(1) def init_estimator(self): return ScaledLogOddsEstimator() def __call__(self, y, pred, sample_weight=None): pred = pred.ravel() if sample_weight is None: return np.mean(np.exp(-(2. * y - 1.) * pred)) else: return (1.0 / sample_weight.sum() * np.sum(sample_weight * np.exp(-(2 * y - 1) * pred))) def negative_gradient(self, y, pred, **kargs): y_ = -(2. * y - 1.) return y_ * np.exp(y_ * pred.ravel()) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): terminal_region = np.where(terminal_regions == leaf)[0] pred = pred.take(terminal_region, axis=0) y = y.take(terminal_region, axis=0) sample_weight = sample_weight.take(terminal_region, axis=0) y_ = 2. * y - 1. numerator = np.sum(y_ * sample_weight * np.exp(-y_ * pred)) denominator = np.sum(sample_weight * np.exp(-y_ * pred)) if denominator == 0.0: tree.value[leaf, 0, 0] = 0.0 else: tree.value[leaf, 0, 0] = numerator / denominator def _score_to_proba(self, score): proba = np.ones((score.shape[0], 2), dtype=np.float64) proba[:, 1] = expit(2.0 * score.ravel()) proba[:, 0] -= proba[:, 1] return proba def _score_to_decision(self, score): return (score.ravel() >= 0.0).astype(np.int) LOSS_FUNCTIONS = {'ls': LeastSquaresError, 'lad': LeastAbsoluteError, 'huber': HuberLossFunction, 'quantile': QuantileLossFunction, 'deviance': None, # for both, multinomial and binomial 'exponential': ExponentialLoss, } INIT_ESTIMATORS = {'zero': ZeroEstimator} class VerboseReporter(object): """Reports verbose output to stdout. If ``verbose==1`` output is printed once in a while (when iteration mod verbose_mod is zero).; if larger than 1 then output is printed for each update. """ def __init__(self, verbose): self.verbose = verbose def init(self, est, begin_at_stage=0): # header fields and line format str header_fields = ['Iter', 'Train Loss'] verbose_fmt = ['{iter:>10d}', '{train_score:>16.4f}'] # do oob? if est.subsample < 1: header_fields.append('OOB Improve') verbose_fmt.append('{oob_impr:>16.4f}') header_fields.append('Remaining Time') verbose_fmt.append('{remaining_time:>16s}') # print the header line print(('%10s ' + '%16s ' * (len(header_fields) - 1)) % tuple(header_fields)) self.verbose_fmt = ' '.join(verbose_fmt) # plot verbose info each time i % verbose_mod == 0 self.verbose_mod = 1 self.start_time = time() self.begin_at_stage = begin_at_stage def update(self, j, est): """Update reporter with new iteration. """ do_oob = est.subsample < 1 # we need to take into account if we fit additional estimators. i = j - self.begin_at_stage # iteration relative to the start iter if (i + 1) % self.verbose_mod == 0: oob_impr = est.oob_improvement_[j] if do_oob else 0 remaining_time = ((est.n_estimators - (j + 1)) * (time() - self.start_time) / float(i + 1)) if remaining_time > 60: remaining_time = '{0:.2f}m'.format(remaining_time / 60.0) else: remaining_time = '{0:.2f}s'.format(remaining_time) print(self.verbose_fmt.format(iter=j + 1, train_score=est.train_score_[j], oob_impr=oob_impr, remaining_time=remaining_time)) if self.verbose == 1 and ((i + 1) // (self.verbose_mod * 10) > 0): # adjust verbose frequency (powers of 10) self.verbose_mod *= 10 class BaseGradientBoosting(six.with_metaclass(ABCMeta, BaseEnsemble)): """Abstract base class for Gradient Boosting. """ @abstractmethod def __init__(self, loss, learning_rate, n_estimators, criterion, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_depth, min_impurity_split, init, subsample, max_features, random_state, alpha=0.9, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto'): self.n_estimators = n_estimators self.learning_rate = learning_rate self.loss = loss self.criterion = criterion self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.subsample = subsample self.max_features = max_features self.max_depth = max_depth self.min_impurity_split = min_impurity_split self.init = init self.random_state = random_state self.alpha = alpha self.verbose = verbose self.max_leaf_nodes = max_leaf_nodes self.warm_start = warm_start self.presort = presort def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, random_state, X_idx_sorted, X_csc=None, X_csr=None): """Fit another stage of ``n_classes_`` trees to the boosting model. """ assert sample_mask.dtype == np.bool loss = self.loss_ original_y = y for k in range(loss.K): if loss.is_multi_class: y = np.array(original_y == k, dtype=np.float64) residual = loss.negative_gradient(y, y_pred, k=k, sample_weight=sample_weight) # induce regression tree on residuals tree = DecisionTreeRegressor( criterion=self.criterion, splitter='best', max_depth=self.max_depth, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf, min_weight_fraction_leaf=self.min_weight_fraction_leaf, min_impurity_split=self.min_impurity_split, max_features=self.max_features, max_leaf_nodes=self.max_leaf_nodes, random_state=random_state, presort=self.presort) if self.subsample < 1.0: # no inplace multiplication! sample_weight = sample_weight * sample_mask.astype(np.float64) if X_csc is not None: tree.fit(X_csc, residual, sample_weight=sample_weight, check_input=False, X_idx_sorted=X_idx_sorted) else: tree.fit(X, residual, sample_weight=sample_weight, check_input=False, X_idx_sorted=X_idx_sorted) # update tree leaves if X_csr is not None: loss.update_terminal_regions(tree.tree_, X_csr, y, residual, y_pred, sample_weight, sample_mask, self.learning_rate, k=k) else: loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred, sample_weight, sample_mask, self.learning_rate, k=k) # add tree to ensemble self.estimators_[i, k] = tree return y_pred def _check_params(self): """Check validity of parameters and raise ValueError if not valid. """ if self.n_estimators <= 0: raise ValueError("n_estimators must be greater than 0 but " "was %r" % self.n_estimators) if self.learning_rate <= 0.0: raise ValueError("learning_rate must be greater than 0 but " "was %r" % self.learning_rate) if (self.loss not in self._SUPPORTED_LOSS or self.loss not in LOSS_FUNCTIONS): raise ValueError("Loss '{0:s}' not supported. ".format(self.loss)) if self.loss == 'deviance': loss_class = (MultinomialDeviance if len(self.classes_) > 2 else BinomialDeviance) else: loss_class = LOSS_FUNCTIONS[self.loss] if self.loss in ('huber', 'quantile'): self.loss_ = loss_class(self.n_classes_, self.alpha) else: self.loss_ = loss_class(self.n_classes_) if not (0.0 < self.subsample <= 1.0): raise ValueError("subsample must be in (0,1] but " "was %r" % self.subsample) if self.init is not None: if isinstance(self.init, six.string_types): if self.init not in INIT_ESTIMATORS: raise ValueError('init="%s" is not supported' % self.init) else: if (not hasattr(self.init, 'fit') or not hasattr(self.init, 'predict')): raise ValueError("init=%r must be valid BaseEstimator " "and support both fit and " "predict" % self.init) if not (0.0 < self.alpha < 1.0): raise ValueError("alpha must be in (0.0, 1.0) but " "was %r" % self.alpha) if isinstance(self.max_features, six.string_types): if self.max_features == "auto": # if is_classification if self.n_classes_ > 1: max_features = max(1, int(np.sqrt(self.n_features_))) else: # is regression max_features = self.n_features_ elif self.max_features == "sqrt": max_features = max(1, int(np.sqrt(self.n_features_))) elif self.max_features == "log2": max_features = max(1, int(np.log2(self.n_features_))) else: raise ValueError("Invalid value for max_features: %r. " "Allowed string values are 'auto', 'sqrt' " "or 'log2'." % self.max_features) elif self.max_features is None: max_features = self.n_features_ elif isinstance(self.max_features, (numbers.Integral, np.integer)): max_features = self.max_features else: # float if 0. < self.max_features <= 1.: max_features = max(int(self.max_features * self.n_features_), 1) else: raise ValueError("max_features must be in (0, n_features]") self.max_features_ = max_features def _init_state(self): """Initialize model state and allocate model state data structures. """ if self.init is None: self.init_ = self.loss_.init_estimator() elif isinstance(self.init, six.string_types): self.init_ = INIT_ESTIMATORS[self.init]() else: self.init_ = self.init self.estimators_ = np.empty((self.n_estimators, self.loss_.K), dtype=np.object) self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64) # do oob? if self.subsample < 1.0: self.oob_improvement_ = np.zeros((self.n_estimators), dtype=np.float64) def _clear_state(self): """Clear the state of the gradient boosting model. """ if hasattr(self, 'estimators_'): self.estimators_ = np.empty((0, 0), dtype=np.object) if hasattr(self, 'train_score_'): del self.train_score_ if hasattr(self, 'oob_improvement_'): del self.oob_improvement_ if hasattr(self, 'init_'): del self.init_ def _resize_state(self): """Add additional ``n_estimators`` entries to all attributes. """ # self.n_estimators is the number of additional est to fit total_n_estimators = self.n_estimators if total_n_estimators < self.estimators_.shape[0]: raise ValueError('resize with smaller n_estimators %d < %d' % (total_n_estimators, self.estimators_[0])) self.estimators_.resize((total_n_estimators, self.loss_.K)) self.train_score_.resize(total_n_estimators) if (self.subsample < 1 or hasattr(self, 'oob_improvement_')): # if do oob resize arrays or create new if not available if hasattr(self, 'oob_improvement_'): self.oob_improvement_.resize(total_n_estimators) else: self.oob_improvement_ = np.zeros((total_n_estimators,), dtype=np.float64) def _is_initialized(self): return len(getattr(self, 'estimators_', [])) > 0 def _check_initialized(self): """Check that the estimator is initialized, raising an error if not.""" check_is_fitted(self, 'estimators_') @property @deprecated("Attribute n_features was deprecated in version 0.19 and " "will be removed in 0.21.") def n_features(self): return self.n_features_ def fit(self, X, y, sample_weight=None, monitor=None): """Fit the gradient boosting model. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target values (integers in classification, real numbers in regression) For classification, labels must correspond to classes. sample_weight : array-like, shape = [n_samples] or None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. monitor : callable, optional The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of ``_fit_stages`` as keyword arguments ``callable(i, self, locals())``. If the callable returns ``True`` the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns ------- self : object Returns self. """ # if not warmstart - clear the estimator state if not self.warm_start: self._clear_state() # Check input X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=DTYPE) n_samples, self.n_features_ = X.shape if sample_weight is None: sample_weight = np.ones(n_samples, dtype=np.float32) else: sample_weight = column_or_1d(sample_weight, warn=True) check_consistent_length(X, y, sample_weight) y = self._validate_y(y) random_state = check_random_state(self.random_state) self._check_params() if not self._is_initialized(): # init state self._init_state() # fit initial model - FIXME make sample_weight optional self.init_.fit(X, y, sample_weight) # init predictions y_pred = self.init_.predict(X) begin_at_stage = 0 else: # add more estimators to fitted model # invariant: warm_start = True if self.n_estimators < self.estimators_.shape[0]: raise ValueError('n_estimators=%d must be larger or equal to ' 'estimators_.shape[0]=%d when ' 'warm_start==True' % (self.n_estimators, self.estimators_.shape[0])) begin_at_stage = self.estimators_.shape[0] y_pred = self._decision_function(X) self._resize_state() X_idx_sorted = None presort = self.presort # Allow presort to be 'auto', which means True if the dataset is dense, # otherwise it will be False. if presort == 'auto' and issparse(X): presort = False elif presort == 'auto': presort = True if presort == True: if issparse(X): raise ValueError("Presorting is not supported for sparse matrices.") else: X_idx_sorted = np.asfortranarray(np.argsort(X, axis=0), dtype=np.int32) # fit the boosting stages n_stages = self._fit_stages(X, y, y_pred, sample_weight, random_state, begin_at_stage, monitor, X_idx_sorted) # change shape of arrays after fit (early-stopping or additional ests) if n_stages != self.estimators_.shape[0]: self.estimators_ = self.estimators_[:n_stages] self.train_score_ = self.train_score_[:n_stages] if hasattr(self, 'oob_improvement_'): self.oob_improvement_ = self.oob_improvement_[:n_stages] return self def _fit_stages(self, X, y, y_pred, sample_weight, random_state, begin_at_stage=0, monitor=None, X_idx_sorted=None): """Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping. """ n_samples = X.shape[0] do_oob = self.subsample < 1.0 sample_mask = np.ones((n_samples, ), dtype=np.bool) n_inbag = max(1, int(self.subsample * n_samples)) loss_ = self.loss_ # Set min_weight_leaf from min_weight_fraction_leaf if self.min_weight_fraction_leaf != 0. and sample_weight is not None: min_weight_leaf = (self.min_weight_fraction_leaf * np.sum(sample_weight)) else: min_weight_leaf = 0. if self.verbose: verbose_reporter = VerboseReporter(self.verbose) verbose_reporter.init(self, begin_at_stage) X_csc = csc_matrix(X) if issparse(X) else None X_csr = csr_matrix(X) if issparse(X) else None # perform boosting iterations i = begin_at_stage for i in range(begin_at_stage, self.n_estimators): # subsampling if do_oob: sample_mask = _random_sample_mask(n_samples, n_inbag, random_state) # OOB score before adding this stage old_oob_score = loss_(y[~sample_mask], y_pred[~sample_mask], sample_weight[~sample_mask]) # fit next stage of trees y_pred = self._fit_stage(i, X, y, y_pred, sample_weight, sample_mask, random_state, X_idx_sorted, X_csc, X_csr) # track deviance (= loss) if do_oob: self.train_score_[i] = loss_(y[sample_mask], y_pred[sample_mask], sample_weight[sample_mask]) self.oob_improvement_[i] = ( old_oob_score - loss_(y[~sample_mask], y_pred[~sample_mask], sample_weight[~sample_mask])) else: # no need to fancy index w/ no subsampling self.train_score_[i] = loss_(y, y_pred, sample_weight) if self.verbose > 0: verbose_reporter.update(i, self) if monitor is not None: early_stopping = monitor(i, self, locals()) if early_stopping: break return i + 1 def _make_estimator(self, append=True): # we don't need _make_estimator raise NotImplementedError() def _init_decision_function(self, X): """Check input and compute prediction of ``init``. """ self._check_initialized() X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) if X.shape[1] != self.n_features_: raise ValueError("X.shape[1] should be {0:d}, not {1:d}.".format( self.n_features_, X.shape[1])) score = self.init_.predict(X).astype(np.float64) return score def _decision_function(self, X): # for use in inner loop, not raveling the output in single-class case, # not doing input validation. score = self._init_decision_function(X) predict_stages(self.estimators_, X, self.learning_rate, score) return score def _staged_decision_function(self, X): """Compute decision function of ``X`` for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- score : generator of array, shape = [n_samples, k] The decision function of the input samples. The order of the classes corresponds to that in the attribute `classes_`. Regression and binary classification are special cases with ``k == 1``, otherwise ``k==n_classes``. """ X = check_array(X, dtype=DTYPE, order="C", accept_sparse='csr') score = self._init_decision_function(X) for i in range(self.estimators_.shape[0]): predict_stage(self.estimators_, i, X, self.learning_rate, score) yield score.copy() @property def feature_importances_(self): """Return the feature importances (the higher, the more important the feature). Returns ------- feature_importances_ : array, shape = [n_features] """ self._check_initialized() total_sum = np.zeros((self.n_features_, ), dtype=np.float64) for stage in self.estimators_: stage_sum = sum(tree.feature_importances_ for tree in stage) / len(stage) total_sum += stage_sum importances = total_sum / len(self.estimators_) return importances def _validate_y(self, y): self.n_classes_ = 1 if y.dtype.kind == 'O': y = y.astype(np.float64) # Default implementation return y def apply(self, X): """Apply trees in the ensemble to X, return leaf indices. .. versionadded:: 0.17 Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted to a sparse ``csr_matrix``. Returns ------- X_leaves : array_like, shape = [n_samples, n_estimators, n_classes] For each datapoint x in X and for each tree in the ensemble, return the index of the leaf x ends up in each estimator. In the case of binary classification n_classes is 1. """ self._check_initialized() X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) # n_classes will be equal to 1 in the binary classification or the # regression case. n_estimators, n_classes = self.estimators_.shape leaves = np.zeros((X.shape[0], n_estimators, n_classes)) for i in range(n_estimators): for j in range(n_classes): estimator = self.estimators_[i, j] leaves[:, i, j] = estimator.apply(X, check_input=False) return leaves class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): """Gradient Boosting for classification. GB builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage ``n_classes_`` regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced. Read more in the :ref:`User Guide <gradient_boosting>`. Parameters ---------- loss : {'deviance', 'exponential'}, optional (default='deviance') loss function to be optimized. 'deviance' refers to deviance (= logistic regression) for classification with probabilistic outputs. For loss 'exponential' gradient boosting recovers the AdaBoost algorithm. learning_rate : float, optional (default=0.1) learning rate shrinks the contribution of each tree by `learning_rate`. There is a trade-off between learning_rate and n_estimators. n_estimators : int (default=100) The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance. max_depth : integer, optional (default=3) maximum depth of the individual regression estimators. The maximum depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables. criterion : string, optional (default="friedman_mse") The function to measure the quality of a split. Supported criteria are "friedman_mse" for the mean squared error with improvement score by Friedman, "mse" for mean squared error, and "mae" for the mean absolute error. The default value of "friedman_mse" is generally the best as it can provide a better approximation in some cases. .. versionadded:: 0.18 min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. subsample : float, optional (default=1.0) The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. `subsample` interacts with the parameter `n_estimators`. Choosing `subsample < 1.0` leads to a reduction of variance and an increase in bias. max_features : int, float, string or None, optional (default=None) The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Choosing `max_features < n_features` leads to a reduction of variance and an increase in bias. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, optional (default=1e-7) Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. versionadded:: 0.18 init : BaseEstimator, None, optional (default=None) An estimator object that is used to compute the initial predictions. ``init`` has to provide ``fit`` and ``predict``. If None it uses ``loss.init_estimator``. verbose : int, default: 0 Enable verbose output. If 1 then it prints progress and performance once in a while (the more trees the lower the frequency). If greater than 1 then it prints progress and performance for every tree. warm_start : bool, default: False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just erase the previous solution. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. presort : bool or 'auto', optional (default='auto') Whether to presort the data to speed up the finding of best splits in fitting. Auto mode by default will use presorting on dense data and default to normal sorting on sparse data. Setting presort to true on sparse data will raise an error. .. versionadded:: 0.17 *presort* parameter. Attributes ---------- feature_importances_ : array, shape = [n_features] The feature importances (the higher, the more important the feature). oob_improvement_ : array, shape = [n_estimators] The improvement in loss (= deviance) on the out-of-bag samples relative to the previous iteration. ``oob_improvement_[0]`` is the improvement in loss of the first stage over the ``init`` estimator. train_score_ : array, shape = [n_estimators] The i-th score ``train_score_[i]`` is the deviance (= loss) of the model at iteration ``i`` on the in-bag sample. If ``subsample == 1`` this is the deviance on the training data. loss_ : LossFunction The concrete ``LossFunction`` object. init : BaseEstimator The estimator that provides the initial predictions. Set via the ``init`` argument or ``loss.init_estimator``. estimators_ : ndarray of DecisionTreeRegressor, shape = [n_estimators, ``loss_.K``] The collection of fitted sub-estimators. ``loss_.K`` is 1 for binary classification, otherwise n_classes. See also -------- sklearn.tree.DecisionTreeClassifier, RandomForestClassifier AdaBoostClassifier References ---------- J. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. J. Friedman, Stochastic Gradient Boosting, 1999 T. Hastie, R. Tibshirani and J. Friedman. Elements of Statistical Learning Ed. 2, Springer, 2009. """ _SUPPORTED_LOSS = ('deviance', 'exponential') def __init__(self, loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_depth=3, min_impurity_split=1e-7, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto'): super(GradientBoostingClassifier, self).__init__( loss=loss, learning_rate=learning_rate, n_estimators=n_estimators, criterion=criterion, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_depth=max_depth, init=init, subsample=subsample, max_features=max_features, random_state=random_state, verbose=verbose, max_leaf_nodes=max_leaf_nodes, min_impurity_split=min_impurity_split, warm_start=warm_start, presort=presort) def _validate_y(self, y): check_classification_targets(y) self.classes_, y = np.unique(y, return_inverse=True) self.n_classes_ = len(self.classes_) return y def decision_function(self, X): """Compute the decision function of ``X``. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- score : array, shape = [n_samples, n_classes] or [n_samples] The decision function of the input samples. The order of the classes corresponds to that in the attribute `classes_`. Regression and binary classification produce an array of shape [n_samples]. """ X = check_array(X, dtype=DTYPE, order="C", accept_sparse='csr') score = self._decision_function(X) if score.shape[1] == 1: return score.ravel() return score def staged_decision_function(self, X): """Compute decision function of ``X`` for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- score : generator of array, shape = [n_samples, k] The decision function of the input samples. The order of the classes corresponds to that in the attribute `classes_`. Regression and binary classification are special cases with ``k == 1``, otherwise ``k==n_classes``. """ for dec in self._staged_decision_function(X): # no yield from in Python2.X yield dec def predict(self, X): """Predict class for X. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : array of shape = ["n_samples] The predicted values. """ score = self.decision_function(X) decisions = self.loss_._score_to_decision(score) return self.classes_.take(decisions, axis=0) def staged_predict(self, X): """Predict class at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : generator of array of shape = [n_samples] The predicted value of the input samples. """ for score in self._staged_decision_function(X): decisions = self.loss_._score_to_decision(score) yield self.classes_.take(decisions, axis=0) def predict_proba(self, X): """Predict class probabilities for X. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Raises ------ AttributeError If the ``loss`` does not support probabilities. Returns ------- p : array of shape = [n_samples] The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ score = self.decision_function(X) try: return self.loss_._score_to_proba(score) except NotFittedError: raise except AttributeError: raise AttributeError('loss=%r does not support predict_proba' % self.loss) def predict_log_proba(self, X): """Predict class log-probabilities for X. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Raises ------ AttributeError If the ``loss`` does not support probabilities. Returns ------- p : array of shape = [n_samples] The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) return np.log(proba) def staged_predict_proba(self, X): """Predict class probabilities at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : generator of array of shape = [n_samples] The predicted value of the input samples. """ try: for score in self._staged_decision_function(X): yield self.loss_._score_to_proba(score) except NotFittedError: raise except AttributeError: raise AttributeError('loss=%r does not support predict_proba' % self.loss) class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): """Gradient Boosting for regression. GB builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage a regression tree is fit on the negative gradient of the given loss function. Read more in the :ref:`User Guide <gradient_boosting>`. Parameters ---------- loss : {'ls', 'lad', 'huber', 'quantile'}, optional (default='ls') loss function to be optimized. 'ls' refers to least squares regression. 'lad' (least absolute deviation) is a highly robust loss function solely based on order information of the input variables. 'huber' is a combination of the two. 'quantile' allows quantile regression (use `alpha` to specify the quantile). learning_rate : float, optional (default=0.1) learning rate shrinks the contribution of each tree by `learning_rate`. There is a trade-off between learning_rate and n_estimators. n_estimators : int (default=100) The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance. max_depth : integer, optional (default=3) maximum depth of the individual regression estimators. The maximum depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables. criterion : string, optional (default="friedman_mse") The function to measure the quality of a split. Supported criteria are "friedman_mse" for the mean squared error with improvement score by Friedman, "mse" for mean squared error, and "mae" for the mean absolute error. The default value of "friedman_mse" is generally the best as it can provide a better approximation in some cases. .. versionadded:: 0.18 min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. subsample : float, optional (default=1.0) The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. `subsample` interacts with the parameter `n_estimators`. Choosing `subsample < 1.0` leads to a reduction of variance and an increase in bias. max_features : int, float, string or None, optional (default=None) The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Choosing `max_features < n_features` leads to a reduction of variance and an increase in bias. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, optional (default=1e-7) Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. versionadded:: 0.18 alpha : float (default=0.9) The alpha-quantile of the huber loss function and the quantile loss function. Only if ``loss='huber'`` or ``loss='quantile'``. init : BaseEstimator, None, optional (default=None) An estimator object that is used to compute the initial predictions. ``init`` has to provide ``fit`` and ``predict``. If None it uses ``loss.init_estimator``. verbose : int, default: 0 Enable verbose output. If 1 then it prints progress and performance once in a while (the more trees the lower the frequency). If greater than 1 then it prints progress and performance for every tree. warm_start : bool, default: False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just erase the previous solution. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. presort : bool or 'auto', optional (default='auto') Whether to presort the data to speed up the finding of best splits in fitting. Auto mode by default will use presorting on dense data and default to normal sorting on sparse data. Setting presort to true on sparse data will raise an error. .. versionadded:: 0.17 optional parameter *presort*. Attributes ---------- feature_importances_ : array, shape = [n_features] The feature importances (the higher, the more important the feature). oob_improvement_ : array, shape = [n_estimators] The improvement in loss (= deviance) on the out-of-bag samples relative to the previous iteration. ``oob_improvement_[0]`` is the improvement in loss of the first stage over the ``init`` estimator. train_score_ : array, shape = [n_estimators] The i-th score ``train_score_[i]`` is the deviance (= loss) of the model at iteration ``i`` on the in-bag sample. If ``subsample == 1`` this is the deviance on the training data. loss_ : LossFunction The concrete ``LossFunction`` object. `init` : BaseEstimator The estimator that provides the initial predictions. Set via the ``init`` argument or ``loss.init_estimator``. estimators_ : ndarray of DecisionTreeRegressor, shape = [n_estimators, 1] The collection of fitted sub-estimators. See also -------- DecisionTreeRegressor, RandomForestRegressor References ---------- J. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. J. Friedman, Stochastic Gradient Boosting, 1999 T. Hastie, R. Tibshirani and J. Friedman. Elements of Statistical Learning Ed. 2, Springer, 2009. """ _SUPPORTED_LOSS = ('ls', 'lad', 'huber', 'quantile') def __init__(self, loss='ls', learning_rate=0.1, n_estimators=100, subsample=1.0, criterion='friedman_mse', min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_depth=3, min_impurity_split=1e-7, init=None, random_state=None, max_features=None, alpha=0.9, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto'): super(GradientBoostingRegressor, self).__init__( loss=loss, learning_rate=learning_rate, n_estimators=n_estimators, criterion=criterion, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_depth=max_depth, init=init, subsample=subsample, max_features=max_features, min_impurity_split=min_impurity_split, random_state=random_state, alpha=alpha, verbose=verbose, max_leaf_nodes=max_leaf_nodes, warm_start=warm_start, presort=presort) def predict(self, X): """Predict regression target for X. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] The predicted values. """ X = check_array(X, dtype=DTYPE, order="C", accept_sparse='csr') return self._decision_function(X).ravel() def staged_predict(self, X): """Predict regression target at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : generator of array of shape = [n_samples] The predicted value of the input samples. """ for y in self._staged_decision_function(X): yield y.ravel() def apply(self, X): """Apply trees in the ensemble to X, return leaf indices. .. versionadded:: 0.17 Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted to a sparse ``csr_matrix``. Returns ------- X_leaves : array_like, shape = [n_samples, n_estimators] For each datapoint x in X and for each tree in the ensemble, return the index of the leaf x ends up in each estimator. """ leaves = super(GradientBoostingRegressor, self).apply(X) leaves = leaves.reshape(X.shape[0], self.estimators_.shape[0]) return leaves
bsd-3-clause
timothyparez/PyBitmessage
src/bitmessageqt/support.py
4
4943
import ctypes from PyQt4 import QtCore, QtGui import ssl import sys import time import account from debug import logger from foldertree import AccountMixin from helper_sql import * from l10n import getTranslationLanguage from openclpow import has_opencl from proofofwork import bmpow from pyelliptic.openssl import OpenSSL import shared # this is BM support address going to Peter Surda SUPPORT_ADDRESS = 'BM-2cTkCtMYkrSPwFTpgcBrMrf5d8oZwvMZWK' SUPPORT_LABEL = 'PyBitmessage support' SUPPORT_MY_LABEL = 'My new address' SUPPORT_SUBJECT = 'Support request' SUPPORT_MESSAGE = '''You can use this message to send a report to one of the PyBitmessage core developers regarding PyBitmessage or the mailchuck.com email service. If you are using PyBitmessage involuntarily, for example because your computer was infected with ransomware, this is not an appropriate venue for resolving such issues. Please describe what you are trying to do: Please describe what you expect to happen: Please describe what happens instead: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Please write above this line and if possible, keep the information about your environment below intact. PyBitmesage version: {} Operating system: {} Architecture: {}bit Python Version: {} OpenSSL Version: {} Frozen: {} Portable mode: {} C PoW: {} OpenCL PoW: {} Locale: {} SOCKS: {} UPnP: {} Connected hosts: {} ''' def checkAddressBook(myapp): queryreturn = sqlQuery('''SELECT * FROM addressbook WHERE address=?''', SUPPORT_ADDRESS) if queryreturn == []: sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', str(QtGui.QApplication.translate("Support", SUPPORT_LABEL)), SUPPORT_ADDRESS) myapp.rerenderAddressBook() def checkHasNormalAddress(): for address in account.getSortedAccounts(): acct = account.accountClass(address) if acct.type == AccountMixin.NORMAL and shared.safeConfigGetBoolean(address, 'enabled'): return address return False def createAddressIfNeeded(myapp): if not checkHasNormalAddress(): shared.addressGeneratorQueue.put(('createRandomAddress', 4, 1, str(QtGui.QApplication.translate("Support", SUPPORT_MY_LABEL)), 1, "", False, shared.networkDefaultProofOfWorkNonceTrialsPerByte, shared.networkDefaultPayloadLengthExtraBytes)) while shared.shutdown == 0 and not checkHasNormalAddress(): time.sleep(.2) myapp.rerenderComboBoxSendFrom() return checkHasNormalAddress() def createSupportMessage(myapp): checkAddressBook(myapp) address = createAddressIfNeeded(myapp) if shared.shutdown: return myapp.ui.lineEditSubject.setText(str(QtGui.QApplication.translate("Support", SUPPORT_SUBJECT))) addrIndex = myapp.ui.comboBoxSendFrom.findData(address, QtCore.Qt.UserRole, QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive) if addrIndex == -1: # something is very wrong return myapp.ui.comboBoxSendFrom.setCurrentIndex(addrIndex) myapp.ui.lineEditTo.setText(SUPPORT_ADDRESS) version = shared.softwareVersion os = sys.platform if os == "win32": windowsversion = sys.getwindowsversion() os = "Windows " + str(windowsversion[0]) + "." + str(windowsversion[1]) else: try: from os import uname unixversion = uname() os = unixversion[0] + " " + unixversion[2] except: pass architecture = "32" if ctypes.sizeof(ctypes.c_voidp) == 4 else "64" pythonversion = sys.version SSLEAY_VERSION = 0 OpenSSL._lib.SSLeay.restype = ctypes.c_long OpenSSL._lib.SSLeay_version.restype = ctypes.c_char_p OpenSSL._lib.SSLeay_version.argtypes = [ctypes.c_int] opensslversion = "%s (Python internal), %s (external for PyElliptic)" % (ssl.OPENSSL_VERSION, OpenSSL._lib.SSLeay_version(SSLEAY_VERSION)) frozen = "N/A" if shared.frozen: frozen = shared.frozen portablemode = "True" if shared.appdata == shared.lookupExeFolder() else "False" cpow = "True" if bmpow else "False" #cpow = QtGui.QApplication.translate("Support", cpow) openclpow = "True" if shared.safeConfigGetBoolean('bitmessagesettings', 'opencl') and has_opencl() else "False" #openclpow = QtGui.QApplication.translate("Support", openclpow) locale = getTranslationLanguage() try: socks = shared.config.get('bitmessagesettings', 'socksproxytype') except: socks = "N/A" try: upnp = shared.config.get('bitmessagesettings', 'upnp') except: upnp = "N/A" connectedhosts = len(shared.connectedHostsList) myapp.ui.textEditMessage.setText(str(QtGui.QApplication.translate("Support", SUPPORT_MESSAGE)).format(version, os, architecture, pythonversion, opensslversion, frozen, portablemode, cpow, openclpow, locale, socks, upnp, connectedhosts)) # single msg tab myapp.ui.tabWidgetSend.setCurrentIndex(0) # send tab myapp.ui.tabWidget.setCurrentIndex(1)
mit
Lektorium-LLC/edx-platform
cms/djangoapps/contentstore/views/tests/test_item.py
3
148881
"""Tests for items views.""" import json from datetime import datetime, timedelta import ddt from django.conf import settings from django.core.urlresolvers import reverse from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from mock import Mock, PropertyMock, patch from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from opaque_keys.edx.locations import Location from pyquery import PyQuery from pytz import UTC from webob import Response from xblock.core import XBlockAside from xblock.exceptions import NoSuchHandlerError from xblock.fields import Scope, ScopeIds, String from xblock.fragment import Fragment from xblock.runtime import DictKeyValueStore, KvsFieldData from xblock.test.tools import TestRuntime from xblock.validation import ValidationMessage from contentstore.tests.utils import CourseTestCase from contentstore.utils import reverse_course_url, reverse_usage_url from contentstore.views.component import component_handler, get_component_templates from contentstore.views.item import ( ALWAYS, VisibilityState, _get_module_info, _get_source_index, _xblock_type_and_display_name, add_container_page_publishing_info, create_xblock_info ) from lms_xblock.mixin import NONSENSICAL_ACCESS_RESTRICTION from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration from student.tests.factories import UserFactory from xblock_django.models import XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConfigurationFlag from xblock_django.user_service import DjangoXBlockUserService from xmodule.capa_module import CapaDescriptor from xmodule.course_module import DEFAULT_START_DATE from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, LibraryFactory, check_mongo_calls from xmodule.partitions.partitions import ( ENROLLMENT_TRACK_PARTITION_ID, MINIMUM_STATIC_PARTITION_ID, Group, UserPartition ) from xmodule.partitions.tests.test_partitions import MockPartitionService from xmodule.x_module import STUDENT_VIEW, STUDIO_VIEW class AsideTest(XBlockAside): """ Test xblock aside class """ FRAG_CONTENT = u"<p>Aside Foo rendered</p>" field11 = String(default="aside1_default_value1", scope=Scope.content) field12 = String(default="aside1_default_value2", scope=Scope.settings) field13 = String(default="aside1_default_value3", scope=Scope.parent) @XBlockAside.aside_for('student_view') def student_view_aside(self, block, context): # pylint: disable=unused-argument """Add to the student view""" return Fragment(self.FRAG_CONTENT) class ItemTest(CourseTestCase): """ Base test class for create, save, and delete """ def setUp(self): super(ItemTest, self).setUp() self.course_key = self.course.id self.usage_key = self.course.location def get_item_from_modulestore(self, usage_key, verify_is_draft=False): """ Get the item referenced by the UsageKey from the modulestore """ item = self.store.get_item(usage_key) if verify_is_draft: self.assertTrue(getattr(item, 'is_draft', False)) return item def response_usage_key(self, response): """ Get the UsageKey from the response payload and verify that the status_code was 200. :param response: """ parsed = json.loads(response.content) self.assertEqual(response.status_code, 200) key = UsageKey.from_string(parsed['locator']) if key.course_key.run is None: key = key.map_into_course(CourseKey.from_string(parsed['courseKey'])) return key def create_xblock(self, parent_usage_key=None, display_name=None, category=None, boilerplate=None): data = { 'parent_locator': unicode(self.usage_key) if parent_usage_key is None else unicode(parent_usage_key), 'category': category } if display_name is not None: data['display_name'] = display_name if boilerplate is not None: data['boilerplate'] = boilerplate return self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data)) def _create_vertical(self, parent_usage_key=None): """ Creates a vertical, returning its UsageKey. """ resp = self.create_xblock(category='vertical', parent_usage_key=parent_usage_key) self.assertEqual(resp.status_code, 200) return self.response_usage_key(resp) @ddt.ddt class GetItemTest(ItemTest): """Tests for '/xblock' GET url.""" def _get_preview(self, usage_key, data=None): """ Makes a request to xblock preview handler """ preview_url = reverse_usage_url("xblock_view_handler", usage_key, {'view_name': 'container_preview'}) data = data if data else {} resp = self.client.get(preview_url, data, HTTP_ACCEPT='application/json') return resp def _get_container_preview(self, usage_key, data=None): """ Returns the HTML and resources required for the xblock at the specified UsageKey """ resp = self._get_preview(usage_key, data) self.assertEqual(resp.status_code, 200) resp_content = json.loads(resp.content) html = resp_content['html'] self.assertTrue(html) resources = resp_content['resources'] self.assertIsNotNone(resources) return html, resources def _get_container_preview_with_error(self, usage_key, expected_code, data=None, content_contains=None): """ Make request and asserts on response code and response contents """ resp = self._get_preview(usage_key, data) self.assertEqual(resp.status_code, expected_code) if content_contains: self.assertIn(content_contains, resp.content) return resp @ddt.data( (1, 17, 15, 16, 12), (2, 17, 15, 16, 12), (3, 17, 15, 16, 12), ) @ddt.unpack def test_get_query_count(self, branching_factor, chapter_queries, section_queries, unit_queries, problem_queries): self.populate_course(branching_factor) # Retrieve it with check_mongo_calls(chapter_queries): self.client.get(reverse_usage_url('xblock_handler', self.populated_usage_keys['chapter'][-1])) with check_mongo_calls(section_queries): self.client.get(reverse_usage_url('xblock_handler', self.populated_usage_keys['sequential'][-1])) with check_mongo_calls(unit_queries): self.client.get(reverse_usage_url('xblock_handler', self.populated_usage_keys['vertical'][-1])) with check_mongo_calls(problem_queries): self.client.get(reverse_usage_url('xblock_handler', self.populated_usage_keys['problem'][-1])) @ddt.data( (1, 30), (2, 32), (3, 34), ) @ddt.unpack def test_container_get_query_count(self, branching_factor, unit_queries,): self.populate_course(branching_factor) with check_mongo_calls(unit_queries): self.client.get(reverse_usage_url('xblock_container_handler', self.populated_usage_keys['vertical'][-1])) def test_get_vertical(self): # Add a vertical resp = self.create_xblock(category='vertical') usage_key = self.response_usage_key(resp) # Retrieve it resp = self.client.get(reverse_usage_url('xblock_handler', usage_key)) self.assertEqual(resp.status_code, 200) def test_get_empty_container_fragment(self): root_usage_key = self._create_vertical() html, __ = self._get_container_preview(root_usage_key) # XBlock messages are added by the Studio wrapper. self.assertIn('wrapper-xblock-message', html) # Make sure that "wrapper-xblock" does not appear by itself (without -message at end). self.assertNotRegexpMatches(html, r'wrapper-xblock[^-]+') # Verify that the header and article tags are still added self.assertIn('<header class="xblock-header xblock-header-vertical">', html) self.assertIn('<article class="xblock-render">', html) def test_get_container_fragment(self): root_usage_key = self._create_vertical() # Add a problem beneath a child vertical child_vertical_usage_key = self._create_vertical(parent_usage_key=root_usage_key) resp = self.create_xblock(parent_usage_key=child_vertical_usage_key, category='problem', boilerplate='multiplechoice.yaml') self.assertEqual(resp.status_code, 200) # Get the preview HTML html, __ = self._get_container_preview(root_usage_key) # Verify that the Studio nesting wrapper has been added self.assertIn('level-nesting', html) self.assertIn('<header class="xblock-header xblock-header-vertical">', html) self.assertIn('<article class="xblock-render">', html) # Verify that the Studio element wrapper has been added self.assertIn('level-element', html) def test_get_container_nested_container_fragment(self): """ Test the case of the container page containing a link to another container page. """ # Add a wrapper with child beneath a child vertical root_usage_key = self._create_vertical() resp = self.create_xblock(parent_usage_key=root_usage_key, category="wrapper") self.assertEqual(resp.status_code, 200) wrapper_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='problem', boilerplate='multiplechoice.yaml') self.assertEqual(resp.status_code, 200) # Get the preview HTML and verify the View -> link is present. html, __ = self._get_container_preview(root_usage_key) self.assertIn('wrapper-xblock', html) self.assertRegexpMatches( html, # The instance of the wrapper class will have an auto-generated ID. Allow any # characters after wrapper. r'"/container/{}" class="action-button">\s*<span class="action-button-text">View</span>'.format( wrapper_usage_key ) ) def test_split_test(self): """ Test that a split_test module renders all of its children in Studio. """ root_usage_key = self._create_vertical() resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key) split_test_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='announcement.yaml') self.assertEqual(resp.status_code, 200) resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='zooming_image.yaml') self.assertEqual(resp.status_code, 200) html, __ = self._get_container_preview(split_test_usage_key) self.assertIn('Announcement', html) self.assertIn('Zooming', html) def test_split_test_edited(self): """ Test that rename of a group changes display name of child vertical. """ self.course.user_partitions = [UserPartition( 0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')] )] self.store.update_item(self.course, self.user.id) root_usage_key = self._create_vertical() resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key) split_test_usage_key = self.response_usage_key(resp) self.client.ajax_post( reverse_usage_url("xblock_handler", split_test_usage_key), data={'metadata': {'user_partition_id': str(0)}} ) html, __ = self._get_container_preview(split_test_usage_key) self.assertIn('alpha', html) self.assertIn('beta', html) # Rename groups in group configuration GROUP_CONFIGURATION_JSON = { u'id': 0, u'name': u'first_partition', u'scheme': u'random', u'description': u'First Partition', u'version': UserPartition.VERSION, u'groups': [ {u'id': 0, u'name': u'New_NAME_A', u'version': 1}, {u'id': 1, u'name': u'New_NAME_B', u'version': 1}, ], } response = self.client.put( reverse_course_url('group_configurations_detail_handler', self.course.id, kwargs={'group_configuration_id': 0}), data=json.dumps(GROUP_CONFIGURATION_JSON), content_type="application/json", HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) self.assertEqual(response.status_code, 201) html, __ = self._get_container_preview(split_test_usage_key) self.assertNotIn('alpha', html) self.assertNotIn('beta', html) self.assertIn('New_NAME_A', html) self.assertIn('New_NAME_B', html) def test_valid_paging(self): """ Tests that valid paging is passed along to underlying block """ with patch('contentstore.views.item.get_preview_fragment') as patched_get_preview_fragment: retval = Mock() type(retval).content = PropertyMock(return_value="Some content") type(retval).resources = PropertyMock(return_value=[]) patched_get_preview_fragment.return_value = retval root_usage_key = self._create_vertical() _, _ = self._get_container_preview( root_usage_key, {'enable_paging': 'true', 'page_number': 0, 'page_size': 2} ) call_args = patched_get_preview_fragment.call_args[0] _, _, context = call_args self.assertIn('paging', context) self.assertEqual({'page_number': 0, 'page_size': 2}, context['paging']) @ddt.data([1, 'invalid'], ['invalid', 2]) @ddt.unpack def test_invalid_paging(self, page_number, page_size): """ Tests that valid paging is passed along to underlying block """ root_usage_key = self._create_vertical() self._get_container_preview_with_error( root_usage_key, 400, data={'enable_paging': 'true', 'page_number': page_number, 'page_size': page_size}, content_contains="Couldn't parse paging parameters" ) def test_get_user_partitions_and_groups(self): # Note about UserPartition and UserPartition Group IDs: these must not conflict with IDs used # by dynamic user partitions. self.course.user_partitions = [ UserPartition( id=MINIMUM_STATIC_PARTITION_ID, name="Random user partition", scheme=UserPartition.get_scheme("random"), description="Random user partition", groups=[ Group(id=MINIMUM_STATIC_PARTITION_ID + 1, name="Group A"), # See note above. Group(id=MINIMUM_STATIC_PARTITION_ID + 2, name="Group B"), # See note above. ], ), ] self.store.update_item(self.course, self.user.id) # Create an item and retrieve it resp = self.create_xblock(category='vertical') usage_key = self.response_usage_key(resp) resp = self.client.get(reverse_usage_url('xblock_handler', usage_key)) self.assertEqual(resp.status_code, 200) # Check that the partition and group information was returned result = json.loads(resp.content) self.assertEqual(result["user_partitions"], [ { "id": ENROLLMENT_TRACK_PARTITION_ID, "name": "Enrollment Track Groups", "scheme": "enrollment_track", "groups": [ { "id": settings.COURSE_ENROLLMENT_MODES["audit"], "name": "Audit", "selected": False, "deleted": False, } ] }, { "id": MINIMUM_STATIC_PARTITION_ID, "name": "Random user partition", "scheme": "random", "groups": [ { "id": MINIMUM_STATIC_PARTITION_ID + 1, "name": "Group A", "selected": False, "deleted": False, }, { "id": MINIMUM_STATIC_PARTITION_ID + 2, "name": "Group B", "selected": False, "deleted": False, }, ] } ]) self.assertEqual(result["group_access"], {}) @ddt.data('ancestorInfo', '') def test_ancestor_info(self, field_type): """ Test that we get correct ancestor info. Arguments: field_type (string): If field_type=ancestorInfo, fetch ancestor info of the XBlock otherwise not. """ # Create a parent chapter chap1 = self.create_xblock(parent_usage_key=self.course.location, display_name='chapter1', category='chapter') chapter_usage_key = self.response_usage_key(chap1) # create a sequential seq1 = self.create_xblock(parent_usage_key=chapter_usage_key, display_name='seq1', category='sequential') seq_usage_key = self.response_usage_key(seq1) # create a vertical vert1 = self.create_xblock(parent_usage_key=seq_usage_key, display_name='vertical1', category='vertical') vert_usage_key = self.response_usage_key(vert1) # create problem and an html component problem1 = self.create_xblock(parent_usage_key=vert_usage_key, display_name='problem1', category='problem') problem_usage_key = self.response_usage_key(problem1) def assert_xblock_info(xblock, xblock_info): """ Assert we have correct xblock info. Arguments: xblock (XBlock): An XBlock item. xblock_info (dict): A dict containing xblock information. """ self.assertEqual(unicode(xblock.location), xblock_info['id']) self.assertEqual(xblock.display_name, xblock_info['display_name']) self.assertEqual(xblock.category, xblock_info['category']) for usage_key in (problem_usage_key, vert_usage_key, seq_usage_key, chapter_usage_key): xblock = self.get_item_from_modulestore(usage_key) url = reverse_usage_url('xblock_handler', usage_key) + '?fields={field_type}'.format(field_type=field_type) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = json.loads(response.content) if field_type == 'ancestorInfo': self.assertIn('ancestors', response) for ancestor_info in response['ancestors']: parent_xblock = xblock.get_parent() assert_xblock_info(parent_xblock, ancestor_info) xblock = parent_xblock else: self.assertNotIn('ancestors', response) self.assertEqual(_get_module_info(xblock), response) @ddt.ddt class DeleteItem(ItemTest): """Tests for '/xblock' DELETE url.""" @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_delete_static_page(self, store): course = CourseFactory.create(default_store=store) # Add static tab resp = self.create_xblock(category='static_tab', parent_usage_key=course.location) usage_key = self.response_usage_key(resp) # Now delete it. There was a bug that the delete was failing (static tabs do not exist in draft modulestore). resp = self.client.delete(reverse_usage_url('xblock_handler', usage_key)) self.assertEqual(resp.status_code, 204) class TestCreateItem(ItemTest): """ Test the create_item handler thoroughly """ def test_create_nicely(self): """ Try the straightforward use cases """ # create a chapter display_name = 'Nicely created' resp = self.create_xblock(display_name=display_name, category='chapter') # get the new item and check its category and display_name chap_usage_key = self.response_usage_key(resp) new_obj = self.get_item_from_modulestore(chap_usage_key) self.assertEqual(new_obj.scope_ids.block_type, 'chapter') self.assertEqual(new_obj.display_name, display_name) self.assertEqual(new_obj.location.org, self.course.location.org) self.assertEqual(new_obj.location.course, self.course.location.course) # get the course and ensure it now points to this one course = self.get_item_from_modulestore(self.usage_key) self.assertIn(chap_usage_key, course.children) # use default display name resp = self.create_xblock(parent_usage_key=chap_usage_key, category='vertical') vert_usage_key = self.response_usage_key(resp) # create problem w/ boilerplate template_id = 'multiplechoice.yaml' resp = self.create_xblock( parent_usage_key=vert_usage_key, category='problem', boilerplate=template_id ) prob_usage_key = self.response_usage_key(resp) problem = self.get_item_from_modulestore(prob_usage_key, verify_is_draft=True) # check against the template template = CapaDescriptor.get_template(template_id) self.assertEqual(problem.data, template['data']) self.assertEqual(problem.display_name, template['metadata']['display_name']) self.assertEqual(problem.markdown, template['metadata']['markdown']) def test_create_item_negative(self): """ Negative tests for create_item """ # non-existent boilerplate: creates a default resp = self.create_xblock(category='problem', boilerplate='nosuchboilerplate.yaml') self.assertEqual(resp.status_code, 200) def test_create_with_future_date(self): self.assertEqual(self.course.start, datetime(2030, 1, 1, tzinfo=UTC)) resp = self.create_xblock(category='chapter') usage_key = self.response_usage_key(resp) obj = self.get_item_from_modulestore(usage_key) self.assertEqual(obj.start, datetime(2030, 1, 1, tzinfo=UTC)) def test_static_tabs_initialization(self): """ Test that static tab display names are not being initialized as None. """ # Add a new static tab with no explicit name resp = self.create_xblock(category='static_tab') usage_key = self.response_usage_key(resp) # Check that its name is not None new_tab = self.get_item_from_modulestore(usage_key) self.assertEquals(new_tab.display_name, 'Empty') class DuplicateHelper(object): """ Helper mixin class for TestDuplicateItem and TestDuplicateItemWithAsides """ def _duplicate_and_verify(self, source_usage_key, parent_usage_key, check_asides=False): """ Duplicates the source, parenting to supplied parent. Then does equality check. """ usage_key = self._duplicate_item(parent_usage_key, source_usage_key) # pylint: disable=no-member self.assertTrue( self._check_equality(source_usage_key, usage_key, parent_usage_key, check_asides=check_asides), "Duplicated item differs from original" ) def _check_equality(self, source_usage_key, duplicate_usage_key, parent_usage_key=None, check_asides=False, is_child=False): """ Gets source and duplicated items from the modulestore using supplied usage keys. Then verifies that they represent equivalent items (modulo parents and other known things that may differ). """ # pylint: disable=no-member original_item = self.get_item_from_modulestore(source_usage_key) duplicated_item = self.get_item_from_modulestore(duplicate_usage_key) if check_asides: original_asides = original_item.runtime.get_asides(original_item) duplicated_asides = duplicated_item.runtime.get_asides(duplicated_item) self.assertEqual(len(original_asides), 1) self.assertEqual(len(duplicated_asides), 1) self.assertEqual(original_asides[0].field11, duplicated_asides[0].field11) self.assertEqual(original_asides[0].field12, duplicated_asides[0].field12) self.assertNotEqual(original_asides[0].field13, duplicated_asides[0].field13) self.assertEqual(duplicated_asides[0].field13, 'aside1_default_value3') self.assertNotEqual( unicode(original_item.location), unicode(duplicated_item.location), "Location of duplicate should be different from original" ) # Parent will only be equal for root of duplicated structure, in the case # where an item is duplicated in-place. if parent_usage_key and unicode(original_item.parent) == unicode(parent_usage_key): self.assertEqual( unicode(parent_usage_key), unicode(duplicated_item.parent), "Parent of duplicate should equal parent of source for root xblock when duplicated in-place" ) else: self.assertNotEqual( unicode(original_item.parent), unicode(duplicated_item.parent), "Parent duplicate should be different from source" ) # Set the location and parent to be the same so we can make sure the rest of the # duplicate is equal. duplicated_item.location = original_item.location duplicated_item.parent = original_item.parent # Children will also be duplicated, so for the purposes of testing equality, we will set # the children to the original after recursively checking the children. if original_item.has_children: self.assertEqual( len(original_item.children), len(duplicated_item.children), "Duplicated item differs in number of children" ) for i in xrange(len(original_item.children)): if not self._check_equality(original_item.children[i], duplicated_item.children[i], is_child=True): return False duplicated_item.children = original_item.children return self._verify_duplicate_display_name(original_item, duplicated_item, is_child) def _verify_duplicate_display_name(self, original_item, duplicated_item, is_child=False): """ Verifies display name of duplicated item. """ if is_child: if original_item.display_name is None: return duplicated_item.display_name == original_item.category return duplicated_item.display_name == original_item.display_name if original_item.display_name is not None: return duplicated_item.display_name == "Duplicate of '{display_name}'".format( display_name=original_item.display_name ) return duplicated_item.display_name == "Duplicate of {display_name}".format( display_name=original_item.category ) def _duplicate_item(self, parent_usage_key, source_usage_key, display_name=None): """ Duplicates the source. """ # pylint: disable=no-member data = { 'parent_locator': unicode(parent_usage_key), 'duplicate_source_locator': unicode(source_usage_key) } if display_name is not None: data['display_name'] = display_name resp = self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data)) return self.response_usage_key(resp) class TestDuplicateItem(ItemTest, DuplicateHelper): """ Test the duplicate method. """ def setUp(self): """ Creates the test course structure and a few components to 'duplicate'. """ super(TestDuplicateItem, self).setUp() # Create a parent chapter (for testing children of children). resp = self.create_xblock(parent_usage_key=self.usage_key, category='chapter') self.chapter_usage_key = self.response_usage_key(resp) # create a sequential resp = self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential') self.seq_usage_key = self.response_usage_key(resp) # create a vertical containing a problem and an html component resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical') self.vert_usage_key = self.response_usage_key(resp) # create problem and an html component resp = self.create_xblock(parent_usage_key=self.vert_usage_key, category='problem', boilerplate='multiplechoice.yaml') self.problem_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=self.vert_usage_key, category='html') self.html_usage_key = self.response_usage_key(resp) # Create a second sequential just (testing children of children) self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential2') def test_duplicate_equality(self): """ Tests that a duplicated xblock is identical to the original, except for location and display name. """ self._duplicate_and_verify(self.problem_usage_key, self.vert_usage_key) self._duplicate_and_verify(self.html_usage_key, self.vert_usage_key) self._duplicate_and_verify(self.vert_usage_key, self.seq_usage_key) self._duplicate_and_verify(self.seq_usage_key, self.chapter_usage_key) self._duplicate_and_verify(self.chapter_usage_key, self.usage_key) def test_ordering(self): """ Tests the a duplicated xblock appears immediately after its source (if duplicate and source share the same parent), else at the end of the children of the parent. """ def verify_order(source_usage_key, parent_usage_key, source_position=None): usage_key = self._duplicate_item(parent_usage_key, source_usage_key) parent = self.get_item_from_modulestore(parent_usage_key) children = parent.children if source_position is None: self.assertNotIn(source_usage_key, children, 'source item not expected in children array') self.assertEqual( children[len(children) - 1], usage_key, "duplicated item not at end" ) else: self.assertEqual( children[source_position], source_usage_key, "source item at wrong position" ) self.assertEqual( children[source_position + 1], usage_key, "duplicated item not ordered after source item" ) verify_order(self.problem_usage_key, self.vert_usage_key, 0) # 2 because duplicate of problem should be located before. verify_order(self.html_usage_key, self.vert_usage_key, 2) verify_order(self.vert_usage_key, self.seq_usage_key, 0) verify_order(self.seq_usage_key, self.chapter_usage_key, 0) # Test duplicating something into a location that is not the parent of the original item. # Duplicated item should appear at the end. verify_order(self.html_usage_key, self.usage_key) def test_display_name(self): """ Tests the expected display name for the duplicated xblock. """ def verify_name(source_usage_key, parent_usage_key, expected_name, display_name=None): usage_key = self._duplicate_item(parent_usage_key, source_usage_key, display_name) duplicated_item = self.get_item_from_modulestore(usage_key) self.assertEqual(duplicated_item.display_name, expected_name) return usage_key # Display name comes from template. dupe_usage_key = verify_name(self.problem_usage_key, self.vert_usage_key, "Duplicate of 'Multiple Choice'") # Test dupe of dupe. verify_name(dupe_usage_key, self.vert_usage_key, "Duplicate of 'Duplicate of 'Multiple Choice''") # Uses default display_name of 'Text' from HTML component. verify_name(self.html_usage_key, self.vert_usage_key, "Duplicate of 'Text'") # The sequence does not have a display_name set, so category is shown. verify_name(self.seq_usage_key, self.chapter_usage_key, "Duplicate of sequential") # Now send a custom display name for the duplicate. verify_name(self.seq_usage_key, self.chapter_usage_key, "customized name", display_name="customized name") @ddt.ddt class TestMoveItem(ItemTest): """ Tests for move item. """ def setUp(self): """ Creates the test course structure to build course outline tree. """ super(TestMoveItem, self).setUp() self.setup_course() def setup_course(self, default_store=None): """ Helper method to create the course. """ if not default_store: default_store = self.store.default_modulestore.get_modulestore_type() self.course = CourseFactory.create(default_store=default_store) # Create group configurations self.course.user_partitions = [ UserPartition(0, 'first_partition', 'Test Partition', [Group("0", 'alpha'), Group("1", 'beta')]) ] self.store.update_item(self.course, self.user.id) # Create a parent chapter chap1 = self.create_xblock(parent_usage_key=self.course.location, display_name='chapter1', category='chapter') self.chapter_usage_key = self.response_usage_key(chap1) chap2 = self.create_xblock(parent_usage_key=self.course.location, display_name='chapter2', category='chapter') self.chapter2_usage_key = self.response_usage_key(chap2) # Create a sequential seq1 = self.create_xblock(parent_usage_key=self.chapter_usage_key, display_name='seq1', category='sequential') self.seq_usage_key = self.response_usage_key(seq1) seq2 = self.create_xblock(parent_usage_key=self.chapter_usage_key, display_name='seq2', category='sequential') self.seq2_usage_key = self.response_usage_key(seq2) # Create a vertical vert1 = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='vertical1', category='vertical') self.vert_usage_key = self.response_usage_key(vert1) vert2 = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='vertical2', category='vertical') self.vert2_usage_key = self.response_usage_key(vert2) # Create problem and an html component problem1 = self.create_xblock(parent_usage_key=self.vert_usage_key, display_name='problem1', category='problem') self.problem_usage_key = self.response_usage_key(problem1) html1 = self.create_xblock(parent_usage_key=self.vert_usage_key, display_name='html1', category='html') self.html_usage_key = self.response_usage_key(html1) # Create a content experiment resp = self.create_xblock(category='split_test', parent_usage_key=self.vert_usage_key) self.split_test_usage_key = self.response_usage_key(resp) def setup_and_verify_content_experiment(self, partition_id): """ Helper method to set up group configurations to content experiment. Arguments: partition_id (int): User partition id. """ split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) # Initially, no user_partition_id is set, and the split_test has no children. self.assertEqual(split_test.user_partition_id, -1) self.assertEqual(len(split_test.children), 0) # Set group configuration self.client.ajax_post( reverse_usage_url("xblock_handler", self.split_test_usage_key), data={'metadata': {'user_partition_id': str(partition_id)}} ) split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) self.assertEqual(split_test.user_partition_id, partition_id) self.assertEqual(len(split_test.children), len(self.course.user_partitions[partition_id].groups)) return split_test def _move_component(self, source_usage_key, target_usage_key, target_index=None): """ Helper method to send move request and returns the response. Arguments: source_usage_key (BlockUsageLocator): Locator of source item. target_usage_key (BlockUsageLocator): Locator of target parent. target_index (int): If provided, insert source item at the provided index location in target_usage_key item. Returns: resp (JsonResponse): Response after the move operation is complete. """ data = { 'move_source_locator': unicode(source_usage_key), 'parent_locator': unicode(target_usage_key) } if target_index is not None: data['target_index'] = target_index return self.client.patch( reverse('contentstore.views.xblock_handler'), json.dumps(data), content_type='application/json' ) def assert_move_item(self, source_usage_key, target_usage_key, target_index=None): """ Assert move component. Arguments: source_usage_key (BlockUsageLocator): Locator of source item. target_usage_key (BlockUsageLocator): Locator of target parent. target_index (int): If provided, insert source item at the provided index location in target_usage_key item. """ parent_loc = self.store.get_parent_location(source_usage_key) parent = self.get_item_from_modulestore(parent_loc) source_index = _get_source_index(source_usage_key, parent) expected_index = target_index if target_index is not None else source_index response = self._move_component(source_usage_key, target_usage_key, target_index) self.assertEqual(response.status_code, 200) response = json.loads(response.content) self.assertEqual(response['move_source_locator'], unicode(source_usage_key)) self.assertEqual(response['parent_locator'], unicode(target_usage_key)) self.assertEqual(response['source_index'], expected_index) # Verify parent referance has been changed now. new_parent_loc = self.store.get_parent_location(source_usage_key) source_item = self.get_item_from_modulestore(source_usage_key) self.assertEqual(source_item.parent, new_parent_loc) self.assertEqual(new_parent_loc, target_usage_key) self.assertNotEqual(parent_loc, new_parent_loc) # Assert item is present in children list of target parent and not source parent target_parent = self.get_item_from_modulestore(target_usage_key) source_parent = self.get_item_from_modulestore(parent_loc) self.assertIn(source_usage_key, target_parent.children) self.assertNotIn(source_usage_key, source_parent.children) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_move_component(self, store_type): """ Test move component with different xblock types. Arguments: store_type (ModuleStoreEnum.Type): Type of modulestore to create test course in. """ self.setup_course(default_store=store_type) for source_usage_key, target_usage_key in [ (self.html_usage_key, self.vert2_usage_key), (self.vert_usage_key, self.seq2_usage_key), (self.seq_usage_key, self.chapter2_usage_key) ]: self.assert_move_item(source_usage_key, target_usage_key) def test_move_source_index(self): """ Test moving an item to a particular index. """ parent = self.get_item_from_modulestore(self.vert_usage_key) children = parent.get_children() self.assertEqual(len(children), 3) # Create a component within vert2. resp = self.create_xblock(parent_usage_key=self.vert2_usage_key, display_name='html2', category='html') html2_usage_key = self.response_usage_key(resp) # Move html2_usage_key inside vert_usage_key at second position. self.assert_move_item(html2_usage_key, self.vert_usage_key, 1) parent = self.get_item_from_modulestore(self.vert_usage_key) children = parent.get_children() self.assertEqual(len(children), 4) self.assertEqual(children[1].location, html2_usage_key) def test_move_undo(self): """ Test move a component and move it back (undo). """ # Get the initial index of the component parent = self.get_item_from_modulestore(self.vert_usage_key) original_index = _get_source_index(self.html_usage_key, parent) # Move component and verify that response contains initial index response = self._move_component(self.html_usage_key, self.vert2_usage_key) response = json.loads(response.content) self.assertEquals(original_index, response['source_index']) # Verify that new parent has the moved component at the last index. parent = self.get_item_from_modulestore(self.vert2_usage_key) self.assertEqual(self.html_usage_key, parent.children[-1]) # Verify original and new index is different now. source_index = _get_source_index(self.html_usage_key, parent) self.assertNotEquals(original_index, source_index) # Undo Move to the original index, use the source index fetched from the response. response = self._move_component(self.html_usage_key, self.vert_usage_key, response['source_index']) response = json.loads(response.content) self.assertEquals(original_index, response['source_index']) def test_move_large_target_index(self): """ Test moving an item at a large index would generate an error message. """ parent = self.get_item_from_modulestore(self.vert2_usage_key) parent_children_length = len(parent.children) response = self._move_component(self.html_usage_key, self.vert2_usage_key, parent_children_length + 10) self.assertEqual(response.status_code, 400) response = json.loads(response.content) expected_error = 'You can not move {usage_key} at an invalid index ({target_index}).'.format( usage_key=self.html_usage_key, target_index=parent_children_length + 10 ) self.assertEqual(expected_error, response['error']) new_parent_loc = self.store.get_parent_location(self.html_usage_key) self.assertEqual(new_parent_loc, self.vert_usage_key) def test_invalid_move(self): """ Test invalid move. """ parent_loc = self.store.get_parent_location(self.html_usage_key) response = self._move_component(self.html_usage_key, self.seq_usage_key) self.assertEqual(response.status_code, 400) response = json.loads(response.content) expected_error = 'You can not move {source_type} into {target_type}.'.format( source_type=self.html_usage_key.block_type, target_type=self.seq_usage_key.block_type ) self.assertEqual(expected_error, response['error']) new_parent_loc = self.store.get_parent_location(self.html_usage_key) self.assertEqual(new_parent_loc, parent_loc) def test_move_current_parent(self): """ Test that a component can not be moved to it's current parent. """ parent_loc = self.store.get_parent_location(self.html_usage_key) self.assertEqual(parent_loc, self.vert_usage_key) response = self._move_component(self.html_usage_key, self.vert_usage_key) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'Item is already present in target location.') self.assertEqual(self.store.get_parent_location(self.html_usage_key), parent_loc) def test_can_not_move_into_itself(self): """ Test that a component can not be moved to itself. """ library_content = self.create_xblock( parent_usage_key=self.vert_usage_key, display_name='library content block', category='library_content' ) library_content_usage_key = self.response_usage_key(library_content) parent_loc = self.store.get_parent_location(library_content_usage_key) self.assertEqual(parent_loc, self.vert_usage_key) response = self._move_component(library_content_usage_key, library_content_usage_key) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'You can not move an item into itself.') self.assertEqual(self.store.get_parent_location(self.html_usage_key), parent_loc) def test_move_library_content(self): """ Test that library content can be moved to any other valid location. """ library_content = self.create_xblock( parent_usage_key=self.vert_usage_key, display_name='library content block', category='library_content' ) library_content_usage_key = self.response_usage_key(library_content) parent_loc = self.store.get_parent_location(library_content_usage_key) self.assertEqual(parent_loc, self.vert_usage_key) self.assert_move_item(library_content_usage_key, self.vert2_usage_key) def test_move_into_library_content(self): """ Test that a component can be moved into library content. """ library_content = self.create_xblock( parent_usage_key=self.vert_usage_key, display_name='library content block', category='library_content' ) library_content_usage_key = self.response_usage_key(library_content) self.assert_move_item(self.html_usage_key, library_content_usage_key) def test_move_content_experiment(self): """ Test that a content experiment can be moved. """ self.setup_and_verify_content_experiment(0) # Move content experiment self.assert_move_item(self.split_test_usage_key, self.vert2_usage_key) def test_move_content_experiment_components(self): """ Test that component inside content experiment can be moved to any other valid location. """ split_test = self.setup_and_verify_content_experiment(0) # Add html component to Group A. html1 = self.create_xblock( parent_usage_key=split_test.children[0], display_name='html1', category='html' ) html_usage_key = self.response_usage_key(html1) # Move content experiment self.assert_move_item(html_usage_key, self.vert2_usage_key) def test_move_into_content_experiment_groups(self): """ Test that a component can be moved to content experiment groups. """ split_test = self.setup_and_verify_content_experiment(0) self.assert_move_item(self.html_usage_key, split_test.children[0]) def test_can_not_move_into_content_experiment_level(self): """ Test that a component can not be moved directly to content experiment level. """ self.setup_and_verify_content_experiment(0) response = self._move_component(self.html_usage_key, self.split_test_usage_key) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'You can not move an item directly into content experiment.') self.assertEqual(self.store.get_parent_location(self.html_usage_key), self.vert_usage_key) def test_can_not_move_content_experiment_into_its_children(self): """ Test that a content experiment can not be moved inside any of it's children. """ split_test = self.setup_and_verify_content_experiment(0) # Try to move content experiment inside it's child groups. for child_vert_usage_key in split_test.children: response = self._move_component(self.split_test_usage_key, child_vert_usage_key) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'You can not move an item into it\'s child.') self.assertEqual(self.store.get_parent_location(self.split_test_usage_key), self.vert_usage_key) # Create content experiment inside group A and set it's group configuration. resp = self.create_xblock(category='split_test', parent_usage_key=split_test.children[0]) child_split_test_usage_key = self.response_usage_key(resp) self.client.ajax_post( reverse_usage_url("xblock_handler", child_split_test_usage_key), data={'metadata': {'user_partition_id': str(0)}} ) child_split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) # Try to move content experiment further down the level to a child group A nested inside main group A. response = self._move_component(self.split_test_usage_key, child_split_test.children[0]) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'You can not move an item into it\'s child.') self.assertEqual(self.store.get_parent_location(self.split_test_usage_key), self.vert_usage_key) def test_move_invalid_source_index(self): """ Test moving an item to an invalid index. """ target_index = 'test_index' parent_loc = self.store.get_parent_location(self.html_usage_key) response = self._move_component(self.html_usage_key, self.vert2_usage_key, target_index) self.assertEqual(response.status_code, 400) response = json.loads(response.content) error = 'You must provide target_index ({target_index}) as an integer.'.format(target_index=target_index) self.assertEqual(response['error'], error) new_parent_loc = self.store.get_parent_location(self.html_usage_key) self.assertEqual(new_parent_loc, parent_loc) def test_move_no_target_locator(self): """ Test move an item without specifying the target location. """ data = {'move_source_locator': unicode(self.html_usage_key)} with self.assertRaises(InvalidKeyError): self.client.patch( reverse('contentstore.views.xblock_handler'), json.dumps(data), content_type='application/json' ) def test_no_move_source_locator(self): """ Test patch request without providing a move source locator. """ response = self.client.patch( reverse('contentstore.views.xblock_handler') ) self.assertEqual(response.status_code, 400) response = json.loads(response.content) self.assertEqual(response['error'], 'Patch request did not recognise any parameters to handle.') def _verify_validation_message(self, message, expected_message, expected_message_type): """ Verify that the validation message has the expected validation message and type. """ self.assertEqual(message.text, expected_message) self.assertEqual(message.type, expected_message_type) def test_move_component_nonsensical_access_restriction_validation(self): """ Test that moving a component with non-contradicting access restrictions into a unit that has contradicting access restrictions brings up the nonsensical access validation message and that the message does not show up when moved into a unit where the component's access settings do not contradict the unit's access settings. """ group1 = self.course.user_partitions[0].groups[0] group2 = self.course.user_partitions[0].groups[1] vert2 = self.store.get_item(self.vert2_usage_key) html = self.store.get_item(self.html_usage_key) # Inject mock partition service as obtaining the course from the draft modulestore # (which is the default for these tests) does not work. partitions_service = MockPartitionService( self.course, course_id=self.course.id, ) html.runtime._services['partitions'] = partitions_service # Set access settings so html will contradict vert2 when moved into that unit vert2.group_access = {self.course.user_partitions[0].id: [group1.id]} html.group_access = {self.course.user_partitions[0].id: [group2.id]} self.store.update_item(html, self.user.id) self.store.update_item(vert2, self.user.id) # Verify that there is no warning when html is in a non contradicting unit validation = html.validate() self.assertEqual(len(validation.messages), 0) # Now move it and confirm that the html component has been moved into vertical 2 self.assert_move_item(self.html_usage_key, self.vert2_usage_key) html.parent = self.vert2_usage_key self.store.update_item(html, self.user.id) validation = html.validate() self.assertEqual(len(validation.messages), 1) self._verify_validation_message( validation.messages[0], NONSENSICAL_ACCESS_RESTRICTION, ValidationMessage.ERROR, ) # Move the html component back and confirm that the warning is gone again self.assert_move_item(self.html_usage_key, self.vert_usage_key) html.parent = self.vert_usage_key self.store.update_item(html, self.user.id) validation = html.validate() self.assertEqual(len(validation.messages), 0) @patch('contentstore.views.item.log') def test_move_logging(self, mock_logger): """ Test logging when an item is successfully moved. Arguments: mock_logger (object): A mock logger object. """ insert_at = 0 self.assert_move_item(self.html_usage_key, self.vert2_usage_key, insert_at) mock_logger.info.assert_called_with( 'MOVE: %s moved from %s to %s at %d index', unicode(self.html_usage_key), unicode(self.vert_usage_key), unicode(self.vert2_usage_key), insert_at ) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_move_and_discard_changes(self, store_type): """ Verifies that discard changes operation brings moved component back to source location and removes the component from target location. Arguments: store_type (ModuleStoreEnum.Type): Type of modulestore to create test course in. """ self.setup_course(default_store=store_type) old_parent_loc = self.store.get_parent_location(self.html_usage_key) # Check that old_parent_loc is not yet published. self.assertFalse(self.store.has_item(old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only)) # Publish old_parent_loc unit self.client.ajax_post( reverse_usage_url("xblock_handler", old_parent_loc), data={'publish': 'make_public'} ) # Check that old_parent_loc is now published. self.assertTrue(self.store.has_item(old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only)) self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) # Move component html_usage_key in vert2_usage_key self.assert_move_item(self.html_usage_key, self.vert2_usage_key) # Check old_parent_loc becomes in draft mode now. self.assertTrue(self.store.has_changes(self.store.get_item(old_parent_loc))) # Now discard changes in old_parent_loc self.client.ajax_post( reverse_usage_url("xblock_handler", old_parent_loc), data={'publish': 'discard_changes'} ) # Check that old_parent_loc now is reverted to publish. Changes discarded, html_usage_key moved back. self.assertTrue(self.store.has_item(old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only)) self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) # Now source item should be back in the old parent. source_item = self.get_item_from_modulestore(self.html_usage_key) self.assertEqual(source_item.parent, old_parent_loc) self.assertEqual(self.store.get_parent_location(self.html_usage_key), source_item.parent) # Also, check that item is not present in target parent but in source parent target_parent = self.get_item_from_modulestore(self.vert2_usage_key) source_parent = self.get_item_from_modulestore(old_parent_loc) self.assertIn(self.html_usage_key, source_parent.children) self.assertNotIn(self.html_usage_key, target_parent.children) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_move_item_not_found(self, store_type=ModuleStoreEnum.Type.mongo): """ Test that an item not found exception raised when an item is not found when getting the item. Arguments: store_type (ModuleStoreEnum.Type): Type of modulestore to create test course in. """ self.setup_course(default_store=store_type) data = { 'move_source_locator': unicode(self.usage_key.course_key.make_usage_key('html', 'html_test')), 'parent_locator': unicode(self.vert2_usage_key) } with self.assertRaises(ItemNotFoundError): self.client.patch( reverse('contentstore.views.xblock_handler'), json.dumps(data), content_type='application/json' ) class TestDuplicateItemWithAsides(ItemTest, DuplicateHelper): """ Test the duplicate method for blocks with asides. """ MODULESTORE = TEST_DATA_SPLIT_MODULESTORE def setUp(self): """ Creates the test course structure and a few components to 'duplicate'. """ super(TestDuplicateItemWithAsides, self).setUp() # Create a parent chapter resp = self.create_xblock(parent_usage_key=self.usage_key, category='chapter') self.chapter_usage_key = self.response_usage_key(resp) # create a sequential containing a problem and an html component resp = self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential') self.seq_usage_key = self.response_usage_key(resp) # create problem and an html component resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate='multiplechoice.yaml') self.problem_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='html') self.html_usage_key = self.response_usage_key(resp) @XBlockAside.register_temp_plugin(AsideTest, 'test_aside') @patch('xmodule.modulestore.split_mongo.caching_descriptor_system.CachingDescriptorSystem.applicable_aside_types', lambda self, block: ['test_aside']) def test_duplicate_equality_with_asides(self): """ Tests that a duplicated xblock aside is identical to the original """ def create_aside(usage_key, block_type): """ Helper function to create aside """ item = self.get_item_from_modulestore(usage_key) key_store = DictKeyValueStore() field_data = KvsFieldData(key_store) runtime = TestRuntime(services={'field-data': field_data}) # pylint: disable=abstract-class-instantiated def_id = runtime.id_generator.create_definition(block_type) usage_id = runtime.id_generator.create_usage(def_id) aside = AsideTest(scope_ids=ScopeIds('user', block_type, def_id, usage_id), runtime=runtime) aside.field11 = '%s_new_value11' % block_type aside.field12 = '%s_new_value12' % block_type aside.field13 = '%s_new_value13' % block_type self.store.update_item(item, self.user.id, asides=[aside]) create_aside(self.html_usage_key, 'html') create_aside(self.problem_usage_key, 'problem') create_aside(self.seq_usage_key, 'seq') create_aside(self.chapter_usage_key, 'chapter') self._duplicate_and_verify(self.problem_usage_key, self.seq_usage_key, check_asides=True) self._duplicate_and_verify(self.html_usage_key, self.seq_usage_key, check_asides=True) self._duplicate_and_verify(self.seq_usage_key, self.chapter_usage_key, check_asides=True) class TestEditItemSetup(ItemTest): """ Setup for xblock update tests. """ def setUp(self): """ Creates the test course structure and a couple problems to 'edit'. """ super(TestEditItemSetup, self).setUp() # create a chapter display_name = 'chapter created' resp = self.create_xblock(display_name=display_name, category='chapter') chap_usage_key = self.response_usage_key(resp) # create 2 sequentials resp = self.create_xblock(parent_usage_key=chap_usage_key, category='sequential') self.seq_usage_key = self.response_usage_key(resp) self.seq_update_url = reverse_usage_url("xblock_handler", self.seq_usage_key) resp = self.create_xblock(parent_usage_key=chap_usage_key, category='sequential') self.seq2_usage_key = self.response_usage_key(resp) self.seq2_update_url = reverse_usage_url("xblock_handler", self.seq2_usage_key) # create problem w/ boilerplate template_id = 'multiplechoice.yaml' resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate=template_id) self.problem_usage_key = self.response_usage_key(resp) self.problem_update_url = reverse_usage_url("xblock_handler", self.problem_usage_key) self.course_update_url = reverse_usage_url("xblock_handler", self.usage_key) class TestEditItem(TestEditItemSetup): """ Test xblock update. """ def test_delete_field(self): """ Sending null in for a field 'deletes' it """ self.client.ajax_post( self.problem_update_url, data={'metadata': {'rerandomize': 'onreset'}} ) problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertEqual(problem.rerandomize, 'onreset') self.client.ajax_post( self.problem_update_url, data={'metadata': {'rerandomize': None}} ) problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertEqual(problem.rerandomize, 'never') def test_null_field(self): """ Sending null in for a field 'deletes' it """ problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertIsNotNone(problem.markdown) self.client.ajax_post( self.problem_update_url, data={'nullout': ['markdown']} ) problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertIsNone(problem.markdown) def test_date_fields(self): """ Test setting due & start dates on sequential """ sequential = self.get_item_from_modulestore(self.seq_usage_key) self.assertIsNone(sequential.due) self.client.ajax_post( self.seq_update_url, data={'metadata': {'due': '2010-11-22T04:00Z'}} ) sequential = self.get_item_from_modulestore(self.seq_usage_key) self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) self.client.ajax_post( self.seq_update_url, data={'metadata': {'start': '2010-09-12T14:00Z'}} ) sequential = self.get_item_from_modulestore(self.seq_usage_key) self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) self.assertEqual(sequential.start, datetime(2010, 9, 12, 14, 0, tzinfo=UTC)) def test_update_generic_fields(self): new_display_name = 'New Display Name' new_max_attempts = 2 self.client.ajax_post( self.problem_update_url, data={ 'fields': { 'display_name': new_display_name, 'max_attempts': new_max_attempts, } } ) problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertEqual(problem.display_name, new_display_name) self.assertEqual(problem.max_attempts, new_max_attempts) def test_delete_child(self): """ Test deleting a child. """ # Create 2 children of main course. resp_1 = self.create_xblock(display_name='child 1', category='chapter') resp_2 = self.create_xblock(display_name='child 2', category='chapter') chapter1_usage_key = self.response_usage_key(resp_1) chapter2_usage_key = self.response_usage_key(resp_2) course = self.get_item_from_modulestore(self.usage_key) self.assertIn(chapter1_usage_key, course.children) self.assertIn(chapter2_usage_key, course.children) # Remove one child from the course. resp = self.client.delete(reverse_usage_url("xblock_handler", chapter1_usage_key)) self.assertEqual(resp.status_code, 204) # Verify that the child is removed. course = self.get_item_from_modulestore(self.usage_key) self.assertNotIn(chapter1_usage_key, course.children) self.assertIn(chapter2_usage_key, course.children) def test_reorder_children(self): """ Test reordering children that can be in the draft store. """ # Create 2 child units and re-order them. There was a bug about @draft getting added # to the IDs. unit_1_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical') unit_2_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical') unit1_usage_key = self.response_usage_key(unit_1_resp) unit2_usage_key = self.response_usage_key(unit_2_resp) # The sequential already has a child defined in the setUp (a problem). # Children must be on the sequential to reproduce the original bug, # as it is important that the parent (sequential) NOT be in the draft store. children = self.get_item_from_modulestore(self.seq_usage_key).children self.assertEqual(unit1_usage_key, children[1]) self.assertEqual(unit2_usage_key, children[2]) resp = self.client.ajax_post( self.seq_update_url, data={'children': [unicode(self.problem_usage_key), unicode(unit2_usage_key), unicode(unit1_usage_key)]} ) self.assertEqual(resp.status_code, 200) children = self.get_item_from_modulestore(self.seq_usage_key).children self.assertEqual(self.problem_usage_key, children[0]) self.assertEqual(unit1_usage_key, children[2]) self.assertEqual(unit2_usage_key, children[1]) def test_move_parented_child(self): """ Test moving a child from one Section to another """ unit_1_key = self.response_usage_key( self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical', display_name='unit 1') ) unit_2_key = self.response_usage_key( self.create_xblock(parent_usage_key=self.seq2_usage_key, category='vertical', display_name='unit 2') ) # move unit 1 from sequential1 to sequential2 resp = self.client.ajax_post( self.seq2_update_url, data={'children': [unicode(unit_1_key), unicode(unit_2_key)]} ) self.assertEqual(resp.status_code, 200) # verify children self.assertListEqual( self.get_item_from_modulestore(self.seq2_usage_key).children, [unit_1_key, unit_2_key], ) self.assertListEqual( self.get_item_from_modulestore(self.seq_usage_key).children, [self.problem_usage_key], # problem child created in setUp ) def test_move_orphaned_child_error(self): """ Test moving an orphan returns an error """ unit_1_key = self.store.create_item(self.user.id, self.course_key, 'vertical', 'unit1').location # adding orphaned unit 1 should return an error resp = self.client.ajax_post( self.seq2_update_url, data={'children': [unicode(unit_1_key)]} ) self.assertEqual(resp.status_code, 400) self.assertIn("Invalid data, possibly caused by concurrent authors", resp.content) # verify children self.assertListEqual( self.get_item_from_modulestore(self.seq2_usage_key).children, [] ) def test_move_child_creates_orphan_error(self): """ Test creating an orphan returns an error """ unit_1_key = self.response_usage_key( self.create_xblock(parent_usage_key=self.seq2_usage_key, category='vertical', display_name='unit 1') ) unit_2_key = self.response_usage_key( self.create_xblock(parent_usage_key=self.seq2_usage_key, category='vertical', display_name='unit 2') ) # remove unit 2 should return an error resp = self.client.ajax_post( self.seq2_update_url, data={'children': [unicode(unit_1_key)]} ) self.assertEqual(resp.status_code, 400) self.assertIn("Invalid data, possibly caused by concurrent authors", resp.content) # verify children self.assertListEqual( self.get_item_from_modulestore(self.seq2_usage_key).children, [unit_1_key, unit_2_key] ) def _is_location_published(self, location): """ Returns whether or not the item with given location has a published version. """ return modulestore().has_item(location, revision=ModuleStoreEnum.RevisionOption.published_only) def _verify_published_with_no_draft(self, location): """ Verifies the item with given location has a published version and no draft (unpublished changes). """ self.assertTrue(self._is_location_published(location)) self.assertFalse(modulestore().has_changes(modulestore().get_item(location))) def _verify_published_with_draft(self, location): """ Verifies the item with given location has a published version and also a draft version (unpublished changes). """ self.assertTrue(self._is_location_published(location)) self.assertTrue(modulestore().has_changes(modulestore().get_item(location))) def test_make_public(self): """ Test making a private problem public (publishing it). """ # When the problem is first created, it is only in draft (because of its category). self.assertFalse(self._is_location_published(self.problem_usage_key)) self.client.ajax_post( self.problem_update_url, data={'publish': 'make_public'} ) self._verify_published_with_no_draft(self.problem_usage_key) def test_make_draft(self): """ Test creating a draft version of a public problem. """ self._make_draft_content_different_from_published() def test_revert_to_published(self): """ Test reverting draft content to published """ self._make_draft_content_different_from_published() self.client.ajax_post( self.problem_update_url, data={'publish': 'discard_changes'} ) self._verify_published_with_no_draft(self.problem_usage_key) published = modulestore().get_item(self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only) self.assertIsNone(published.due) def test_republish(self): """ Test republishing an item. """ new_display_name = 'New Display Name' # When the problem is first created, it is only in draft (because of its category). self.assertFalse(self._is_location_published(self.problem_usage_key)) # Republishing when only in draft will update the draft but not cause a public item to be created. self.client.ajax_post( self.problem_update_url, data={ 'publish': 'republish', 'metadata': { 'display_name': new_display_name } } ) self.assertFalse(self._is_location_published(self.problem_usage_key)) draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertEqual(draft.display_name, new_display_name) # Publish the item self.client.ajax_post( self.problem_update_url, data={'publish': 'make_public'} ) # Now republishing should update the published version new_display_name_2 = 'New Display Name 2' self.client.ajax_post( self.problem_update_url, data={ 'publish': 'republish', 'metadata': { 'display_name': new_display_name_2 } } ) self._verify_published_with_no_draft(self.problem_usage_key) published = modulestore().get_item( self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only ) self.assertEqual(published.display_name, new_display_name_2) def test_direct_only_categories_not_republished(self): """Verify that republish is ignored for items in DIRECT_ONLY_CATEGORIES""" # Create a vertical child with published and unpublished versions. # If the parent sequential is not re-published, then the child problem should also not be re-published. resp = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='vertical', category='vertical') vertical_usage_key = self.response_usage_key(resp) vertical_update_url = reverse_usage_url('xblock_handler', vertical_usage_key) self.client.ajax_post(vertical_update_url, data={'publish': 'make_public'}) self.client.ajax_post(vertical_update_url, data={'metadata': {'display_name': 'New Display Name'}}) self._verify_published_with_draft(self.seq_usage_key) self.client.ajax_post(self.seq_update_url, data={'publish': 'republish'}) self._verify_published_with_draft(self.seq_usage_key) def _make_draft_content_different_from_published(self): """ Helper method to create different draft and published versions of a problem. """ # Make problem public. self.client.ajax_post( self.problem_update_url, data={'publish': 'make_public'} ) self._verify_published_with_no_draft(self.problem_usage_key) published = modulestore().get_item(self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only) # Update the draft version and check that published is different. self.client.ajax_post( self.problem_update_url, data={'metadata': {'due': '2077-10-10T04:00Z'}} ) updated_draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertEqual(updated_draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) self.assertIsNone(published.due) # Fetch the published version again to make sure the due date is still unset. published = modulestore().get_item(published.location, revision=ModuleStoreEnum.RevisionOption.published_only) self.assertIsNone(published.due) def test_make_public_with_update(self): """ Update a problem and make it public at the same time. """ self.client.ajax_post( self.problem_update_url, data={ 'metadata': {'due': '2077-10-10T04:00Z'}, 'publish': 'make_public' } ) published = self.get_item_from_modulestore(self.problem_usage_key) self.assertEqual(published.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) def test_published_and_draft_contents_with_update(self): """ Create a draft and publish it then modify the draft and check that published content is not modified """ # Make problem public. self.client.ajax_post( self.problem_update_url, data={'publish': 'make_public'} ) self._verify_published_with_no_draft(self.problem_usage_key) published = modulestore().get_item(self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only) # Now make a draft self.client.ajax_post( self.problem_update_url, data={ 'id': unicode(self.problem_usage_key), 'metadata': {}, 'data': "<p>Problem content draft.</p>" } ) # Both published and draft content should be different draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertNotEqual(draft.data, published.data) # Get problem by 'xblock_handler' view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDENT_VIEW}) resp = self.client.get(view_url, HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, 200) # Activate the editing view view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDIO_VIEW}) resp = self.client.get(view_url, HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, 200) # Both published and draft content should still be different draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True) self.assertNotEqual(draft.data, published.data) # Fetch the published version again to make sure the data is correct. published = modulestore().get_item(published.location, revision=ModuleStoreEnum.RevisionOption.published_only) self.assertNotEqual(draft.data, published.data) def test_publish_states_of_nested_xblocks(self): """ Test publishing of a unit page containing a nested xblock """ resp = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='Test Unit', category='vertical') unit_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=unit_usage_key, category='wrapper') wrapper_usage_key = self.response_usage_key(resp) resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='html') html_usage_key = self.response_usage_key(resp) # The unit and its children should be private initially unit_update_url = reverse_usage_url('xblock_handler', unit_usage_key) self.assertFalse(self._is_location_published(unit_usage_key)) self.assertFalse(self._is_location_published(html_usage_key)) # Make the unit public and verify that the problem is also made public resp = self.client.ajax_post( unit_update_url, data={'publish': 'make_public'} ) self.assertEqual(resp.status_code, 200) self._verify_published_with_no_draft(unit_usage_key) self._verify_published_with_no_draft(html_usage_key) # Make a draft for the unit and verify that the problem also has a draft resp = self.client.ajax_post( unit_update_url, data={ 'id': unicode(unit_usage_key), 'metadata': {}, } ) self.assertEqual(resp.status_code, 200) self._verify_published_with_draft(unit_usage_key) self._verify_published_with_draft(html_usage_key) def test_field_value_errors(self): """ Test that if the user's input causes a ValueError on an XBlock field, we provide a friendly error message back to the user. """ response = self.create_xblock(parent_usage_key=self.seq_usage_key, category='video') video_usage_key = self.response_usage_key(response) update_url = reverse_usage_url('xblock_handler', video_usage_key) response = self.client.ajax_post( update_url, data={ 'id': unicode(video_usage_key), 'metadata': { 'saved_video_position': "Not a valid relative time", }, } ) self.assertEqual(response.status_code, 400) parsed = json.loads(response.content) self.assertIn("error", parsed) self.assertIn("Incorrect RelativeTime value", parsed["error"]) # See xmodule/fields.py class TestEditItemSplitMongo(TestEditItemSetup): """ Tests for EditItem running on top of the SplitMongoModuleStore. """ MODULESTORE = TEST_DATA_SPLIT_MODULESTORE def test_editing_view_wrappers(self): """ Verify that the editing view only generates a single wrapper, no matter how many times it's loaded Exposes: PLAT-417 """ view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDIO_VIEW}) for __ in xrange(3): resp = self.client.get(view_url, HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, 200) content = json.loads(resp.content) self.assertEqual(len(PyQuery(content['html'])('.xblock-{}'.format(STUDIO_VIEW))), 1) class TestEditSplitModule(ItemTest): """ Tests around editing instances of the split_test module. """ def setUp(self): super(TestEditSplitModule, self).setUp() self.user = UserFactory() self.first_user_partition_group_1 = Group(unicode(MINIMUM_STATIC_PARTITION_ID + 1), 'alpha') self.first_user_partition_group_2 = Group(unicode(MINIMUM_STATIC_PARTITION_ID + 2), 'beta') self.first_user_partition = UserPartition( MINIMUM_STATIC_PARTITION_ID, 'first_partition', 'First Partition', [self.first_user_partition_group_1, self.first_user_partition_group_2] ) # There is a test point below (test_create_groups) that purposefully wants the group IDs # of the 2 partitions to overlap (which is not something that normally happens). self.second_user_partition_group_1 = Group(unicode(MINIMUM_STATIC_PARTITION_ID + 1), 'Group 1') self.second_user_partition_group_2 = Group(unicode(MINIMUM_STATIC_PARTITION_ID + 2), 'Group 2') self.second_user_partition_group_3 = Group(unicode(MINIMUM_STATIC_PARTITION_ID + 3), 'Group 3') self.second_user_partition = UserPartition( MINIMUM_STATIC_PARTITION_ID + 10, 'second_partition', 'Second Partition', [ self.second_user_partition_group_1, self.second_user_partition_group_2, self.second_user_partition_group_3 ] ) self.course.user_partitions = [ self.first_user_partition, self.second_user_partition ] self.store.update_item(self.course, self.user.id) root_usage_key = self._create_vertical() resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key) self.split_test_usage_key = self.response_usage_key(resp) self.split_test_update_url = reverse_usage_url("xblock_handler", self.split_test_usage_key) self.request_factory = RequestFactory() self.request = self.request_factory.get('/dummy-url') self.request.user = self.user def _update_partition_id(self, partition_id): """ Helper method that sets the user_partition_id to the supplied value. The updated split_test instance is returned. """ self.client.ajax_post( self.split_test_update_url, # Even though user_partition_id is Scope.content, it will get saved by the Studio editor as # metadata. The code in item.py will update the field correctly, even though it is not the # expected scope. data={'metadata': {'user_partition_id': str(partition_id)}} ) # Verify the partition_id was saved. split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) self.assertEqual(partition_id, split_test.user_partition_id) return split_test def _assert_children(self, expected_number): """ Verifies the number of children of the split_test instance. """ split_test = self.get_item_from_modulestore(self.split_test_usage_key, True) self.assertEqual(expected_number, len(split_test.children)) return split_test def test_create_groups(self): """ Test that verticals are created for the configuration groups when a spit test module is edited. """ split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) # Initially, no user_partition_id is set, and the split_test has no children. self.assertEqual(-1, split_test.user_partition_id) self.assertEqual(0, len(split_test.children)) # Set the user_partition_id to match the first user_partition. split_test = self._update_partition_id(self.first_user_partition.id) # Verify that child verticals have been set to match the groups self.assertEqual(2, len(split_test.children)) vertical_0 = self.get_item_from_modulestore(split_test.children[0], verify_is_draft=True) vertical_1 = self.get_item_from_modulestore(split_test.children[1], verify_is_draft=True) self.assertEqual("vertical", vertical_0.category) self.assertEqual("vertical", vertical_1.category) self.assertEqual("Group ID " + unicode(MINIMUM_STATIC_PARTITION_ID + 1), vertical_0.display_name) self.assertEqual("Group ID " + unicode(MINIMUM_STATIC_PARTITION_ID + 2), vertical_1.display_name) # Verify that the group_id_to_child mapping is correct. self.assertEqual(2, len(split_test.group_id_to_child)) self.assertEqual(vertical_0.location, split_test.group_id_to_child[str(self.first_user_partition_group_1.id)]) self.assertEqual(vertical_1.location, split_test.group_id_to_child[str(self.first_user_partition_group_2.id)]) def test_split_xblock_info_group_name(self): """ Test that concise outline for split test component gives display name as group name. """ split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True) # Initially, no user_partition_id is set, and the split_test has no children. self.assertEqual(split_test.user_partition_id, -1) self.assertEqual(len(split_test.children), 0) # Set the user_partition_id to match the first user_partition. split_test = self._update_partition_id(self.first_user_partition.id) # Verify that child verticals have been set to match the groups self.assertEqual(len(split_test.children), 2) # Get xblock outline xblock_info = create_xblock_info( split_test, is_concise=True, include_child_info=True, include_children_predicate=lambda xblock: xblock.has_children, course=self.course, user=self.request.user ) self.assertEqual(xblock_info['child_info']['children'][0]['display_name'], 'alpha') self.assertEqual(xblock_info['child_info']['children'][1]['display_name'], 'beta') def test_change_user_partition_id(self): """ Test what happens when the user_partition_id is changed to a different groups group configuration. """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) self.assertEqual(2, len(split_test.children)) initial_vertical_0_location = split_test.children[0] initial_vertical_1_location = split_test.children[1] # Set to second group configuration split_test = self._update_partition_id(self.second_user_partition.id) # We don't remove existing children. self.assertEqual(5, len(split_test.children)) self.assertEqual(initial_vertical_0_location, split_test.children[0]) self.assertEqual(initial_vertical_1_location, split_test.children[1]) vertical_0 = self.get_item_from_modulestore(split_test.children[2], verify_is_draft=True) vertical_1 = self.get_item_from_modulestore(split_test.children[3], verify_is_draft=True) vertical_2 = self.get_item_from_modulestore(split_test.children[4], verify_is_draft=True) # Verify that the group_id_to child mapping is correct. self.assertEqual(3, len(split_test.group_id_to_child)) self.assertEqual(vertical_0.location, split_test.group_id_to_child[str(self.second_user_partition_group_1.id)]) self.assertEqual(vertical_1.location, split_test.group_id_to_child[str(self.second_user_partition_group_2.id)]) self.assertEqual(vertical_2.location, split_test.group_id_to_child[str(self.second_user_partition_group_3.id)]) self.assertNotEqual(initial_vertical_0_location, vertical_0.location) self.assertNotEqual(initial_vertical_1_location, vertical_1.location) def test_change_same_user_partition_id(self): """ Test that nothing happens when the user_partition_id is set to the same value twice. """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) self.assertEqual(2, len(split_test.children)) initial_group_id_to_child = split_test.group_id_to_child # Set again to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) self.assertEqual(2, len(split_test.children)) self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) def test_change_non_existent_user_partition_id(self): """ Test that nothing happens when the user_partition_id is set to a value that doesn't exist. The user_partition_id will be updated, but children and group_id_to_child map will not change. """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) self.assertEqual(2, len(split_test.children)) initial_group_id_to_child = split_test.group_id_to_child # Set to an group configuration that doesn't exist. split_test = self._update_partition_id(-50) self.assertEqual(2, len(split_test.children)) self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) def test_add_groups(self): """ Test the "fix up behavior" when groups are missing (after a group is added to a group configuration). This test actually belongs over in common, but it relies on a mutable modulestore. TODO: move tests that can go over to common after the mixed modulestore work is done. # pylint: disable=fixme """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) # Add a group to the first group configuration. new_group_id = "1002" split_test.user_partitions = [ UserPartition( self.first_user_partition.id, 'first_partition', 'First Partition', [self.first_user_partition_group_1, self.first_user_partition_group_2, Group(new_group_id, 'pie')] ) ] self.store.update_item(split_test, self.user.id) # group_id_to_child and children have not changed yet. split_test = self._assert_children(2) group_id_to_child = split_test.group_id_to_child.copy() self.assertEqual(2, len(group_id_to_child)) # Test environment and Studio use different module systems # (CachingDescriptorSystem is used in tests, PreviewModuleSystem in Studio). # CachingDescriptorSystem doesn't have user service, that's needed for # SplitTestModule. So, in this line of code we add this service manually. split_test.runtime._services['user'] = DjangoXBlockUserService(self.user) # pylint: disable=protected-access # Call add_missing_groups method to add the missing group. split_test.add_missing_groups(self.request) split_test = self._assert_children(3) self.assertNotEqual(group_id_to_child, split_test.group_id_to_child) group_id_to_child = split_test.group_id_to_child self.assertEqual(split_test.children[2], group_id_to_child[new_group_id]) # Call add_missing_groups again -- it should be a no-op. split_test.add_missing_groups(self.request) split_test = self._assert_children(3) self.assertEqual(group_id_to_child, split_test.group_id_to_child) @ddt.ddt class TestComponentHandler(TestCase): def setUp(self): super(TestComponentHandler, self).setUp() self.request_factory = RequestFactory() patcher = patch('contentstore.views.component.modulestore') self.modulestore = patcher.start() self.addCleanup(patcher.stop) # component_handler calls modulestore.get_item to get the descriptor of the requested xBlock. # Here, we mock the return value of modulestore.get_item so it can be used to mock the handler # of the xBlock descriptor. self.descriptor = self.modulestore.return_value.get_item.return_value self.usage_key_string = unicode( Location('dummy_org', 'dummy_course', 'dummy_run', 'dummy_category', 'dummy_name') ) self.user = UserFactory() self.request = self.request_factory.get('/dummy-url') self.request.user = self.user def test_invalid_handler(self): self.descriptor.handle.side_effect = NoSuchHandlerError with self.assertRaises(Http404): component_handler(self.request, self.usage_key_string, 'invalid_handler') @ddt.data('GET', 'POST', 'PUT', 'DELETE') def test_request_method(self, method): def check_handler(handler, request, suffix): self.assertEquals(request.method, method) return Response() self.descriptor.handle = check_handler # Have to use the right method to create the request to get the HTTP method that we want req_factory_method = getattr(self.request_factory, method.lower()) request = req_factory_method('/dummy-url') request.user = self.user component_handler(request, self.usage_key_string, 'dummy_handler') @ddt.data(200, 404, 500) def test_response_code(self, status_code): def create_response(handler, request, suffix): return Response(status_code=status_code) self.descriptor.handle = create_response self.assertEquals(component_handler(self.request, self.usage_key_string, 'dummy_handler').status_code, status_code) class TestComponentTemplates(CourseTestCase): """ Unit tests for the generation of the component templates for a course. """ def setUp(self): super(TestComponentTemplates, self).setUp() # Advanced Module support levels. XBlockStudioConfiguration.objects.create(name='poll', enabled=True, support_level="fs") XBlockStudioConfiguration.objects.create(name='survey', enabled=True, support_level="ps") XBlockStudioConfiguration.objects.create(name='annotatable', enabled=True, support_level="us") # Basic component support levels. XBlockStudioConfiguration.objects.create(name='html', enabled=True, support_level="fs") XBlockStudioConfiguration.objects.create(name='discussion', enabled=True, support_level="ps") XBlockStudioConfiguration.objects.create(name='problem', enabled=True, support_level="us") XBlockStudioConfiguration.objects.create(name='video', enabled=True, support_level="us") # XBlock masquerading as a problem XBlockStudioConfiguration.objects.create(name='openassessment', enabled=True, support_level="us") XBlockStudioConfiguration.objects.create(name='drag-and-drop-v2', enabled=True, support_level="fs") self.templates = get_component_templates(self.course) def get_templates_of_type(self, template_type): """ Returns the templates for the specified type, or None if none is found. """ template_dict = next((template for template in self.templates if template.get('type') == template_type), None) return template_dict.get('templates') if template_dict else None def get_template(self, templates, display_name): """ Returns the template which has the specified display name. """ return next((template for template in templates if template.get('display_name') == display_name), None) def test_basic_components(self): """ Test the handling of the basic component templates. """ self._verify_basic_component("discussion", "Discussion") self._verify_basic_component("video", "Video") self.assertGreater(self.get_templates_of_type('html'), 0) self.assertGreater(self.get_templates_of_type('problem'), 0) self.assertIsNone(self.get_templates_of_type('advanced')) # Now fully disable video through XBlockConfiguration XBlockConfiguration.objects.create(name='video', enabled=False) self.templates = get_component_templates(self.course) self.assertIsNone(self.get_templates_of_type('video')) def test_basic_components_support_levels(self): """ Test that support levels can be set on basic component templates. """ XBlockStudioConfigurationFlag.objects.create(enabled=True) self.templates = get_component_templates(self.course) self._verify_basic_component("discussion", "Discussion", "ps") self.assertEqual([], self.get_templates_of_type("video")) supported_problem_templates = [ { 'boilerplate_name': None, 'category': 'drag-and-drop-v2', 'display_name': u'Drag and Drop', 'hinted': False, 'support_level': u'fs', 'tab': 'advanced' } ] self.assertEqual(supported_problem_templates, self.get_templates_of_type("problem")) self.course.allow_unsupported_xblocks = True self.templates = get_component_templates(self.course) self._verify_basic_component("video", "Video", "us") problem_templates = self.get_templates_of_type('problem') problem_no_boilerplate = self.get_template(problem_templates, u'Blank Advanced Problem') self.assertIsNotNone(problem_no_boilerplate) self.assertEqual('us', problem_no_boilerplate['support_level']) # Now fully disable video through XBlockConfiguration XBlockConfiguration.objects.create(name='video', enabled=False) self.templates = get_component_templates(self.course) self.assertIsNone(self.get_templates_of_type('video')) def test_advanced_components(self): """ Test the handling of advanced component templates. """ self.course.advanced_modules.append('word_cloud') self.templates = get_component_templates(self.course) advanced_templates = self.get_templates_of_type('advanced') self.assertEqual(len(advanced_templates), 1) world_cloud_template = advanced_templates[0] self.assertEqual(world_cloud_template.get('category'), 'word_cloud') self.assertEqual(world_cloud_template.get('display_name'), u'Word cloud') self.assertIsNone(world_cloud_template.get('boilerplate_name', None)) # Verify that non-advanced components are not added twice self.course.advanced_modules.append('video') self.course.advanced_modules.append('openassessment') self.templates = get_component_templates(self.course) advanced_templates = self.get_templates_of_type('advanced') self.assertEqual(len(advanced_templates), 1) only_template = advanced_templates[0] self.assertNotEqual(only_template.get('category'), 'video') self.assertNotEqual(only_template.get('category'), 'openassessment') # Now fully disable word_cloud through XBlockConfiguration XBlockConfiguration.objects.create(name='word_cloud', enabled=False) self.templates = get_component_templates(self.course) self.assertIsNone(self.get_templates_of_type('advanced')) def test_advanced_problems(self): """ Test the handling of advanced problem templates. """ problem_templates = self.get_templates_of_type('problem') circuit_template = self.get_template(problem_templates, u'Circuit Schematic Builder') self.assertIsNotNone(circuit_template) self.assertEqual(circuit_template.get('category'), 'problem') self.assertEqual(circuit_template.get('boilerplate_name'), 'circuitschematic.yaml') def test_deprecated_no_advance_component_button(self): """ Test that there will be no `Advanced` button on unit page if xblocks have disabled Studio support given that they are the only modules in `Advanced Module List` """ # Update poll and survey to have "enabled=False". XBlockStudioConfiguration.objects.create(name='poll', enabled=False, support_level="fs") XBlockStudioConfiguration.objects.create(name='survey', enabled=False, support_level="fs") XBlockStudioConfigurationFlag.objects.create(enabled=True) self.course.advanced_modules.extend(['poll', 'survey']) templates = get_component_templates(self.course) button_names = [template['display_name'] for template in templates] self.assertNotIn('Advanced', button_names) def test_cannot_create_deprecated_problems(self): """ Test that xblocks that have Studio support disabled do not show on the "new component" menu. """ # Update poll to have "enabled=False". XBlockStudioConfiguration.objects.create(name='poll', enabled=False, support_level="fs") XBlockStudioConfigurationFlag.objects.create(enabled=True) self.course.advanced_modules.extend(['annotatable', 'poll', 'survey']) # Annotatable doesn't show up because it is unsupported (in test setUp). self._verify_advanced_xblocks(['Survey'], ['ps']) # Now enable unsupported components. self.course.allow_unsupported_xblocks = True self._verify_advanced_xblocks(['Annotation', 'Survey'], ['us', 'ps']) # Now disable Annotatable completely through XBlockConfiguration XBlockConfiguration.objects.create(name='annotatable', enabled=False) self._verify_advanced_xblocks(['Survey'], ['ps']) def test_create_support_level_flag_off(self): """ Test that we can create any advanced xblock (that isn't completely disabled through XBlockConfiguration) if XBlockStudioConfigurationFlag is False. """ XBlockStudioConfigurationFlag.objects.create(enabled=False) self.course.advanced_modules.extend(['annotatable', 'survey']) self._verify_advanced_xblocks(['Annotation', 'Survey'], [True, True]) def test_xblock_masquerading_as_problem(self): """ Test the integration of xblocks masquerading as problems. """ def get_xblock_problem(label): """ Helper method to get the template of any XBlock in the problems list """ self.templates = get_component_templates(self.course) problem_templates = self.get_templates_of_type('problem') return self.get_template(problem_templates, label) def verify_openassessment_present(support_level): """ Helper method to verify that openassessment template is present """ openassessment = get_xblock_problem('Open Response Assessment') self.assertIsNotNone(openassessment) self.assertEqual(openassessment.get('category'), 'openassessment') self.assertEqual(openassessment.get('support_level'), support_level) def verify_dndv2_present(support_level): """ Helper method to verify that DnDv2 template is present """ dndv2 = get_xblock_problem('Drag and Drop') self.assertIsNotNone(dndv2) self.assertEqual(dndv2.get('category'), 'drag-and-drop-v2') self.assertEqual(dndv2.get('support_level'), support_level) verify_openassessment_present(True) verify_dndv2_present(True) # Now enable XBlockStudioConfigurationFlag. The openassessment block is marked # unsupported, so will no longer show up, but DnDv2 will continue to appear. XBlockStudioConfigurationFlag.objects.create(enabled=True) self.assertIsNone(get_xblock_problem('Peer Assessment')) self.assertIsNotNone(get_xblock_problem('Drag and Drop')) # Now allow unsupported components. self.course.allow_unsupported_xblocks = True verify_openassessment_present('us') verify_dndv2_present('fs') # Now disable the blocks completely through XBlockConfiguration XBlockConfiguration.objects.create(name='openassessment', enabled=False) XBlockConfiguration.objects.create(name='drag-and-drop-v2', enabled=False) self.assertIsNone(get_xblock_problem('Peer Assessment')) self.assertIsNone(get_xblock_problem('Drag and Drop')) def _verify_advanced_xblocks(self, expected_xblocks, expected_support_levels): """ Verify the names of the advanced xblocks showing in the "new component" menu. """ templates = get_component_templates(self.course) button_names = [template['display_name'] for template in templates] self.assertIn('Advanced', button_names) self.assertEqual(len(templates[0]['templates']), len(expected_xblocks)) template_display_names = [template['display_name'] for template in templates[0]['templates']] self.assertEqual(template_display_names, expected_xblocks) template_support_levels = [template['support_level'] for template in templates[0]['templates']] self.assertEqual(template_support_levels, expected_support_levels) def _verify_basic_component(self, component_type, display_name, support_level=True): """ Verify the display name and support level of basic components (that have no boilerplates). """ templates = self.get_templates_of_type(component_type) self.assertEqual(1, len(templates)) self.assertEqual(display_name, templates[0]['display_name']) self.assertEqual(support_level, templates[0]['support_level']) @ddt.ddt class TestXBlockInfo(ItemTest): """ Unit tests for XBlock's outline handling. """ def setUp(self): super(TestXBlockInfo, self).setUp() user_id = self.user.id self.chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Week 1", user_id=user_id ) self.sequential = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name="Lesson 1", user_id=user_id ) self.vertical = ItemFactory.create( parent_location=self.sequential.location, category='vertical', display_name='Unit 1', user_id=user_id ) self.video = ItemFactory.create( parent_location=self.vertical.location, category='video', display_name='My Video', user_id=user_id ) def test_json_responses(self): outline_url = reverse_usage_url('xblock_outline_handler', self.usage_key) resp = self.client.get(outline_url, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) self.validate_course_xblock_info(json_response, course_outline=True) @ddt.data( (ModuleStoreEnum.Type.split, 4, 4), (ModuleStoreEnum.Type.mongo, 5, 7), ) @ddt.unpack def test_xblock_outline_handler_mongo_calls(self, store_type, chapter_queries, chapter_queries_1): with self.store.default_store(store_type): course = CourseFactory.create() chapter = ItemFactory.create( parent_location=course.location, category='chapter', display_name='Week 1' ) outline_url = reverse_usage_url('xblock_outline_handler', chapter.location) with check_mongo_calls(chapter_queries): self.client.get(outline_url, HTTP_ACCEPT='application/json') sequential = ItemFactory.create( parent_location=chapter.location, category='sequential', display_name='Sequential 1' ) ItemFactory.create( parent_location=sequential.location, category='vertical', display_name='Vertical 1' ) # calls should be same after adding two new children for split only. with check_mongo_calls(chapter_queries_1): self.client.get(outline_url, HTTP_ACCEPT='application/json') def test_entrance_exam_chapter_xblock_info(self): chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Entrance Exam", user_id=self.user.id, is_entrance_exam=True ) chapter = modulestore().get_item(chapter.location) xblock_info = create_xblock_info( chapter, include_child_info=True, include_children_predicate=ALWAYS, ) # entrance exam chapter should not be deletable, draggable and childAddable. actions = xblock_info['actions'] self.assertEqual(actions['deletable'], False) self.assertEqual(actions['draggable'], False) self.assertEqual(actions['childAddable'], False) self.assertEqual(xblock_info['display_name'], 'Entrance Exam') self.assertIsNone(xblock_info.get('is_header_visible', None)) def test_none_entrance_exam_chapter_xblock_info(self): chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Test Chapter", user_id=self.user.id ) chapter = modulestore().get_item(chapter.location) xblock_info = create_xblock_info( chapter, include_child_info=True, include_children_predicate=ALWAYS, ) # chapter should be deletable, draggable and childAddable if not an entrance exam. actions = xblock_info['actions'] self.assertEqual(actions['deletable'], True) self.assertEqual(actions['draggable'], True) self.assertEqual(actions['childAddable'], True) # chapter xblock info should not contains the key of 'is_header_visible'. self.assertIsNone(xblock_info.get('is_header_visible', None)) def test_entrance_exam_sequential_xblock_info(self): chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Entrance Exam", user_id=self.user.id, is_entrance_exam=True, in_entrance_exam=True ) subsection = ItemFactory.create( parent_location=chapter.location, category='sequential', display_name="Subsection - Entrance Exam", user_id=self.user.id, in_entrance_exam=True ) subsection = modulestore().get_item(subsection.location) xblock_info = create_xblock_info( subsection, include_child_info=True, include_children_predicate=ALWAYS ) # in case of entrance exam subsection, header should be hidden. self.assertEqual(xblock_info['is_header_visible'], False) self.assertEqual(xblock_info['display_name'], 'Subsection - Entrance Exam') def test_none_entrance_exam_sequential_xblock_info(self): subsection = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name="Subsection - Exam", user_id=self.user.id ) subsection = modulestore().get_item(subsection.location) xblock_info = create_xblock_info( subsection, include_child_info=True, include_children_predicate=ALWAYS, parent_xblock=self.chapter ) # sequential xblock info should not contains the key of 'is_header_visible'. self.assertIsNone(xblock_info.get('is_header_visible', None)) def test_chapter_xblock_info(self): chapter = modulestore().get_item(self.chapter.location) xblock_info = create_xblock_info( chapter, include_child_info=True, include_children_predicate=ALWAYS, ) self.validate_chapter_xblock_info(xblock_info) def test_sequential_xblock_info(self): sequential = modulestore().get_item(self.sequential.location) xblock_info = create_xblock_info( sequential, include_child_info=True, include_children_predicate=ALWAYS, ) self.validate_sequential_xblock_info(xblock_info) def test_vertical_xblock_info(self): vertical = modulestore().get_item(self.vertical.location) xblock_info = create_xblock_info( vertical, include_child_info=True, include_children_predicate=ALWAYS, include_ancestor_info=True, user=self.user ) add_container_page_publishing_info(vertical, xblock_info) self.validate_vertical_xblock_info(xblock_info) def test_component_xblock_info(self): video = modulestore().get_item(self.video.location) xblock_info = create_xblock_info( video, include_child_info=True, include_children_predicate=ALWAYS ) self.validate_component_xblock_info(xblock_info) @ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo) def test_validate_start_date(self, store_type): """ Validate if start-date year is less than 1900 reset the date to DEFAULT_START_DATE. """ with self.store.default_store(store_type): course = CourseFactory.create() chapter = ItemFactory.create( parent_location=course.location, category='chapter', display_name='Week 1' ) chapter.start = datetime(year=1899, month=1, day=1, tzinfo=UTC) xblock_info = create_xblock_info( chapter, include_child_info=True, include_children_predicate=ALWAYS, include_ancestor_info=True, user=self.user ) self.assertEqual(xblock_info['start'], DEFAULT_START_DATE.strftime('%Y-%m-%dT%H:%M:%SZ')) def validate_course_xblock_info(self, xblock_info, has_child_info=True, course_outline=False): """ Validate that the xblock info is correct for the test course. """ self.assertEqual(xblock_info['category'], 'course') self.assertEqual(xblock_info['id'], unicode(self.course.location)) self.assertEqual(xblock_info['display_name'], self.course.display_name) self.assertTrue(xblock_info['published']) # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info, has_child_info=has_child_info, course_outline=course_outline) def validate_chapter_xblock_info(self, xblock_info, has_child_info=True): """ Validate that the xblock info is correct for the test chapter. """ self.assertEqual(xblock_info['category'], 'chapter') self.assertEqual(xblock_info['id'], unicode(self.chapter.location)) self.assertEqual(xblock_info['display_name'], 'Week 1') self.assertTrue(xblock_info['published']) self.assertIsNone(xblock_info.get('edited_by', None)) self.assertEqual(xblock_info['course_graders'], ['Homework', 'Lab', 'Midterm Exam', 'Final Exam']) self.assertEqual(xblock_info['start'], '2030-01-01T00:00:00Z') self.assertEqual(xblock_info['graded'], False) self.assertEqual(xblock_info['due'], None) self.assertEqual(xblock_info['format'], None) # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info, has_child_info=has_child_info) def validate_sequential_xblock_info(self, xblock_info, has_child_info=True): """ Validate that the xblock info is correct for the test sequential. """ self.assertEqual(xblock_info['category'], 'sequential') self.assertEqual(xblock_info['id'], unicode(self.sequential.location)) self.assertEqual(xblock_info['display_name'], 'Lesson 1') self.assertTrue(xblock_info['published']) self.assertIsNone(xblock_info.get('edited_by', None)) # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info, has_child_info=has_child_info) def validate_vertical_xblock_info(self, xblock_info): """ Validate that the xblock info is correct for the test vertical. """ self.assertEqual(xblock_info['category'], 'vertical') self.assertEqual(xblock_info['id'], unicode(self.vertical.location)) self.assertEqual(xblock_info['display_name'], 'Unit 1') self.assertTrue(xblock_info['published']) self.assertEqual(xblock_info['edited_by'], 'testuser') # Validate that the correct ancestor info has been included ancestor_info = xblock_info.get('ancestor_info', None) self.assertIsNotNone(ancestor_info) ancestors = ancestor_info['ancestors'] self.assertEqual(len(ancestors), 3) self.validate_sequential_xblock_info(ancestors[0], has_child_info=True) self.validate_chapter_xblock_info(ancestors[1], has_child_info=False) self.validate_course_xblock_info(ancestors[2], has_child_info=False) # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info, has_child_info=True, has_ancestor_info=True) def validate_component_xblock_info(self, xblock_info): """ Validate that the xblock info is correct for the test component. """ self.assertEqual(xblock_info['category'], 'video') self.assertEqual(xblock_info['id'], unicode(self.video.location)) self.assertEqual(xblock_info['display_name'], 'My Video') self.assertTrue(xblock_info['published']) self.assertIsNone(xblock_info.get('edited_by', None)) # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info) def validate_xblock_info_consistency(self, xblock_info, has_ancestor_info=False, has_child_info=False, course_outline=False): """ Validate that the xblock info is internally consistent. """ self.assertIsNotNone(xblock_info['display_name']) self.assertIsNotNone(xblock_info['id']) self.assertIsNotNone(xblock_info['category']) self.assertTrue(xblock_info['published']) if has_ancestor_info: self.assertIsNotNone(xblock_info.get('ancestor_info', None)) ancestors = xblock_info['ancestor_info']['ancestors'] for ancestor in xblock_info['ancestor_info']['ancestors']: self.validate_xblock_info_consistency( ancestor, has_child_info=(ancestor == ancestors[0]), # Only the direct ancestor includes children course_outline=course_outline ) else: self.assertIsNone(xblock_info.get('ancestor_info', None)) if has_child_info: self.assertIsNotNone(xblock_info.get('child_info', None)) if xblock_info['child_info'].get('children', None): for child_response in xblock_info['child_info']['children']: self.validate_xblock_info_consistency( child_response, has_child_info=(not child_response.get('child_info', None) is None), course_outline=course_outline ) else: self.assertIsNone(xblock_info.get('child_info', None)) @patch.dict('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True}) def test_proctored_exam_xblock_info(self): self.course.enable_proctored_exams = True self.course.save() self.store.update_item(self.course, self.user.id) course = modulestore().get_item(self.course.location) xblock_info = create_xblock_info( course, include_child_info=True, include_children_predicate=ALWAYS, ) # exam proctoring should be enabled and time limited. self.assertEqual(xblock_info['enable_proctored_exams'], True) sequential = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name="Test Lesson 1", user_id=self.user.id, is_proctored_exam=True, is_time_limited=True, default_time_limit_minutes=100 ) sequential = modulestore().get_item(sequential.location) xblock_info = create_xblock_info( sequential, include_child_info=True, include_children_predicate=ALWAYS, ) # exam proctoring should be enabled and time limited. self.assertEqual(xblock_info['is_proctored_exam'], True) self.assertEqual(xblock_info['is_time_limited'], True) self.assertEqual(xblock_info['default_time_limit_minutes'], 100) class TestLibraryXBlockInfo(ModuleStoreTestCase): """ Unit tests for XBlock Info for XBlocks in a content library """ def setUp(self): super(TestLibraryXBlockInfo, self).setUp() user_id = self.user.id self.library = LibraryFactory.create() self.top_level_html = ItemFactory.create( parent_location=self.library.location, category='html', user_id=user_id, publish_item=False ) self.vertical = ItemFactory.create( parent_location=self.library.location, category='vertical', user_id=user_id, publish_item=False ) self.child_html = ItemFactory.create( parent_location=self.vertical.location, category='html', display_name='Test HTML Child Block', user_id=user_id, publish_item=False ) def test_lib_xblock_info(self): html_block = modulestore().get_item(self.top_level_html.location) xblock_info = create_xblock_info(html_block) self.validate_component_xblock_info(xblock_info, html_block) self.assertIsNone(xblock_info.get('child_info', None)) def test_lib_child_xblock_info(self): html_block = modulestore().get_item(self.child_html.location) xblock_info = create_xblock_info(html_block, include_ancestor_info=True, include_child_info=True) self.validate_component_xblock_info(xblock_info, html_block) self.assertIsNone(xblock_info.get('child_info', None)) ancestors = xblock_info['ancestor_info']['ancestors'] self.assertEqual(len(ancestors), 2) self.assertEqual(ancestors[0]['category'], 'vertical') self.assertEqual(ancestors[0]['id'], unicode(self.vertical.location)) self.assertEqual(ancestors[1]['category'], 'library') def validate_component_xblock_info(self, xblock_info, original_block): """ Validate that the xblock info is correct for the test component. """ self.assertEqual(xblock_info['category'], original_block.category) self.assertEqual(xblock_info['id'], unicode(original_block.location)) self.assertEqual(xblock_info['display_name'], original_block.display_name) self.assertIsNone(xblock_info.get('has_changes', None)) self.assertIsNone(xblock_info.get('published', None)) self.assertIsNone(xblock_info.get('published_on', None)) self.assertIsNone(xblock_info.get('graders', None)) class TestLibraryXBlockCreation(ItemTest): """ Tests the adding of XBlocks to Library """ def test_add_xblock(self): """ Verify we can add an XBlock to a Library. """ lib = LibraryFactory.create() self.create_xblock(parent_usage_key=lib.location, display_name='Test', category="html") lib = self.store.get_library(lib.location.library_key) self.assertTrue(lib.children) xblock_locator = lib.children[0] self.assertEqual(self.store.get_item(xblock_locator).display_name, 'Test') def test_no_add_discussion(self): """ Verify we cannot add a discussion module to a Library. """ lib = LibraryFactory.create() response = self.create_xblock(parent_usage_key=lib.location, display_name='Test', category='discussion') self.assertEqual(response.status_code, 400) lib = self.store.get_library(lib.location.library_key) self.assertFalse(lib.children) def test_no_add_advanced(self): lib = LibraryFactory.create() lib.advanced_modules = ['lti'] lib.save() response = self.create_xblock(parent_usage_key=lib.location, display_name='Test', category='lti') self.assertEqual(response.status_code, 400) lib = self.store.get_library(lib.location.library_key) self.assertFalse(lib.children) @ddt.ddt class TestXBlockPublishingInfo(ItemTest): """ Unit tests for XBlock's outline handling. """ FIRST_SUBSECTION_PATH = [0] FIRST_UNIT_PATH = [0, 0] SECOND_UNIT_PATH = [0, 1] def _create_child(self, parent, category, display_name, publish_item=False, staff_only=False): """ Creates a child xblock for the given parent. """ child = ItemFactory.create( parent_location=parent.location, category=category, display_name=display_name, user_id=self.user.id, publish_item=publish_item ) if staff_only: self._enable_staff_only(child.location) # In case the staff_only state was set, return the updated xblock. return modulestore().get_item(child.location) def _get_child_xblock_info(self, xblock_info, index): """ Returns the child xblock info at the specified index. """ children = xblock_info['child_info']['children'] self.assertGreater(len(children), index) return children[index] def _get_xblock_info(self, location): """ Returns the xblock info for the specified location. """ return create_xblock_info( modulestore().get_item(location), include_child_info=True, include_children_predicate=ALWAYS, ) def _get_xblock_outline_info(self, location): """ Returns the xblock info for the specified location as neeeded for the course outline page. """ return create_xblock_info( modulestore().get_item(location), include_child_info=True, include_children_predicate=ALWAYS, course_outline=True ) def _set_release_date(self, location, start): """ Sets the release date for the specified xblock. """ xblock = modulestore().get_item(location) xblock.start = start self.store.update_item(xblock, self.user.id) def _enable_staff_only(self, location): """ Enables staff only for the specified xblock. """ xblock = modulestore().get_item(location) xblock.visible_to_staff_only = True self.store.update_item(xblock, self.user.id) def _set_display_name(self, location, display_name): """ Sets the display name for the specified xblock. """ xblock = modulestore().get_item(location) xblock.display_name = display_name self.store.update_item(xblock, self.user.id) def _verify_xblock_info_state(self, xblock_info, xblock_info_field, expected_state, path=None, should_equal=True): """ Verify the state of an xblock_info field. If no path is provided then the root item will be verified. If should_equal is True, assert that the current state matches the expected state, otherwise assert that they do not match. """ if path: direct_child_xblock_info = self._get_child_xblock_info(xblock_info, path[0]) remaining_path = path[1:] if len(path) > 1 else None self._verify_xblock_info_state(direct_child_xblock_info, xblock_info_field, expected_state, remaining_path, should_equal) else: if should_equal: self.assertEqual(xblock_info[xblock_info_field], expected_state) else: self.assertNotEqual(xblock_info[xblock_info_field], expected_state) def _verify_has_staff_only_message(self, xblock_info, expected_state, path=None): """ Verify the staff_only_message field of xblock_info. """ self._verify_xblock_info_state(xblock_info, 'staff_only_message', expected_state, path) def _verify_visibility_state(self, xblock_info, expected_state, path=None, should_equal=True): """ Verify the publish state of an item in the xblock_info. """ self._verify_xblock_info_state(xblock_info, 'visibility_state', expected_state, path, should_equal) def _verify_explicit_staff_lock_state(self, xblock_info, expected_state, path=None, should_equal=True): """ Verify the explicit staff lock state of an item in the xblock_info. """ self._verify_xblock_info_state(xblock_info, 'has_explicit_staff_lock', expected_state, path, should_equal) def test_empty_chapter(self): empty_chapter = self._create_child(self.course, 'chapter', "Empty Chapter") xblock_info = self._get_xblock_info(empty_chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.unscheduled) def test_empty_sequential(self): chapter = self._create_child(self.course, 'chapter', "Test Chapter") self._create_child(chapter, 'sequential', "Empty Sequential") xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.unscheduled) self._verify_visibility_state(xblock_info, VisibilityState.unscheduled, path=self.FIRST_SUBSECTION_PATH) def test_published_unit(self): """ Tests the visibility state of a published unit with release date in the future. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(chapter.location, datetime.now(UTC) + timedelta(days=1)) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.ready) self._verify_visibility_state(xblock_info, VisibilityState.ready, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.ready, path=self.FIRST_UNIT_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.SECOND_UNIT_PATH) def test_released_unit(self): """ Tests the visibility state of a published unit with release date in the past. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(chapter.location, datetime.now(UTC) - timedelta(days=1)) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.live) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_UNIT_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.SECOND_UNIT_PATH) def test_unpublished_changes(self): """ Tests the visibility state of a published unit with draft (unpublished) changes. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") unit = self._create_child(sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(sequential, 'vertical', "Staff Only Unit", staff_only=True) # Setting the display name creates a draft version of unit. self._set_display_name(unit.location, 'Updated Unit') xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.needs_attention) self._verify_visibility_state(xblock_info, VisibilityState.needs_attention, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.needs_attention, path=self.FIRST_UNIT_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.SECOND_UNIT_PATH) def test_partially_released_section(self): chapter = self._create_child(self.course, 'chapter', "Test Chapter") released_sequential = self._create_child(chapter, 'sequential', "Released Sequential") self._create_child(released_sequential, 'vertical', "Released Unit", publish_item=True) self._create_child(released_sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(chapter.location, datetime.now(UTC) - timedelta(days=1)) published_sequential = self._create_child(chapter, 'sequential', "Published Sequential") self._create_child(published_sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(published_sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(published_sequential.location, datetime.now(UTC) + timedelta(days=1)) xblock_info = self._get_xblock_info(chapter.location) # Verify the state of the released sequential self._verify_visibility_state(xblock_info, VisibilityState.live, path=[0]) self._verify_visibility_state(xblock_info, VisibilityState.live, path=[0, 0]) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=[0, 1]) # Verify the state of the published sequential self._verify_visibility_state(xblock_info, VisibilityState.ready, path=[1]) self._verify_visibility_state(xblock_info, VisibilityState.ready, path=[1, 0]) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=[1, 1]) # Finally verify the state of the chapter self._verify_visibility_state(xblock_info, VisibilityState.ready) def test_staff_only_section(self): """ Tests that an explicitly staff-locked section and all of its children are visible to staff only. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter", staff_only=True) sequential = self._create_child(chapter, 'sequential', "Test Sequential") vertical = self._create_child(sequential, 'vertical', "Unit") xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.staff_only) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_UNIT_PATH) self._verify_explicit_staff_lock_state(xblock_info, True) self._verify_explicit_staff_lock_state(xblock_info, False, path=self.FIRST_SUBSECTION_PATH) self._verify_explicit_staff_lock_state(xblock_info, False, path=self.FIRST_UNIT_PATH) vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) self.assertEqual(_xblock_type_and_display_name(chapter), vertical_info["staff_lock_from"]) def test_no_staff_only_section(self): """ Tests that a section with a staff-locked subsection and a visible subsection is not staff locked itself. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") self._create_child(chapter, 'sequential', "Test Visible Sequential") self._create_child(chapter, 'sequential', "Test Staff Locked Sequential", staff_only=True) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, should_equal=False) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=[0], should_equal=False) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=[1]) def test_staff_only_subsection(self): """ Tests that an explicitly staff-locked subsection and all of its children are visible to staff only. In this case the parent section is also visible to staff only because all of its children are staff only. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential", staff_only=True) vertical = self._create_child(sequential, 'vertical', "Unit") xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.staff_only) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_UNIT_PATH) self._verify_explicit_staff_lock_state(xblock_info, False) self._verify_explicit_staff_lock_state(xblock_info, True, path=self.FIRST_SUBSECTION_PATH) self._verify_explicit_staff_lock_state(xblock_info, False, path=self.FIRST_UNIT_PATH) vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) self.assertEqual(_xblock_type_and_display_name(sequential), vertical_info["staff_lock_from"]) def test_no_staff_only_subsection(self): """ Tests that a subsection with a staff-locked unit and a visible unit is not staff locked itself. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Unit") self._create_child(sequential, 'vertical', "Locked Unit", staff_only=True) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, self.FIRST_SUBSECTION_PATH, should_equal=False) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, self.FIRST_UNIT_PATH, should_equal=False) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, self.SECOND_UNIT_PATH) def test_staff_only_unit(self): chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") vertical = self._create_child(sequential, 'vertical', "Unit", staff_only=True) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.staff_only) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.FIRST_UNIT_PATH) self._verify_explicit_staff_lock_state(xblock_info, False) self._verify_explicit_staff_lock_state(xblock_info, False, path=self.FIRST_SUBSECTION_PATH) self._verify_explicit_staff_lock_state(xblock_info, True, path=self.FIRST_UNIT_PATH) vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) self.assertEqual(_xblock_type_and_display_name(vertical), vertical_info["staff_lock_from"]) def test_unscheduled_section_with_live_subsection(self): chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(sequential.location, datetime.now(UTC) - timedelta(days=1)) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.needs_attention) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_UNIT_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.SECOND_UNIT_PATH) def test_unreleased_section_with_live_subsection(self): chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Published Unit", publish_item=True) self._create_child(sequential, 'vertical', "Staff Only Unit", staff_only=True) self._set_release_date(chapter.location, datetime.now(UTC) + timedelta(days=1)) self._set_release_date(sequential.location, datetime.now(UTC) - timedelta(days=1)) xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.needs_attention) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_SUBSECTION_PATH) self._verify_visibility_state(xblock_info, VisibilityState.live, path=self.FIRST_UNIT_PATH) self._verify_visibility_state(xblock_info, VisibilityState.staff_only, path=self.SECOND_UNIT_PATH) def test_locked_section_staff_only_message(self): """ Tests that a locked section has a staff only message and its descendants do not. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter", staff_only=True) sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Unit") xblock_info = self._get_xblock_outline_info(chapter.location) self._verify_has_staff_only_message(xblock_info, True) self._verify_has_staff_only_message(xblock_info, False, path=self.FIRST_SUBSECTION_PATH) self._verify_has_staff_only_message(xblock_info, False, path=self.FIRST_UNIT_PATH) def test_locked_unit_staff_only_message(self): """ Tests that a lone locked unit has a staff only message along with its ancestors. """ chapter = self._create_child(self.course, 'chapter', "Test Chapter") sequential = self._create_child(chapter, 'sequential', "Test Sequential") self._create_child(sequential, 'vertical', "Unit", staff_only=True) xblock_info = self._get_xblock_outline_info(chapter.location) self._verify_has_staff_only_message(xblock_info, True) self._verify_has_staff_only_message(xblock_info, True, path=self.FIRST_SUBSECTION_PATH) self._verify_has_staff_only_message(xblock_info, True, path=self.FIRST_UNIT_PATH) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_self_paced_item_visibility_state(self, store_type): """ Test that in self-paced course, item has `live` visibility state. Test that when item was initially in `scheduled` state in instructor mode, change course pacing to self-paced, now in self-paced course, item should have `live` visibility state. """ SelfPacedConfiguration(enabled=True).save() # Create course, chapter and setup future release date to make chapter in scheduled state course = CourseFactory.create(default_store=store_type) chapter = self._create_child(course, 'chapter', "Test Chapter") self._set_release_date(chapter.location, datetime.now(UTC) + timedelta(days=1)) # Check that chapter has scheduled state xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.ready) self.assertFalse(course.self_paced) # Change course pacing to self paced course.self_paced = True self.store.update_item(course, self.user.id) self.assertTrue(course.self_paced) # Check that in self paced course content has live state now xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.live)
agpl-3.0
michaelld/gnuradio
gr-qtgui/examples/pyqt_time_c.py
7
6860
#!/usr/bin/env python # # Copyright 2011,2012,2015 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from __future__ import print_function from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt5 import QtWidgets, Qt import sip except ImportError: sys.stderr.write("Error: Program requires PyQt5 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtWidgets.QToolTip.setFont(Qt.QFont('OldEnglish', 10)) self.layout = QtWidgets.QFormLayout(self) # Control the first signal self.freq1Edit = QtWidgets.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.freq1Edit.editingFinished.connect(self.freq1EditText) self.amp1Edit = QtWidgets.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.amp2Edit.editingFinished.connect(self.amp2EditText) self.quit = QtWidgets.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.quit.clicked.connect(QtWidgets.qApp.quit) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(("{0}").format(self.signal1.frequency())) self.amp1Edit.setText(("{0}").format(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(("{0}").format(self.signal2.frequency())) self.amp2Edit.setText(("{0}").format(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print("Bad frequency value entered") def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print("Bad amplitude value entered") def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print("Bad frequency value entered") def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print("Bad amplitude value entered") class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtWidgets.QApplication(sys.argv) ss = open(gr.prefix() + '/share/gnuradio/themes/dark.qss') sstext = ss.read() ss.close() self.qapp.setStyleSheet(sstext) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.01) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.time_sink_c(npts, Rs, "Complex Time Example", 1) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) #self.connect(src1, (self.snk1, 1)) #self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) # Example of using signal/slot to set the title of a curve # FIXME: update for Qt5 #pyWin.setLineLabel.connect(pyWin.setLineLabel) #pyWin.emit(QtCore.SIGNAL("setLineLabel(int, QString)"), 0, "Re{sum}") self.snk1.set_line_label(0, "Re{Sum}") self.snk1.set_line_label(1, "Im{Sum}") #self.snk1.set_line_label(2, "Re{src1}") #self.snk1.set_line_label(3, "Im{src1}") #self.snk1.set_line_label(4, "Re{src2}") #self.snk1.set_line_label(5, "Im{src2}") # Can also set the color of a curve #self.snk1.set_color(5, "blue") self.snk1.set_update_time(0.5) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop()
gpl-3.0
mateon1/servo
tests/wpt/web-platform-tests/tools/gitignore/tests/test_gitignore.py
98
2034
import pytest from ..gitignore import fnmatch_translate, PathFilter match_data = [ ("foo", False, ["a/foo", "foo"]), ("*.a", False, ["foo.a", "a/foo.a", "a/b/foo.a", "a.a/foo.a"]), ("*.py[co]", False, ["a.pyc", "a.pyo", "a/b/c.pyc"]), ("\\#*", False, ["#a", "a/#b"]), ("*#", False, ["a#", "a/b#", "#a#"]), ("/*.c", False, ["a.c", ".c"]), ("**/b", False, ["a/b", "a/c/b"]), ("*b", True, ["ab"]), ("**/b", True, ["a/b"]) ] mismatch_data = [ ("foo", False, ["foob", "afoo"]), ("*.a", False, ["a", "foo:a", "a.a/foo"]), ("*.py[co]", False, ["a.pyd", "pyo"]), ("/*.c", False, ["a/b.c"]), ("*b", True, ["a/b"]), ("**b", True, ["a/b"]), ("a[/]b", True, ["a/b"]), ("**/b", True, ["a/c/b"]), ] invalid_data = [ "[a", "***/foo", "a\\", ] filter_data = [ ("foo", True), ("a", False), ("a/b", False), ("a/c", True), ("a/c/", False), ("c/b", True) ] def expand_data(compact_data): for pattern, path_name, inputs in compact_data: for input in inputs: yield pattern, input, path_name @pytest.mark.parametrize("pattern, input, path_name", expand_data(match_data)) def tests_match(pattern, input, path_name): regexp = fnmatch_translate(pattern, path_name) assert regexp.match(input) is not None @pytest.mark.parametrize("pattern, input, path_name", expand_data(mismatch_data)) def tests_no_match(pattern, input, path_name): regexp = fnmatch_translate(pattern, path_name) assert regexp.match(input) is None @pytest.mark.parametrize("pattern", invalid_data) def tests_invalid(pattern): with pytest.raises(ValueError): fnmatch_translate(pattern, False) with pytest.raises(ValueError): fnmatch_translate(pattern, True) @pytest.mark.parametrize("path, expected", filter_data) def test_path_filter(path, expected): extras = [ "#foo", "a ", "**/b", "a/c/", "!c/b", ] f = PathFilter(None, extras) assert f(path) == expected
mpl-2.0
caldwell/servo
tests/wpt/web-platform-tests/webdriver/javascript/execute_script_test.py
65
5664
import os import sys import unittest sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../.."))) import base_test class ExecuteScriptTest(base_test.WebDriverBaseTest): def test_ecmascript_translates_null_return_to_none(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return null;") self.assertIsNone(result) def test_ecmascript_translates_undefined_return_to_none(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("var undef; return undef;") self.assertIsNone(result) def test_can_return_numbers_from_scripts(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) self.assertEquals(1, self.driver.execute_script("return 1;")) self.assertEquals(3.14, self.driver.execute_script("return 3.14;")) def test_can_return_strings_from_scripts(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) self.assertEquals("hello, world!", self.driver.execute_script("return 'hello, world!'")) def test_can_return_booleans_from_scripts(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) self.assertTrue(self.driver.execute_script("return true;")) self.assertFalse(self.driver.execute_script("return false;")) def test_can_return_an_array_of_primitives(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return [1, false, null, 3.14]") self.assertListEqual([1, False, None, 3.14], result) def test_can_return_nested_arrays(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return [[1, 2, [3]]]") self.assertIsInstance(result, list) self.assertEquals(1, len(result)) result = result[0] self.assertListEqual([1, 2], result[:2]) self.assertListEqual([3], result[2]) def test_can_return_object_literals(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return {}") self.assertDictEqual({}, result) result = self.driver.execute_script("return {a: 1, b: false, c: null}") self.assertDictEqual({ "a": 1, "b": False, "c": None }, result) def test_can_return_complex_object_literals(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return {a:{b: 'hello'}}") self.assertIsInstance(result, dict) self.assertIsInstance(result['a'], dict) self.assertDictEqual({"b": "hello"}, result["a"]) def test_dom_element_return_value_is_translated_to_a_web_element(self): self.driver.get(self.webserver.where_is( "javascript/res/return_document_body.html")) result = self.driver.execute_script("return document.body") self.assertEquals(result.text, "Hello, world!") def test_return_an_array_of_dom_elements(self): self.driver.get(self.webserver.where_is( "javascript/res/return_array_of_dom_elements.html")) result = self.driver.execute_script( "var nodes = document.getElementsByTagName('div');" "return [nodes[0], nodes[1]]") self.assertIsInstance(result, list) self.assertEquals(2, len(result)) self.assertEquals("a", result[0].text) self.assertEquals("b", result[1].text) def test_node_list_return_value_is_translated_to_list_of_web_elements(self): self.driver.get(self.webserver.where_is( "javascript/res/return_array_of_dom_elements.html")) result = self.driver.execute_script( "return document.getElementsByTagName('div');") self.assertIsInstance(result, list) self.assertEquals(2, len(result)) self.assertEquals("a", result[0].text) self.assertEquals("b", result[1].text) def test_return_object_literal_with_dom_element_property(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return {a: document.body}") self.assertIsInstance(result, dict) self.assertEquals("body", result["a"].tag_name) def test_scripts_execute_in_anonymous_function_and_do_not_pollute_global_scope(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) self.driver.execute_script("var x = 1;") self.assertEquals("undefined", self.driver.execute_script("return typeof x;")); def test_scripts_can_modify_context_window_object(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) self.driver.execute_script("window.x = 1;") self.assertEquals("number", self.driver.execute_script("return typeof x;")); self.assertEquals(1, self.driver.execute_script("return x;")); def test_that_ecmascript_returns_document_title(self): self.driver.get(self.webserver.where_is("javascript/res/execute_script_test.html")) result = self.driver.execute_script("return document.title;") self.assertEquals("executeScript test", result) if __name__ == "__main__": unittest.main()
mpl-2.0
0x0all/scikit-learn
examples/covariance/plot_covariance_estimation.py
250
5070
""" ======================================================================= Shrinkage covariance estimation: LedoitWolf vs OAS and max-likelihood ======================================================================= When working with covariance estimation, the usual approach is to use a maximum likelihood estimator, such as the :class:`sklearn.covariance.EmpiricalCovariance`. It is unbiased, i.e. it converges to the true (population) covariance when given many observations. However, it can also be beneficial to regularize it, in order to reduce its variance; this, in turn, introduces some bias. This example illustrates the simple regularization used in :ref:`shrunk_covariance` estimators. In particular, it focuses on how to set the amount of regularization, i.e. how to choose the bias-variance trade-off. Here we compare 3 approaches: * Setting the parameter by cross-validating the likelihood on three folds according to a grid of potential shrinkage parameters. * A close formula proposed by Ledoit and Wolf to compute the asymptotically optimal regularization parameter (minimizing a MSE criterion), yielding the :class:`sklearn.covariance.LedoitWolf` covariance estimate. * An improvement of the Ledoit-Wolf shrinkage, the :class:`sklearn.covariance.OAS`, proposed by Chen et al. Its convergence is significantly better under the assumption that the data are Gaussian, in particular for small samples. To quantify estimation error, we plot the likelihood of unseen data for different values of the shrinkage parameter. We also show the choices by cross-validation, or with the LedoitWolf and OAS estimates. Note that the maximum likelihood estimate corresponds to no shrinkage, and thus performs poorly. The Ledoit-Wolf estimate performs really well, as it is close to the optimal and is computational not costly. In this example, the OAS estimate is a bit further away. Interestingly, both approaches outperform cross-validation, which is significantly most computationally costly. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from scipy import linalg from sklearn.covariance import LedoitWolf, OAS, ShrunkCovariance, \ log_likelihood, empirical_covariance from sklearn.grid_search import GridSearchCV ############################################################################### # Generate sample data n_features, n_samples = 40, 20 np.random.seed(42) base_X_train = np.random.normal(size=(n_samples, n_features)) base_X_test = np.random.normal(size=(n_samples, n_features)) # Color samples coloring_matrix = np.random.normal(size=(n_features, n_features)) X_train = np.dot(base_X_train, coloring_matrix) X_test = np.dot(base_X_test, coloring_matrix) ############################################################################### # Compute the likelihood on test data # spanning a range of possible shrinkage coefficient values shrinkages = np.logspace(-2, 0, 30) negative_logliks = [-ShrunkCovariance(shrinkage=s).fit(X_train).score(X_test) for s in shrinkages] # under the ground-truth model, which we would not have access to in real # settings real_cov = np.dot(coloring_matrix.T, coloring_matrix) emp_cov = empirical_covariance(X_train) loglik_real = -log_likelihood(emp_cov, linalg.inv(real_cov)) ############################################################################### # Compare different approaches to setting the parameter # GridSearch for an optimal shrinkage coefficient tuned_parameters = [{'shrinkage': shrinkages}] cv = GridSearchCV(ShrunkCovariance(), tuned_parameters) cv.fit(X_train) # Ledoit-Wolf optimal shrinkage coefficient estimate lw = LedoitWolf() loglik_lw = lw.fit(X_train).score(X_test) # OAS coefficient estimate oa = OAS() loglik_oa = oa.fit(X_train).score(X_test) ############################################################################### # Plot results fig = plt.figure() plt.title("Regularized covariance: likelihood and shrinkage coefficient") plt.xlabel('Regularizaton parameter: shrinkage coefficient') plt.ylabel('Error: negative log-likelihood on test data') # range shrinkage curve plt.loglog(shrinkages, negative_logliks, label="Negative log-likelihood") plt.plot(plt.xlim(), 2 * [loglik_real], '--r', label="Real covariance likelihood") # adjust view lik_max = np.amax(negative_logliks) lik_min = np.amin(negative_logliks) ymin = lik_min - 6. * np.log((plt.ylim()[1] - plt.ylim()[0])) ymax = lik_max + 10. * np.log(lik_max - lik_min) xmin = shrinkages[0] xmax = shrinkages[-1] # LW likelihood plt.vlines(lw.shrinkage_, ymin, -loglik_lw, color='magenta', linewidth=3, label='Ledoit-Wolf estimate') # OAS likelihood plt.vlines(oa.shrinkage_, ymin, -loglik_oa, color='purple', linewidth=3, label='OAS estimate') # best CV estimator likelihood plt.vlines(cv.best_estimator_.shrinkage, ymin, -cv.best_estimator_.score(X_test), color='cyan', linewidth=3, label='Cross-validation best estimate') plt.ylim(ymin, ymax) plt.xlim(xmin, xmax) plt.legend() plt.show()
bsd-3-clause
abimannans/scikit-learn
sklearn/mixture/tests/test_gmm.py
200
17427
import unittest import copy import sys from nose.tools import assert_true import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_raises) from scipy import stats from sklearn import mixture from sklearn.datasets.samples_generator import make_spd_matrix from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raise_message from sklearn.metrics.cluster import adjusted_rand_score from sklearn.externals.six.moves import cStringIO as StringIO rng = np.random.RandomState(0) def test_sample_gaussian(): # Test sample generation from mixture.sample_gaussian where covariance # is diagonal, spherical and full n_features, n_samples = 2, 300 axis = 1 mu = rng.randint(10) * rng.rand(n_features) cv = (rng.rand(n_features) + 1.0) ** 2 samples = mixture.sample_gaussian( mu, cv, covariance_type='diag', n_samples=n_samples) assert_true(np.allclose(samples.mean(axis), mu, atol=1.3)) assert_true(np.allclose(samples.var(axis), cv, atol=1.5)) # the same for spherical covariances cv = (rng.rand() + 1.0) ** 2 samples = mixture.sample_gaussian( mu, cv, covariance_type='spherical', n_samples=n_samples) assert_true(np.allclose(samples.mean(axis), mu, atol=1.5)) assert_true(np.allclose( samples.var(axis), np.repeat(cv, n_features), atol=1.5)) # and for full covariances A = rng.randn(n_features, n_features) cv = np.dot(A.T, A) + np.eye(n_features) samples = mixture.sample_gaussian( mu, cv, covariance_type='full', n_samples=n_samples) assert_true(np.allclose(samples.mean(axis), mu, atol=1.3)) assert_true(np.allclose(np.cov(samples), cv, atol=2.5)) # Numerical stability check: in SciPy 0.12.0 at least, eigh may return # tiny negative values in its second return value. from sklearn.mixture import sample_gaussian x = sample_gaussian([0, 0], [[4, 3], [1, .1]], covariance_type='full', random_state=42) print(x) assert_true(np.isfinite(x).all()) def _naive_lmvnpdf_diag(X, mu, cv): # slow and naive implementation of lmvnpdf ref = np.empty((len(X), len(mu))) stds = np.sqrt(cv) for i, (m, std) in enumerate(zip(mu, stds)): ref[:, i] = np.log(stats.norm.pdf(X, m, std)).sum(axis=1) return ref def test_lmvnpdf_diag(): # test a slow and naive implementation of lmvnpdf and # compare it to the vectorized version (mixture.lmvnpdf) to test # for correctness n_features, n_components, n_samples = 2, 3, 10 mu = rng.randint(10) * rng.rand(n_components, n_features) cv = (rng.rand(n_components, n_features) + 1.0) ** 2 X = rng.randint(10) * rng.rand(n_samples, n_features) ref = _naive_lmvnpdf_diag(X, mu, cv) lpr = mixture.log_multivariate_normal_density(X, mu, cv, 'diag') assert_array_almost_equal(lpr, ref) def test_lmvnpdf_spherical(): n_features, n_components, n_samples = 2, 3, 10 mu = rng.randint(10) * rng.rand(n_components, n_features) spherecv = rng.rand(n_components, 1) ** 2 + 1 X = rng.randint(10) * rng.rand(n_samples, n_features) cv = np.tile(spherecv, (n_features, 1)) reference = _naive_lmvnpdf_diag(X, mu, cv) lpr = mixture.log_multivariate_normal_density(X, mu, spherecv, 'spherical') assert_array_almost_equal(lpr, reference) def test_lmvnpdf_full(): n_features, n_components, n_samples = 2, 3, 10 mu = rng.randint(10) * rng.rand(n_components, n_features) cv = (rng.rand(n_components, n_features) + 1.0) ** 2 X = rng.randint(10) * rng.rand(n_samples, n_features) fullcv = np.array([np.diag(x) for x in cv]) reference = _naive_lmvnpdf_diag(X, mu, cv) lpr = mixture.log_multivariate_normal_density(X, mu, fullcv, 'full') assert_array_almost_equal(lpr, reference) def test_lvmpdf_full_cv_non_positive_definite(): n_features, n_samples = 2, 10 rng = np.random.RandomState(0) X = rng.randint(10) * rng.rand(n_samples, n_features) mu = np.mean(X, 0) cv = np.array([[[-1, 0], [0, 1]]]) expected_message = "'covars' must be symmetric, positive-definite" assert_raise_message(ValueError, expected_message, mixture.log_multivariate_normal_density, X, mu, cv, 'full') def test_GMM_attributes(): n_components, n_features = 10, 4 covariance_type = 'diag' g = mixture.GMM(n_components, covariance_type, random_state=rng) weights = rng.rand(n_components) weights = weights / weights.sum() means = rng.randint(-20, 20, (n_components, n_features)) assert_true(g.n_components == n_components) assert_true(g.covariance_type == covariance_type) g.weights_ = weights assert_array_almost_equal(g.weights_, weights) g.means_ = means assert_array_almost_equal(g.means_, means) covars = (0.1 + 2 * rng.rand(n_components, n_features)) ** 2 g.covars_ = covars assert_array_almost_equal(g.covars_, covars) assert_raises(ValueError, g._set_covars, []) assert_raises(ValueError, g._set_covars, np.zeros((n_components - 2, n_features))) assert_raises(ValueError, mixture.GMM, n_components=20, covariance_type='badcovariance_type') class GMMTester(): do_test_eval = True def _setUp(self): self.n_components = 10 self.n_features = 4 self.weights = rng.rand(self.n_components) self.weights = self.weights / self.weights.sum() self.means = rng.randint(-20, 20, (self.n_components, self.n_features)) self.threshold = -0.5 self.I = np.eye(self.n_features) self.covars = { 'spherical': (0.1 + 2 * rng.rand(self.n_components, self.n_features)) ** 2, 'tied': (make_spd_matrix(self.n_features, random_state=0) + 5 * self.I), 'diag': (0.1 + 2 * rng.rand(self.n_components, self.n_features)) ** 2, 'full': np.array([make_spd_matrix(self.n_features, random_state=0) + 5 * self.I for x in range(self.n_components)])} def test_eval(self): if not self.do_test_eval: return # DPGMM does not support setting the means and # covariances before fitting There is no way of fixing this # due to the variational parameters being more expressive than # covariance matrices g = self.model(n_components=self.n_components, covariance_type=self.covariance_type, random_state=rng) # Make sure the means are far apart so responsibilities.argmax() # picks the actual component used to generate the observations. g.means_ = 20 * self.means g.covars_ = self.covars[self.covariance_type] g.weights_ = self.weights gaussidx = np.repeat(np.arange(self.n_components), 5) n_samples = len(gaussidx) X = rng.randn(n_samples, self.n_features) + g.means_[gaussidx] ll, responsibilities = g.score_samples(X) self.assertEqual(len(ll), n_samples) self.assertEqual(responsibilities.shape, (n_samples, self.n_components)) assert_array_almost_equal(responsibilities.sum(axis=1), np.ones(n_samples)) assert_array_equal(responsibilities.argmax(axis=1), gaussidx) def test_sample(self, n=100): g = self.model(n_components=self.n_components, covariance_type=self.covariance_type, random_state=rng) # Make sure the means are far apart so responsibilities.argmax() # picks the actual component used to generate the observations. g.means_ = 20 * self.means g.covars_ = np.maximum(self.covars[self.covariance_type], 0.1) g.weights_ = self.weights samples = g.sample(n) self.assertEqual(samples.shape, (n, self.n_features)) def test_train(self, params='wmc'): g = mixture.GMM(n_components=self.n_components, covariance_type=self.covariance_type) g.weights_ = self.weights g.means_ = self.means g.covars_ = 20 * self.covars[self.covariance_type] # Create a training set by sampling from the predefined distribution. X = g.sample(n_samples=100) g = self.model(n_components=self.n_components, covariance_type=self.covariance_type, random_state=rng, min_covar=1e-1, n_iter=1, init_params=params) g.fit(X) # Do one training iteration at a time so we can keep track of # the log likelihood to make sure that it increases after each # iteration. trainll = [] for _ in range(5): g.params = params g.init_params = '' g.fit(X) trainll.append(self.score(g, X)) g.n_iter = 10 g.init_params = '' g.params = params g.fit(X) # finish fitting # Note that the log likelihood will sometimes decrease by a # very small amount after it has more or less converged due to # the addition of min_covar to the covariance (to prevent # underflow). This is why the threshold is set to -0.5 # instead of 0. delta_min = np.diff(trainll).min() self.assertTrue( delta_min > self.threshold, "The min nll increase is %f which is lower than the admissible" " threshold of %f, for model %s. The likelihoods are %s." % (delta_min, self.threshold, self.covariance_type, trainll)) def test_train_degenerate(self, params='wmc'): # Train on degenerate data with 0 in some dimensions # Create a training set by sampling from the predefined distribution. X = rng.randn(100, self.n_features) X.T[1:] = 0 g = self.model(n_components=2, covariance_type=self.covariance_type, random_state=rng, min_covar=1e-3, n_iter=5, init_params=params) g.fit(X) trainll = g.score(X) self.assertTrue(np.sum(np.abs(trainll / 100 / X.shape[1])) < 5) def test_train_1d(self, params='wmc'): # Train on 1-D data # Create a training set by sampling from the predefined distribution. X = rng.randn(100, 1) # X.T[1:] = 0 g = self.model(n_components=2, covariance_type=self.covariance_type, random_state=rng, min_covar=1e-7, n_iter=5, init_params=params) g.fit(X) trainll = g.score(X) if isinstance(g, mixture.DPGMM): self.assertTrue(np.sum(np.abs(trainll / 100)) < 5) else: self.assertTrue(np.sum(np.abs(trainll / 100)) < 2) def score(self, g, X): return g.score(X).sum() class TestGMMWithSphericalCovars(unittest.TestCase, GMMTester): covariance_type = 'spherical' model = mixture.GMM setUp = GMMTester._setUp class TestGMMWithDiagonalCovars(unittest.TestCase, GMMTester): covariance_type = 'diag' model = mixture.GMM setUp = GMMTester._setUp class TestGMMWithTiedCovars(unittest.TestCase, GMMTester): covariance_type = 'tied' model = mixture.GMM setUp = GMMTester._setUp class TestGMMWithFullCovars(unittest.TestCase, GMMTester): covariance_type = 'full' model = mixture.GMM setUp = GMMTester._setUp def test_multiple_init(): # Test that multiple inits does not much worse than a single one X = rng.randn(30, 5) X[:10] += 2 g = mixture.GMM(n_components=2, covariance_type='spherical', random_state=rng, min_covar=1e-7, n_iter=5) train1 = g.fit(X).score(X).sum() g.n_init = 5 train2 = g.fit(X).score(X).sum() assert_true(train2 >= train1 - 1.e-2) def test_n_parameters(): # Test that the right number of parameters is estimated n_samples, n_dim, n_components = 7, 5, 2 X = rng.randn(n_samples, n_dim) n_params = {'spherical': 13, 'diag': 21, 'tied': 26, 'full': 41} for cv_type in ['full', 'tied', 'diag', 'spherical']: g = mixture.GMM(n_components=n_components, covariance_type=cv_type, random_state=rng, min_covar=1e-7, n_iter=1) g.fit(X) assert_true(g._n_parameters() == n_params[cv_type]) def test_1d_1component(): # Test all of the covariance_types return the same BIC score for # 1-dimensional, 1 component fits. n_samples, n_dim, n_components = 100, 1, 1 X = rng.randn(n_samples, n_dim) g_full = mixture.GMM(n_components=n_components, covariance_type='full', random_state=rng, min_covar=1e-7, n_iter=1) g_full.fit(X) g_full_bic = g_full.bic(X) for cv_type in ['tied', 'diag', 'spherical']: g = mixture.GMM(n_components=n_components, covariance_type=cv_type, random_state=rng, min_covar=1e-7, n_iter=1) g.fit(X) assert_array_almost_equal(g.bic(X), g_full_bic) def assert_fit_predict_correct(model, X): model2 = copy.deepcopy(model) predictions_1 = model.fit(X).predict(X) predictions_2 = model2.fit_predict(X) assert adjusted_rand_score(predictions_1, predictions_2) == 1.0 def test_fit_predict(): """ test that gmm.fit_predict is equivalent to gmm.fit + gmm.predict """ lrng = np.random.RandomState(101) n_samples, n_dim, n_comps = 100, 2, 2 mu = np.array([[8, 8]]) component_0 = lrng.randn(n_samples, n_dim) component_1 = lrng.randn(n_samples, n_dim) + mu X = np.vstack((component_0, component_1)) for m_constructor in (mixture.GMM, mixture.VBGMM, mixture.DPGMM): model = m_constructor(n_components=n_comps, covariance_type='full', min_covar=1e-7, n_iter=5, random_state=np.random.RandomState(0)) assert_fit_predict_correct(model, X) model = mixture.GMM(n_components=n_comps, n_iter=0) z = model.fit_predict(X) assert np.all(z == 0), "Quick Initialization Failed!" def test_aic(): # Test the aic and bic criteria n_samples, n_dim, n_components = 50, 3, 2 X = rng.randn(n_samples, n_dim) SGH = 0.5 * (X.var() + np.log(2 * np.pi)) # standard gaussian entropy for cv_type in ['full', 'tied', 'diag', 'spherical']: g = mixture.GMM(n_components=n_components, covariance_type=cv_type, random_state=rng, min_covar=1e-7) g.fit(X) aic = 2 * n_samples * SGH * n_dim + 2 * g._n_parameters() bic = (2 * n_samples * SGH * n_dim + np.log(n_samples) * g._n_parameters()) bound = n_dim * 3. / np.sqrt(n_samples) assert_true(np.abs(g.aic(X) - aic) / n_samples < bound) assert_true(np.abs(g.bic(X) - bic) / n_samples < bound) def check_positive_definite_covars(covariance_type): r"""Test that covariance matrices do not become non positive definite Due to the accumulation of round-off errors, the computation of the covariance matrices during the learning phase could lead to non-positive definite covariance matrices. Namely the use of the formula: .. math:: C = (\sum_i w_i x_i x_i^T) - \mu \mu^T instead of: .. math:: C = \sum_i w_i (x_i - \mu)(x_i - \mu)^T while mathematically equivalent, was observed a ``LinAlgError`` exception, when computing a ``GMM`` with full covariance matrices and fixed mean. This function ensures that some later optimization will not introduce the problem again. """ rng = np.random.RandomState(1) # we build a dataset with 2 2d component. The components are unbalanced # (respective weights 0.9 and 0.1) X = rng.randn(100, 2) X[-10:] += (3, 3) # Shift the 10 last points gmm = mixture.GMM(2, params="wc", covariance_type=covariance_type, min_covar=1e-3) # This is a non-regression test for issue #2640. The following call used # to trigger: # numpy.linalg.linalg.LinAlgError: 2-th leading minor not positive definite gmm.fit(X) if covariance_type == "diag" or covariance_type == "spherical": assert_greater(gmm.covars_.min(), 0) else: if covariance_type == "tied": covs = [gmm.covars_] else: covs = gmm.covars_ for c in covs: assert_greater(np.linalg.det(c), 0) def test_positive_definite_covars(): # Check positive definiteness for all covariance types for covariance_type in ["full", "tied", "diag", "spherical"]: yield check_positive_definite_covars, covariance_type def test_verbose_first_level(): # Create sample data X = rng.randn(30, 5) X[:10] += 2 g = mixture.GMM(n_components=2, n_init=2, verbose=1) old_stdout = sys.stdout sys.stdout = StringIO() try: g.fit(X) finally: sys.stdout = old_stdout def test_verbose_second_level(): # Create sample data X = rng.randn(30, 5) X[:10] += 2 g = mixture.GMM(n_components=2, n_init=2, verbose=2) old_stdout = sys.stdout sys.stdout = StringIO() try: g.fit(X) finally: sys.stdout = old_stdout
bsd-3-clause
alvarop/silta
sw/examples/drivers/max31855.py
1
1403
#!/usr/bin/env python # # SPI example (using the STM32F407 discovery board) # import sys import time import ctypes from silta import stm32f407 def bytes_to_int(byte_list): num = 0 for byte in range(len(byte_list)): num += byte_list[byte] << ((len(byte_list) - 1 - byte) * 8) return num class MAX31855(object): def __init__(self, bridge, cs_pin): self.bridge = bridge self.cs_pin = cs_pin self.last_fault = 0 # Set the CS line as an output self.bridge.gpiocfg(self.cs_pin, 'output') # Configure ~1.05MHz clock with CPOL=0,CPHA=0 self.bridge.spicfg(10500000, 0, 0) # CS is active low in this case self.bridge.gpio(self.cs_pin, 1) def read(self): # Read 32 bits txbuff = [0x00, 0x00, 0x00, 0x00] rval = self.bridge.spi(self.cs_pin, txbuff) if isinstance(rval, list): reg = bytes_to_int(rval) fault = ((reg >> 16) & 1) == 1 if fault: temperature = None last_fault = reg & 0x7 else: temperature = ctypes.c_int16((reg >> 16) & 0xFFFC).value >> 2 temperature = temperature * 0.25 return temperature else: print('SPI Error: ' + str(rval)) return None def get_last_fault(self): return last_fault
bsd-2-clause
eternalthinker/flask-server-rq-example
venv/lib/python2.7/site-packages/setuptools/package_index.py
84
38798
"""PyPI and direct package downloading""" import sys import os import re import shutil import socket import base64 import hashlib from functools import wraps from pkg_resources import ( CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST, require, Environment, find_distributions, safe_name, safe_version, to_filename, Requirement, DEVELOP_DIST, ) from setuptools import ssl_support from distutils import log from distutils.errors import DistutilsError from setuptools.compat import (urllib2, httplib, StringIO, HTTPError, urlparse, urlunparse, unquote, splituser, url2pathname, name2codepoint, unichr, urljoin, urlsplit, urlunsplit, ConfigParser) from setuptools.compat import filterfalse from fnmatch import translate from setuptools.py26compat import strip_fragment from setuptools.py27compat import get_all_headers EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.]+)$') HREF = re.compile("""href\\s*=\\s*['"]?([^'"> ]+)""", re.I) # this is here to fix emacs' cruddy broken syntax highlighting PYPI_MD5 = re.compile( '<a href="([^"#]+)">([^<]+)</a>\n\s+\\(<a (?:title="MD5 hash"\n\s+)' 'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\\)' ) URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):',re.I).match EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split() __all__ = [ 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst', 'interpret_distro_name', ] _SOCKET_TIMEOUT = 15 def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower.startswith('.win32-py',-16): py_ver = name[-7:-4] base = name[:-16] plat = 'win32' elif lower.endswith('.win-amd64.exe'): base = name[:-14] plat = 'win-amd64' elif lower.startswith('.win-amd64-py',-20): py_ver = name[-7:-4] base = name[:-20] plat = 'win-amd64' return base,py_ver,plat def egg_info_for_url(url): scheme, server, path, parameters, query, fragment = urlparse(url) base = unquote(path.split('/')[-1]) if server=='sourceforge.net' and base=='download': # XXX Yuck base = unquote(path.split('/')[-2]) if '#' in base: base, fragment = base.split('#',1) return base,fragment def distros_for_url(url, metadata=None): """Yield egg or source distribution objects that might be found at a URL""" base, fragment = egg_info_for_url(url) for dist in distros_for_location(url, base, metadata): yield dist if fragment: match = EGG_FRAGMENT.match(fragment) if match: for dist in interpret_distro_name( url, match.group(1), metadata, precedence = CHECKOUT_DIST ): yield dist def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretation return [Distribution.from_location(location, basename, metadata)] if basename.endswith('.exe'): win_base, py_ver, platform = parse_bdist_wininst(basename) if win_base is not None: return interpret_distro_name( location, win_base, metadata, py_ver, BINARY_DIST, platform ) # Try source distro extensions (.zip, .tgz, etc.) # for ext in EXTENSIONS: if basename.endswith(ext): basename = basename[:-len(ext)] return interpret_distro_name(location, basename, metadata) return [] # no extension matched def distros_for_filename(filename, metadata=None): """Yield possible egg or source distribution objects based on a filename""" return distros_for_location( normalize_path(filename), os.path.basename(filename), metadata ) def interpret_distro_name( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine! """ # Generate alternative interpretations of a source distro name # Because some packages are ambiguous as to name/versions split # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, # the spurious interpretations should be ignored, because in the event # there's also an "adns" package, the spurious "python-1.1.0" version will # compare lower than any numeric version number, and is therefore unlikely # to match a request for it. It's still a potential problem, though, and # in the long run PyPI and the distutils should go for "safe" names and # versions in distribution archive names (sdist and bdist). parts = basename.split('-') if not py_version: for i,p in enumerate(parts[2:]): if len(p)==5 and p.startswith('py2.'): return # It's a bdist_dumb, not an sdist -- bail out for p in range(1,len(parts)+1): yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence = precedence, platform = platform ) # From Python 2.7 docs def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element def unique_values(func): """ Wrap a function returning an iterable such that the resulting iterable only ever yields unique items. """ @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper REL = re.compile("""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I) # this line is here to fix emacs' cruddy broken syntax highlighting @unique_values def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for match in HREF.finditer(tag): yield urljoin(url, htmldecode(match.group(1))) for tag in ("<th>Home Page", "<th>Download URL"): pos = page.find(tag) if pos!=-1: match = HREF.search(page,pos) if match: yield urljoin(url, htmldecode(match.group(1))) user_agent = "Python-urllib/%s setuptools/%s" % ( sys.version[:3], require('setuptools')[0].version ) class ContentChecker(object): """ A null content checker that defines the interface for checking content """ def feed(self, block): """ Feed a block of data to the hash. """ return def is_valid(self): """ Check the hash. Return False if validation fails. """ return True def report(self, reporter, template): """ Call reporter with information about the checker (hash name) substituted into the template. """ return class HashChecker(ContentChecker): pattern = re.compile( r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)=' r'(?P<expected>[a-f0-9]+)' ) def __init__(self, hash_name, expected): self.hash_name = hash_name self.hash = hashlib.new(hash_name) self.expected = expected @classmethod def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls(**match.groupdict()) def feed(self, block): self.hash.update(block) def is_valid(self): return self.hash.hexdigest() == self.expected def report(self, reporter, template): msg = template % self.hash_name return reporter(msg) class PackageIndex(Environment): """A distribution index that scans web pages for download URLs""" def __init__( self, index_url="https://pypi.python.org/simple", hosts=('*',), ca_bundle=None, verify_ssl=True, *args, **kw ): Environment.__init__(self,*args,**kw) self.index_url = index_url + "/"[:not index_url.endswith('/')] self.scanned_urls = {} self.fetched_urls = {} self.package_pages = {} self.allows = re.compile('|'.join(map(translate,hosts))).match self.to_scan = [] if verify_ssl and ssl_support.is_available and (ca_bundle or ssl_support.find_ca_bundle()): self.opener = ssl_support.opener_for(ca_bundle) else: self.opener = urllib2.urlopen def process_url(self, url, retrieve=False): """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return else: dists = list(distros_for_url(url)) if dists: if not self.url_ok(url): return self.debug("Found link: %s", url) if dists or not retrieve or url in self.fetched_urls: list(map(self.add, dists)) return # don't need the actual page if not self.url_ok(url): self.fetched_urls[url] = True return self.info("Reading %s", url) self.fetched_urls[url] = True # prevent multiple fetch attempts f = self.open_url(url, "Download error on %s: %%s -- Some packages may not be found!" % url) if f is None: return self.fetched_urls[f.url] = True if 'html' not in f.headers.get('content-type', '').lower(): f.close() # not html, we can't process it return base = f.url # handle redirects page = f.read() if not isinstance(page, str): # We are in Python 3 and got bytes. We want str. if isinstance(f, HTTPError): # Errors have no charset, assume latin1: charset = 'latin-1' else: charset = f.headers.get_param('charset') or 'latin-1' page = page.decode(charset, "ignore") f.close() for match in HREF.finditer(page): link = urljoin(base, htmldecode(match.group(1))) self.process_url(link) if url.startswith(self.index_url) and getattr(f,'code',None)!=404: page = self.process_index(url, page) def process_filename(self, fn, nested=False): # process filenames or directories if not os.path.exists(fn): self.warn("Not found: %s", fn) return if os.path.isdir(fn) and not nested: path = os.path.realpath(fn) for item in os.listdir(path): self.process_filename(os.path.join(path,item), True) dists = distros_for_filename(fn) if dists: self.debug("Found: %s", fn) list(map(self.add, dists)) def url_ok(self, url, fatal=False): s = URL_SCHEME(url) if (s and s.group(1).lower()=='file') or self.allows(urlparse(url)[1]): return True msg = ("\nNote: Bypassing %s (disallowed host; see " "http://bit.ly/1dg9ijs for details).\n") if fatal: raise DistutilsError(msg % url) else: self.warn(msg, url) def scan_egg_links(self, search_path): for item in search_path: if os.path.isdir(item): for entry in os.listdir(item): if entry.endswith('.egg-link'): self.scan_egg_link(item, entry) def scan_egg_link(self, path, entry): lines = [_f for _f in map(str.strip, open(os.path.join(path, entry))) if _f] if len(lines)==2: for dist in find_distributions(os.path.join(path, lines[0])): dist.location = os.path.join(path, *lines) dist.precedence = SOURCE_DIST self.add(dist) def process_index(self,url,page): """Process the contents of a PyPI page""" def scan(link): # Process a URL to see if it's for a package page if link.startswith(self.index_url): parts = list(map( unquote, link[len(self.index_url):].split('/') )) if len(parts)==2 and '#' not in parts[1]: # it's a package page, sanitize and index it pkg = safe_name(parts[0]) ver = safe_version(parts[1]) self.package_pages.setdefault(pkg.lower(),{})[link] = True return to_filename(pkg), to_filename(ver) return None, None # process an index page into the package-page index for match in HREF.finditer(page): try: scan(urljoin(url, htmldecode(match.group(1)))) except ValueError: pass pkg, ver = scan(url) # ensure this page is in the page index if pkg: # process individual package page for new_url in find_external_links(url, page): # Process the found URL base, frag = egg_info_for_url(new_url) if base.endswith('.py') and not frag: if ver: new_url+='#egg=%s-%s' % (pkg,ver) else: self.need_version_info(url) self.scan_url(new_url) return PYPI_MD5.sub( lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1,3,2), page ) else: return "" # no sense double-scanning non-package pages def need_version_info(self, url): self.scan_all( "Page at %s links to .py file(s) without version info; an index " "scan is required.", url ) def scan_all(self, msg=None, *args): if self.index_url not in self.fetched_urls: if msg: self.warn(msg,*args) self.info( "Scanning index of all packages (this may take a while)" ) self.scan_url(self.index_url) def find_packages(self, requirement): self.scan_url(self.index_url + requirement.unsafe_name+'/') if not self.package_pages.get(requirement.key): # Fall back to safe version of the name self.scan_url(self.index_url + requirement.project_name+'/') if not self.package_pages.get(requirement.key): # We couldn't find the target package, so search the index page too self.not_found_in_index(requirement) for url in list(self.package_pages.get(requirement.key,())): # scan each page that might be related to the desired package self.scan_url(url) def obtain(self, requirement, installer=None): self.prescan() self.find_packages(requirement) for dist in self[requirement.key]: if dist in requirement: return dist self.debug("%s does not match %s", requirement, dist) return super(PackageIndex, self).obtain(requirement,installer) def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report(self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise DistutilsError( "%s validation failed for %s; " "possible download problem?" % ( checker.hash.name, os.path.basename(filename)) ) def add_find_links(self, urls): """Add `urls` to the list that will be prescanned for searches""" for url in urls: if ( self.to_scan is None # if we have already "gone online" or not URL_SCHEME(url) # or it's a local file/directory or url.startswith('file:') or list(distros_for_url(url)) # or a direct package link ): # then go ahead and process it now self.scan_url(url) else: # otherwise, defer retrieval till later self.to_scan.append(url) def prescan(self): """Scan urls scheduled for prescanning (e.g. --find-links)""" if self.to_scan: list(map(self.scan_url, self.to_scan)) self.to_scan = None # from now on, go ahead and process immediately def not_found_in_index(self, requirement): if self[requirement.key]: # we've seen at least one distro meth, msg = self.info, "Couldn't retrieve index page for %r" else: # no distros seen for this name, might be misspelled meth, msg = (self.warn, "Couldn't find index page for %r (maybe misspelled?)") meth(msg, requirement.unsafe_name) self.scan_all() def download(self, spec, tmpdir): """Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is automatically created alongside the downloaded file. If `spec` is a ``Requirement`` object or a string containing a project/version requirement spec, this method returns the location of a matching distribution (possibly after downloading it to `tmpdir`). If `spec` is a locally existing file or directory name, it is simply returned unchanged. If `spec` is a URL, it is downloaded to a subpath of `tmpdir`, and the local filename is returned. Various errors may be raised if a problem occurs during downloading. """ if not isinstance(spec,Requirement): scheme = URL_SCHEME(spec) if scheme: # It's a url, download it to tmpdir found = self._download_url(scheme.group(1), spec, tmpdir) base, fragment = egg_info_for_url(spec) if base.endswith('.py'): found = self.gen_setup(found,fragment,tmpdir) return found elif os.path.exists(spec): # Existing file or directory, just return it return spec else: try: spec = Requirement.parse(spec) except ValueError: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) return getattr(self.fetch_distribution(spec, tmpdir),'location',None) def fetch_distribution( self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = {} dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence==DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn("Skipping development or system egg: %s",dist) skipped[dist] = 1 continue if dist in req and (dist.precedence<=SOURCE_DIST or not source): return dist if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if local_index is not None: dist = dist or find(requirement, local_index) if dist is None: if self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) else: self.info("Best match: %s", dist) return dist.clone(location=self.download(dist.location, tmpdir)) def fetch(self, requirement, tmpdir, force_scan=False, source=False): """Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object. """ dist = self.fetch_distribution(requirement,tmpdir,force_scan,source) if dist is not None: return dist.location return None def gen_setup(self, filename, fragment, tmpdir): match = EGG_FRAGMENT.match(fragment) dists = match and [ d for d in interpret_distro_name(filename, match.group(1), None) if d.version ] or [] if len(dists)==1: # unambiguous ``#egg`` fragment basename = os.path.basename(filename) # Make sure the file has been downloaded to the temp dir. if os.path.dirname(filename) != tmpdir: dst = os.path.join(tmpdir, basename) from setuptools.command.easy_install import samefile if not samefile(filename, dst): shutil.copy2(filename, dst) filename=dst with open(os.path.join(tmpdir, 'setup.py'), 'w') as file: file.write( "from setuptools import setup\n" "setup(name=%r, version=%r, py_modules=[%r])\n" % ( dists[0].project_name, dists[0].version, os.path.splitext(basename)[0] ) ) return filename elif match: raise DistutilsError( "Can't unambiguously interpret project/version identifier %r; " "any dashes in the name or version should be escaped using " "underscores. %r" % (fragment,dists) ) else: raise DistutilsError( "Can't process plain .py files without an '#egg=name-version'" " suffix to enable automatic setup script generation." ) dl_blocksize = 8192 def _download_to(self, url, filename): self.info("Downloading %s", url) # Download the file fp, info = None, None try: checker = HashChecker.from_url(url) fp = self.open_url(strip_fragment(url)) if isinstance(fp, HTTPError): raise DistutilsError( "Can't download %s: %s %s" % (url, fp.code,fp.msg) ) headers = fp.info() blocknum = 0 bs = self.dl_blocksize size = -1 if "content-length" in headers: # Some servers return multiple Content-Length headers :( sizes = get_all_headers(headers, 'Content-Length') size = max(map(int, sizes)) self.reporthook(url, filename, blocknum, bs, size) with open(filename,'wb') as tfp: while True: block = fp.read(bs) if block: checker.feed(block) tfp.write(block) blocknum += 1 self.reporthook(url, filename, blocknum, bs, size) else: break self.check_hash(checker, filename, tfp) return headers finally: if fp: fp.close() def reporthook(self, url, filename, blocknum, blksize, size): pass # no-op def open_url(self, url, warning=None): if url.startswith('file:'): return local_open(url) try: return open_with_auth(url, self.opener) except (ValueError, httplib.InvalidURL) as v: msg = ' '.join([str(arg) for arg in v.args]) if warning: self.warn(warning, msg) else: raise DistutilsError('%s %s' % (url, msg)) except urllib2.HTTPError as v: return v except urllib2.URLError as v: if warning: self.warn(warning, v.reason) else: raise DistutilsError("Download error for %s: %s" % (url, v.reason)) except httplib.BadStatusLine as v: if warning: self.warn(warning, v.line) else: raise DistutilsError( '%s returned a bad status line. The server might be ' 'down, %s' % (url, v.line) ) except httplib.HTTPException as v: if warning: self.warn(warning, v) else: raise DistutilsError("Download error for %s: %s" % (url, v)) def _download_url(self, scheme, url, tmpdir): # Determine download filename # name, fragment = egg_info_for_url(url) if name: while '..' in name: name = name.replace('..','.').replace('\\','_') else: name = "__downloaded__" # default if URL has no path contents if name.endswith('.egg.zip'): name = name[:-4] # strip the extra .zip before download filename = os.path.join(tmpdir,name) # Download the file # if scheme=='svn' or scheme.startswith('svn+'): return self._download_svn(url, filename) elif scheme=='git' or scheme.startswith('git+'): return self._download_git(url, filename) elif scheme.startswith('hg+'): return self._download_hg(url, filename) elif scheme=='file': return url2pathname(urlparse(url)[2]) else: self.url_ok(url, True) # raises error if not allowed return self._attempt_download(url, filename) def scan_url(self, url): self.process_url(url, True) def _attempt_download(self, url, filename): headers = self._download_to(url, filename) if 'html' in headers.get('content-type','').lower(): return self._download_html(url, headers, filename) else: return filename def _download_html(self, url, headers, filename): file = open(filename) for line in file: if line.strip(): # Check for a subversion index page if re.search(r'<title>([^- ]+ - )?Revision \d+:', line): # it's a subversion index page: file.close() os.unlink(filename) return self._download_svn(url, filename) break # not an index page file.close() os.unlink(filename) raise DistutilsError("Unexpected HTML page found at "+url) def _download_svn(self, url, filename): url = url.split('#',1)[0] # remove any fragment for svn's sake creds = '' if url.lower().startswith('svn:') and '@' in url: scheme, netloc, path, p, q, f = urlparse(url) if not netloc and path.startswith('//') and '/' in path[2:]: netloc, path = path[2:].split('/',1) auth, host = splituser(netloc) if auth: if ':' in auth: user, pw = auth.split(':',1) creds = " --username=%s --password=%s" % (user, pw) else: creds = " --username="+auth netloc = host url = urlunparse((scheme, netloc, url, p, q, f)) self.info("Doing subversion checkout from %s to %s", url, filename) os.system("svn checkout%s -q %s %s" % (creds, url, filename)) return filename @staticmethod def _vcs_split_rev_from_url(url, pop_prefix=False): scheme, netloc, path, query, frag = urlsplit(url) scheme = scheme.split('+', 1)[-1] # Some fragment identification fails path = path.split('#',1)[0] rev = None if '@' in path: path, rev = path.rsplit('@', 1) # Also, discard fragment url = urlunsplit((scheme, netloc, path, query, '')) return url, rev def _download_git(self, url, filename): filename = filename.split('#',1)[0] url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True) self.info("Doing git clone from %s to %s", url, filename) os.system("git clone --quiet %s %s" % (url, filename)) if rev is not None: self.info("Checking out %s", rev) os.system("(cd %s && git checkout --quiet %s)" % ( filename, rev, )) return filename def _download_hg(self, url, filename): filename = filename.split('#',1)[0] url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True) self.info("Doing hg clone from %s to %s", url, filename) os.system("hg clone --quiet %s %s" % (url, filename)) if rev is not None: self.info("Updating to %s", rev) os.system("(cd %s && hg up -C -r %s >&-)" % ( filename, rev, )) return filename def debug(self, msg, *args): log.debug(msg, *args) def info(self, msg, *args): log.info(msg, *args) def warn(self, msg, *args): log.warn(msg, *args) # This pattern matches a character entity reference (a decimal numeric # references, a hexadecimal numeric reference, or a named reference). entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub def uchr(c): if not isinstance(c, int): return c if c>255: return unichr(c) return chr(c) def decode_entity(match): what = match.group(1) if what.startswith('#x'): what = int(what[2:], 16) elif what.startswith('#'): what = int(what[1:]) else: what = name2codepoint.get(what, match.group(0)) return uchr(what) def htmldecode(text): """Decode HTML entities in the given text.""" return entity_sub(decode_entity, text) def socket_timeout(timeout=15): def _socket_timeout(func): def _socket_timeout(*args, **kwargs): old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: return func(*args, **kwargs) finally: socket.setdefaulttimeout(old_timeout) return _socket_timeout return _socket_timeout def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:' + 'password'*10 >>> chr(10) in str(_encode_auth(long_auth)) False """ auth_s = unquote(auth) # convert to bytes auth_bytes = auth_s.encode() # use the legacy interface for Python 2.3 support encoded_bytes = base64.encodestring(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.replace('\n','') class Credential(object): """ A username/password pair. Use like a namedtuple. """ def __init__(self, username, password): self.username = username self.password = password def __iter__(self): yield self.username yield self.password def __str__(self): return '%(username)s:%(password)s' % vars(self) class PyPIConfig(ConfigParser.ConfigParser): def __init__(self): """ Load from ~/.pypirc """ defaults = dict.fromkeys(['username', 'password', 'repository'], '') ConfigParser.ConfigParser.__init__(self, defaults) rc = os.path.join(os.path.expanduser('~'), '.pypirc') if os.path.exists(rc): self.read(rc) @property def creds_by_repository(self): sections_with_repositories = [ section for section in self.sections() if self.get(section, 'repository').strip() ] return dict(map(self._get_repo_cred, sections_with_repositories)) def _get_repo_cred(self, section): repo = self.get(section, 'repository').strip() return repo, Credential( self.get(section, 'username').strip(), self.get(section, 'password').strip(), ) def find_credential(self, url): """ If the URL indicated appears to be a repository defined in this config, return the credential for that repository. """ for repository, cred in self.creds_by_repository.items(): if url.startswith(repository): return cred def open_with_auth(url, opener=urllib2.urlopen): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise httplib.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = splituser(netloc) else: auth = None if not auth: cred = PyPIConfig().find_credential(url) if cred: auth = str(cred) info = cred.username, url log.info('Authenticating as %s for %s (from .pypirc)' % info) if auth: auth = "Basic " + _encode_auth(auth) new_url = urlunparse((scheme,host,path,params,query,frag)) request = urllib2.Request(new_url) request.add_header("Authorization", auth) else: request = urllib2.Request(url) request.add_header('User-Agent', user_agent) fp = opener(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urlparse(fp.url) if s2==scheme and h2==host: fp.url = urlunparse((s2,netloc,path2,param2,query2,frag2)) return fp # adding a timeout to avoid freezing package_index open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth) def fix_sf_url(url): return url # backward compatibility def local_open(url): """Read a local path, with special support for directories""" scheme, server, path, param, query, frag = urlparse(url) filename = url2pathname(path) if os.path.isfile(filename): return urllib2.urlopen(url) elif path.endswith('/') and os.path.isdir(filename): files = [] for f in os.listdir(filename): if f=='index.html': with open(os.path.join(filename,f),'r') as fp: body = fp.read() break elif os.path.isdir(os.path.join(filename,f)): f+='/' files.append("<a href=%r>%s</a>" % (f,f)) else: body = ("<html><head><title>%s</title>" % url) + \ "</head><body>%s</body></html>" % '\n'.join(files) status, message = 200, "OK" else: status, message, body = 404, "Path not found", "Not found" headers = {'content-type': 'text/html'} return HTTPError(url, status, message, headers, StringIO(body))
apache-2.0
Lujeni/ansible
lib/ansible/modules/cloud/xenserver/xenserver_guest_info.py
11
7874
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, Bojan Vitnik <bvitnik@mainstream.rs> # 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 = r''' --- module: xenserver_guest_info short_description: Gathers information for virtual machines running on Citrix Hypervisor/XenServer host or pool description: > This module can be used to gather essential VM facts. version_added: '2.8' author: - Bojan Vitnik (@bvitnik) <bvitnik@mainstream.rs> notes: - Minimal supported version of XenServer is 5.6. - Module was tested with XenServer 6.5, 7.1, 7.2, 7.6, Citrix Hypervisor 8.0, XCP-ng 7.6 and 8.0. - 'To acquire XenAPI Python library, just run C(pip install XenAPI) on your Ansible Control Node. The library can also be found inside Citrix Hypervisor/XenServer SDK (downloadable from Citrix website). Copy the XenAPI.py file from the SDK to your Python site-packages on your Ansible Control Node to use it. Latest version of the library can also be acquired from GitHub: https://raw.githubusercontent.com/xapi-project/xen-api/master/scripts/examples/python/XenAPI.py' - 'If no scheme is specified in C(hostname), module defaults to C(http://) because C(https://) is problematic in most setups. Make sure you are accessing XenServer host in trusted environment or use C(https://) scheme explicitly.' - 'To use C(https://) scheme for C(hostname) you have to either import host certificate to your OS certificate store or use C(validate_certs: no) which requires XenAPI library from XenServer 7.2 SDK or newer and Python 2.7.9 or newer.' - This module was called C(xenserver_guest_facts) before Ansible 2.9. The usage did not change. requirements: - python >= 2.6 - XenAPI options: name: description: - Name of the VM to gather facts from. - VMs running on XenServer do not necessarily have unique names. The module will fail if multiple VMs with same name are found. - In case of multiple VMs with same name, use C(uuid) to uniquely specify VM to manage. - This parameter is case sensitive. type: str required: yes aliases: [ name_label ] uuid: description: - UUID of the VM to gather fact of. This is XenServer's unique identifier. - It is required if name is not unique. type: str extends_documentation_fragment: xenserver.documentation ''' EXAMPLES = r''' - name: Gather facts xenserver_guest_info: hostname: "{{ xenserver_hostname }}" username: "{{ xenserver_username }}" password: "{{ xenserver_password }}" name: testvm_11 delegate_to: localhost register: facts ''' RETURN = r''' instance: description: Metadata about the VM returned: always type: dict sample: { "cdrom": { "type": "none" }, "customization_agent": "native", "disks": [ { "name": "testvm_11-0", "name_desc": "", "os_device": "xvda", "size": 42949672960, "sr": "Local storage", "sr_uuid": "0af1245e-bdb0-ba33-1446-57a962ec4075", "vbd_userdevice": "0" }, { "name": "testvm_11-1", "name_desc": "", "os_device": "xvdb", "size": 42949672960, "sr": "Local storage", "sr_uuid": "0af1245e-bdb0-ba33-1446-57a962ec4075", "vbd_userdevice": "1" } ], "domid": "56", "folder": "", "hardware": { "memory_mb": 8192, "num_cpu_cores_per_socket": 2, "num_cpus": 4 }, "home_server": "", "is_template": false, "name": "testvm_11", "name_desc": "", "networks": [ { "gateway": "192.168.0.254", "gateway6": "fc00::fffe", "ip": "192.168.0.200", "ip6": [ "fe80:0000:0000:0000:e9cb:625a:32c5:c291", "fc00:0000:0000:0000:0000:0000:0000:0001" ], "mac": "ba:91:3a:48:20:76", "mtu": "1500", "name": "Pool-wide network associated with eth1", "netmask": "255.255.255.128", "prefix": "25", "prefix6": "64", "vif_device": "0" } ], "other_config": { "base_template_name": "Windows Server 2016 (64-bit)", "import_task": "OpaqueRef:e43eb71c-45d6-5351-09ff-96e4fb7d0fa5", "install-methods": "cdrom", "instant": "true", "mac_seed": "f83e8d8a-cfdc-b105-b054-ef5cb416b77e" }, "platform": { "acpi": "1", "apic": "true", "cores-per-socket": "2", "device_id": "0002", "hpet": "true", "nx": "true", "pae": "true", "timeoffset": "-25200", "vga": "std", "videoram": "8", "viridian": "true", "viridian_reference_tsc": "true", "viridian_time_ref_count": "true" }, "state": "poweredon", "uuid": "e3c0b2d5-5f05-424e-479c-d3df8b3e7cda", "xenstore_data": { "vm-data": "" } } ''' HAS_XENAPI = False try: import XenAPI HAS_XENAPI = True except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.xenserver import (xenserver_common_argument_spec, XAPI, XenServerObject, get_object_ref, gather_vm_params, gather_vm_facts) class XenServerVM(XenServerObject): """Class for managing XenServer VM. Attributes: vm_ref (str): XAPI reference to VM. vm_params (dict): A dictionary with VM parameters as returned by gather_vm_params() function. """ def __init__(self, module): """Inits XenServerVM using module parameters. Args: module: Reference to AnsibleModule object. """ super(XenServerVM, self).__init__(module) self.vm_ref = get_object_ref(self.module, self.module.params['name'], self.module.params['uuid'], obj_type="VM", fail=True, msg_prefix="VM search: ") self.gather_params() def gather_params(self): """Gathers all VM parameters available in XAPI database.""" self.vm_params = gather_vm_params(self.module, self.vm_ref) def gather_facts(self): """Gathers and returns VM facts.""" return gather_vm_facts(self.module, self.vm_params) def main(): argument_spec = xenserver_common_argument_spec() argument_spec.update( name=dict(type='str', aliases=['name_label']), uuid=dict(type='str'), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_one_of=[ ['name', 'uuid'], ], ) if module._name == 'xenserver_guest_facts': module.deprecate("The 'xenserver_guest_facts' module has been renamed to 'xenserver_guest_info'", version='2.13') result = {'failed': False, 'changed': False} # Module will exit with an error message if no VM is found. vm = XenServerVM(module) # Gather facts. result['instance'] = vm.gather_facts() if result['failed']: module.fail_json(**result) else: module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
funkring/fdoo
addons/l10n_ar/__init__.py
2120
1456
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 # ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
dcastro9/patternrec_ps2
code/alcohol_script.py
1
5623
from Dataset import Dataset from WTA_Hasher import WTAHasher from kNN_Classifier import kNNClassifier import numpy as np import matplotlib.pyplot as plt import copy ds_train_dir = "../datasets/alcohol/alcoholism_training.csv" ds_test_dir = "../datasets/alcohol/alcoholism_test.csv" results_dir = "../final_results/alcohol/" num_k_values = 10 weights = [1,1,1,1,1,3] ds_orig = Dataset(ds_train_dir, name='Original Data') ds_norm = Dataset(ds_train_dir, normalize=True, name='Normalized Data') ds_norm_weigh = Dataset(ds_train_dir, normalize=True, weights=weights, name='Norm & Weighted Data') ds_whiten = Dataset(ds_train_dir, whiten=True, name='Whitened Data') ds_orig_t = Dataset(ds_test_dir) ds_norm_t = Dataset(ds_test_dir, normalize=True) ds_norm_weigh_t = Dataset(ds_test_dir, normalize=True, weights=weights) ds_whiten_t = Dataset(ds_test_dir, whiten=True) alcohol_datasets = [[ds_orig, ds_orig_t], [ds_norm, ds_norm_t], [ds_norm_weigh, ds_norm_weigh_t], [ds_whiten, ds_whiten_t]] k_values = range(1,num_k_values*2,2) color=['red','blue','green','black'] labels=['20%', '50%', '80%', '100%'] folds=['2-fold', '5-fold', 'N-fold'] for ds in alcohol_datasets: train_data_all = ds[0].data test_data = ds[1].data # Accuracy for get 20%, 50%, 80% and 100% of the data. # Each subset will have train_accuracy = [[np.zeros(num_k_values), np.zeros(num_k_values), np.zeros(num_k_values)], [np.zeros(num_k_values), np.zeros(num_k_values), np.zeros(num_k_values)], [np.zeros(num_k_values), np.zeros(num_k_values), np.zeros(num_k_values)], [np.zeros(num_k_values), np.zeros(num_k_values), np.zeros(num_k_values)]] best_k_and_ds = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] for it in range(5): train_data_20, t = Dataset.getRandomPercent(train_data_all, 0.2) train_data_50, t = Dataset.getRandomPercent(train_data_all, 0.5) train_data_80, t = Dataset.getRandomPercent(train_data_all, 0.8) all_training_data = [train_data_20, train_data_50, train_data_80, train_data_all] # Only run on train_data_all once. if it > 0: all_training_data = all_training_data[:-1] for val in range(len(all_training_data)): for k in k_values: print str(it) + ": Training on: " + labels[val] + "for k value: " + str(k) + " for " + ds[0].name # Do 2-5-N Fold Cross Validation. cv_2 = Dataset.getkPartitions(all_training_data[val], 2) cv_5 = Dataset.getkPartitions(all_training_data[val], 5) cv_n = Dataset.getkPartitions(all_training_data[val], len(all_training_data[val])) cvs = [cv_2, cv_5, cv_n] cross_val_accuracy = [0, 0, 0] for cv_c in range(len(cvs)): # Does f-Fold cross validation. accuracy = 0 for fold in range(len(cvs[cv_c])): td = copy.deepcopy(cvs[cv_c]) # Copy the cross validation dataset. del td[fold] # Delete the item we're using for testing. td_reshaped = [] for elem in td: for item in elem: td_reshaped.append(item) knn = kNNClassifier(td_reshaped, k) # Initialize kNN. accuracy += knn.test(cvs[cv_c][fold]) # Test. accuracy /= len(cvs[cv_c]) if best_k_and_ds[val][cv_c] == 0: best_k_and_ds[val][cv_c] = [k, td_reshaped, accuracy] elif best_k_and_ds[val][cv_c][2] < accuracy: best_k_and_ds[val][cv_c] = [k, td_reshaped, accuracy] train_accuracy[val][cv_c][k/2] += accuracy # Write results to file. out_f = open(results_dir + ds[0].name + ".txt", 'w') for cnt in range(len(train_accuracy)): # Setup plot. plt.xlabel('k Values') plt.ylabel('Accuracy') plt.title(ds[0].name) average = True if cnt == len(train_accuracy) - 1: average = False for fold in range(len(train_accuracy[cnt])): if (average): train_accuracy[cnt][fold] /= 5 plt.plot(k_values, train_accuracy[cnt][fold], color=color[fold], label=folds[fold]) out_f.write(labels[cnt] + ":" + folds[fold] + ":" + str(train_accuracy[cnt][fold]) + "\n") # Save plot. plt.legend() plt.savefig(results_dir + ds[0].name + labels[cnt] + ".pdf") plt.clf() plt.cla() # Now we test with the original test data provided. out_f.write("\n\n Testing for best k & DS for:" + ds[0].name +"\n") for val in range(len(best_k_and_ds)): for fold in range(len(best_k_and_ds[val])): knn = kNNClassifier(best_k_and_ds[val][fold][1], best_k_and_ds[val][fold][0]) # Initialize kNN. out = knn.test(test_data) # Test. out_f.write(labels[val] + " with k:" + str(best_k_and_ds[val][fold][0]) + " at " + folds[fold] + " original accuracy:" + str(best_k_and_ds[val][fold][2]) + " vs accuracy:" + str(out) + "\n") # Close file. out_f.close()
mit
GaussDing/django
tests/test_runner/test_discover_runner.py
97
6079
import os from contextlib import contextmanager from unittest import TestSuite, TextTestRunner, defaultTestLoader from django.test import TestCase from django.test.runner import DiscoverRunner @contextmanager def change_cwd(directory): current_dir = os.path.abspath(os.path.dirname(__file__)) new_dir = os.path.join(current_dir, directory) old_cwd = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(old_cwd) class DiscoverRunnerTest(TestCase): def test_dotted_test_module(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests_sample"], ).countTestCases() self.assertEqual(count, 4) def test_dotted_test_class_vanilla_unittest(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests_sample.TestVanillaUnittest"], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_class_django_testcase(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests_sample.TestDjangoTestCase"], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_method_django_testcase(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests_sample.TestDjangoTestCase.test_sample"], ).countTestCases() self.assertEqual(count, 1) def test_pattern(self): count = DiscoverRunner( pattern="*_tests.py", ).build_suite(["test_discovery_sample"]).countTestCases() self.assertEqual(count, 1) def test_file_path(self): with change_cwd(".."): count = DiscoverRunner().build_suite( ["test_discovery_sample/"], ).countTestCases() self.assertEqual(count, 5) def test_empty_label(self): """ If the test label is empty, discovery should happen on the current working directory. """ with change_cwd("."): suite = DiscoverRunner().build_suite([]) self.assertEqual( suite._tests[0].id().split(".")[0], os.path.basename(os.getcwd()), ) def test_empty_test_case(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests_sample.EmptyTestCase"], ).countTestCases() self.assertEqual(count, 0) def test_discovery_on_package(self): count = DiscoverRunner().build_suite( ["test_discovery_sample.tests"], ).countTestCases() self.assertEqual(count, 1) def test_ignore_adjacent(self): """ When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module. This results in tests from adjacent modules being run when they should not. The discover runner avoids this behavior. """ count = DiscoverRunner().build_suite( ["test_discovery_sample.empty"], ).countTestCases() self.assertEqual(count, 0) def test_testcase_ordering(self): with change_cwd(".."): suite = DiscoverRunner().build_suite(["test_discovery_sample/"]) self.assertEqual( suite._tests[0].__class__.__name__, 'TestDjangoTestCase', msg="TestDjangoTestCase should be the first test case") self.assertEqual( suite._tests[1].__class__.__name__, 'TestZimpleTestCase', msg="TestZimpleTestCase should be the second test case") # All others can follow in unspecified order, including doctests self.assertIn('DocTestCase', [t.__class__.__name__ for t in suite._tests[2:]]) def test_duplicates_ignored(self): """ Tests shouldn't be discovered twice when discovering on overlapping paths. """ single = DiscoverRunner().build_suite(["gis_tests"]).countTestCases() dups = DiscoverRunner().build_suite( ["gis_tests", "gis_tests.geo3d"]).countTestCases() self.assertEqual(single, dups) def test_reverse(self): """ Reverse should reorder tests while maintaining the grouping specified by ``DiscoverRunner.reorder_by``. """ runner = DiscoverRunner(reverse=True) suite = runner.build_suite( test_labels=('test_discovery_sample', 'test_discovery_sample2')) self.assertIn('test_discovery_sample2', next(iter(suite)).id(), msg="Test labels should be reversed.") suite = runner.build_suite(test_labels=('test_discovery_sample2',)) suite = tuple(suite) self.assertIn('DjangoCase', suite[0].id(), msg="Test groups should not be reversed.") self.assertIn('SimpleCase', suite[4].id(), msg="Test groups order should be preserved.") self.assertIn('DjangoCase2', suite[0].id(), msg="Django test cases should be reversed.") self.assertIn('SimpleCase2', suite[4].id(), msg="Simple test cases should be reversed.") self.assertIn('UnittestCase2', suite[8].id(), msg="Unittest test cases should be reversed.") self.assertIn('test_2', suite[0].id(), msg="Methods of Django cases should be reversed.") self.assertIn('test_2', suite[4].id(), msg="Methods of simple cases should be reversed.") self.assertIn('test_2', suite[8].id(), msg="Methods of unittest cases should be reversed.") def test_overrideable_test_suite(self): self.assertEqual(DiscoverRunner().test_suite, TestSuite) def test_overrideable_test_runner(self): self.assertEqual(DiscoverRunner().test_runner, TextTestRunner) def test_overrideable_test_loader(self): self.assertEqual(DiscoverRunner().test_loader, defaultTestLoader)
bsd-3-clause
2014c2g2/2015cdag2_0421
static/Brython3.1.1-20150328-091302/Lib/xml/sax/__init__.py
637
3505
"""Simple API for XML (SAX) implementation for Python. This module provides an implementation of the SAX 2 interface; information about the Java version of the interface can be found at http://www.megginson.com/SAX/. The Python version of the interface is documented at <...>. This package contains the following modules: handler -- Base classes and constants which define the SAX 2 API for the 'client-side' of SAX for Python. saxutils -- Implementation of the convenience classes commonly used to work with SAX. xmlreader -- Base classes and constants which define the SAX 2 API for the parsers used with SAX for Python. expatreader -- Driver that allows use of the Expat parser with SAX. """ from .xmlreader import InputSource from .handler import ContentHandler, ErrorHandler from ._exceptions import SAXException, SAXNotRecognizedException, \ SAXParseException, SAXNotSupportedException, \ SAXReaderNotAvailable def parse(source, handler, errorHandler=ErrorHandler()): parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) parser.parse(source) def parseString(string, handler, errorHandler=ErrorHandler()): from io import BytesIO if errorHandler is None: errorHandler = ErrorHandler() parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) inpsrc = InputSource() inpsrc.setByteStream(BytesIO(string)) parser.parse(inpsrc) # this is the parser list used by the make_parser function if no # alternatives are given as parameters to the function default_parser_list = ["xml.sax.expatreader"] # tell modulefinder that importing sax potentially imports expatreader _false = 0 if _false: import xml.sax.expatreader import os, sys #if "PY_SAX_PARSER" in os.environ: # default_parser_list = os.environ["PY_SAX_PARSER"].split(",") del os _key = "python.xml.sax.parser" if sys.platform[:4] == "java" and sys.registry.containsKey(_key): default_parser_list = sys.registry.getProperty(_key).split(",") def make_parser(parser_list = []): """Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.""" for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) except ImportError as e: import sys if parser_name in sys.modules: # The parser module was found, but importing it # failed unexpectedly, pass this exception through raise except SAXReaderNotAvailable: # The parser module detected that it won't work properly, # so try the next one pass raise SAXReaderNotAvailable("No parsers found", None) # --- Internal utility methods used by make_parser if sys.platform[ : 4] == "java": def _create_parser(parser_name): from org.python.core import imp drv_module = imp.importName(parser_name, 0, globals()) return drv_module.create_parser() else: def _create_parser(parser_name): drv_module = __import__(parser_name,{},{},['create_parser']) return drv_module.create_parser() del sys
agpl-3.0
thaumos/ansible
lib/ansible/modules/network/aci/aci_interface_policy_fc.py
27
6184
#!/usr/bin/python # -*- coding: utf-8 -*- # 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': 'certified'} DOCUMENTATION = r''' --- module: aci_interface_policy_fc short_description: Manage Fibre Channel interface policies (fc:IfPol) description: - Manage ACI Fiber Channel interface policies on Cisco ACI fabrics. version_added: '2.4' options: fc_policy: description: - The name of the Fiber Channel interface policy. type: str required: yes aliases: [ name ] description: description: - The description of the Fiber Channel interface policy. type: str aliases: [ descr ] port_mode: description: - The Port Mode to use. - The APIC defaults to C(f) when unset during creation. type: str choices: [ f, np ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. type: str choices: [ absent, present, query ] default: present extends_documentation_fragment: aci seealso: - name: APIC Management Information Model reference description: More information about the internal APIC class B(fc:IfPol). link: https://developer.cisco.com/docs/apic-mim-ref/ author: - Dag Wieers (@dagwieers) ''' EXAMPLES = r''' - aci_interface_policy_fc: host: '{{ hostname }}' username: '{{ username }}' password: '{{ password }}' fc_policy: '{{ fc_policy }}' port_mode: '{{ port_mode }}' description: '{{ description }}' state: present delegate_to: localhost ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: str sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: str sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: str sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: str sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: str sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec def main(): argument_spec = aci_argument_spec() argument_spec.update( fc_policy=dict(type='str', aliases=['name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), port_mode=dict(type='str', choices=['f', 'np']), # No default provided on purpose state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['fc_policy']], ['state', 'present', ['fc_policy']], ], ) fc_policy = module.params['fc_policy'] port_mode = module.params['port_mode'] description = module.params['description'] state = module.params['state'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fcIfPol', aci_rn='infra/fcIfPol-{0}'.format(fc_policy), module_object=fc_policy, target_filter={'name': fc_policy}, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='fcIfPol', class_config=dict( name=fc_policy, descr=description, portMode=port_mode, ), ) aci.get_diff(aci_class='fcIfPol') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
gpl-3.0
yencarnacion/jaikuengine
.google_appengine/lib/django-1.2/django/db/backends/postgresql/creation.py
51
3650
from django.db.backends.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): # This dictionary maps Field objects to their associated PostgreSQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. data_types = { 'AutoField': 'serial', 'BooleanField': 'boolean', 'CharField': 'varchar(%(max_length)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 'DateField': 'date', 'DateTimeField': 'timestamp with time zone', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'FileField': 'varchar(%(max_length)s)', 'FilePathField': 'varchar(%(max_length)s)', 'FloatField': 'double precision', 'IntegerField': 'integer', 'BigIntegerField': 'bigint', 'IPAddressField': 'inet', 'NullBooleanField': 'boolean', 'OneToOneField': 'integer', 'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)', 'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)', 'SlugField': 'varchar(%(max_length)s)', 'SmallIntegerField': 'smallint', 'TextField': 'text', 'TimeField': 'time', } def sql_table_creation_suffix(self): assert self.connection.settings_dict['TEST_COLLATION'] is None, "PostgreSQL does not support collation setting at database creation time." if self.connection.settings_dict['TEST_CHARSET']: return "WITH ENCODING '%s'" % self.connection.settings_dict['TEST_CHARSET'] return '' def sql_indexes_for_field(self, model, f, style): if f.db_index and not f.unique: qn = self.connection.ops.quote_name db_table = model._meta.db_table tablespace = f.db_tablespace or model._meta.db_tablespace if tablespace: sql = self.connection.ops.tablespace_sql(tablespace) if sql: tablespace_sql = ' ' + sql else: tablespace_sql = '' else: tablespace_sql = '' def get_index_sql(index_name, opclass=''): return (style.SQL_KEYWORD('CREATE INDEX') + ' ' + style.SQL_TABLE(qn(index_name)) + ' ' + style.SQL_KEYWORD('ON') + ' ' + style.SQL_TABLE(qn(db_table)) + ' ' + "(%s%s)" % (style.SQL_FIELD(qn(f.column)), opclass) + "%s;" % tablespace_sql) output = [get_index_sql('%s_%s' % (db_table, f.column))] # Fields with database column types of `varchar` and `text` need # a second index that specifies their operator class, which is # needed when performing correct LIKE queries outside the # C locale. See #12234. db_type = f.db_type(connection=self.connection) if db_type.startswith('varchar'): output.append(get_index_sql('%s_%s_like' % (db_table, f.column), ' varchar_pattern_ops')) elif db_type.startswith('text'): output.append(get_index_sql('%s_%s_like' % (db_table, f.column), ' text_pattern_ops')) else: output = [] return output
apache-2.0
icexelloss/spark
sql/hive/src/test/resources/data/scripts/input20_script.py
131
1028
# # 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. # import sys import re line = sys.stdin.readline() x = 1 while line: tem = sys.stdin.readline() if line == tem: x += 1 else: print(str(x).strip()+'\t'+re.sub('\t', '_', line.strip())) line = tem x = 1
apache-2.0
OpusVL/odoo-trading-as
trading_as/res_partner.py
1
1361
# -*- coding: utf-8 -*- ############################################################################## # # Trading As Brands # Copyright (C) 2015 OpusVL (<http://opusvl.com/>) # # 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/>. # ############################################################################## from openerp import models, fields, api class ResPartner(models.Model): _inherit = 'res.partner' brand = fields.Many2one( string='Brand', help=( 'The trading name to use for branding documents for this partner.\n' + 'If blank, the default company branding will be used.' ), comodel_name='res.company.brand', ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
dhruv13J/scikit-learn
sklearn/tests/test_naive_bayes.py
142
17496
import pickle from io import BytesIO import numpy as np import scipy.sparse from sklearn.datasets import load_digits, load_iris from sklearn.cross_validation import cross_val_score, train_test_split from sklearn.externals.six.moves import zip from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB # Data is just 6 separable points in the plane X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) y = np.array([1, 1, 1, 2, 2, 2]) # A bit more random tests rng = np.random.RandomState(0) X1 = rng.normal(size=(10, 3)) y1 = (rng.normal(size=(10)) > 0).astype(np.int) # Data is 6 random integer points in a 100 dimensional space classified to # three classes. X2 = rng.randint(5, size=(6, 100)) y2 = np.array([1, 1, 2, 2, 3, 3]) def test_gnb(): # Gaussian Naive Bayes classification. # This checks that GaussianNB implements fit and predict and returns # correct values for a simple toy dataset. clf = GaussianNB() y_pred = clf.fit(X, y).predict(X) assert_array_equal(y_pred, y) y_pred_proba = clf.predict_proba(X) y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) # Test whether label mismatch between target y and classes raises # an Error # FIXME Remove this test once the more general partial_fit tests are merged assert_raises(ValueError, GaussianNB().partial_fit, X, y, classes=[0, 1]) def test_gnb_prior(): # Test whether class priors are properly set. clf = GaussianNB().fit(X, y) assert_array_almost_equal(np.array([3, 3]) / 6.0, clf.class_prior_, 8) clf.fit(X1, y1) # Check that the class priors sum to 1 assert_array_almost_equal(clf.class_prior_.sum(), 1) def test_gnb_sample_weight(): """Test whether sample weights are properly used in GNB. """ # Sample weights all being 1 should not change results sw = np.ones(6) clf = GaussianNB().fit(X, y) clf_sw = GaussianNB().fit(X, y, sw) assert_array_almost_equal(clf.theta_, clf_sw.theta_) assert_array_almost_equal(clf.sigma_, clf_sw.sigma_) # Fitting twice with half sample-weights should result # in same result as fitting once with full weights sw = rng.rand(y.shape[0]) clf1 = GaussianNB().fit(X, y, sample_weight=sw) clf2 = GaussianNB().partial_fit(X, y, classes=[1, 2], sample_weight=sw / 2) clf2.partial_fit(X, y, sample_weight=sw / 2) assert_array_almost_equal(clf1.theta_, clf2.theta_) assert_array_almost_equal(clf1.sigma_, clf2.sigma_) # Check that duplicate entries and correspondingly increased sample # weights yield the same result ind = rng.randint(0, X.shape[0], 20) sample_weight = np.bincount(ind, minlength=X.shape[0]) clf_dupl = GaussianNB().fit(X[ind], y[ind]) clf_sw = GaussianNB().fit(X, y, sample_weight) assert_array_almost_equal(clf_dupl.theta_, clf_sw.theta_) assert_array_almost_equal(clf_dupl.sigma_, clf_sw.sigma_) def test_discrete_prior(): # Test whether class priors are properly set. for cls in [BernoulliNB, MultinomialNB]: clf = cls().fit(X2, y2) assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0), clf.class_log_prior_, 8) def test_mnnb(): # Test Multinomial Naive Bayes classification. # This checks that MultinomialNB implements fit and predict and returns # correct values for a simple toy dataset. for X in [X2, scipy.sparse.csr_matrix(X2)]: # Check the ability to predict the learning set. clf = MultinomialNB() assert_raises(ValueError, clf.fit, -X, y2) y_pred = clf.fit(X, y2).predict(X) assert_array_equal(y_pred, y2) # Verify that np.log(clf.predict_proba(X)) gives the same results as # clf.predict_log_proba(X) y_pred_proba = clf.predict_proba(X) y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) # Check that incremental fitting yields the same results clf2 = MultinomialNB() clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2)) clf2.partial_fit(X[2:5], y2[2:5]) clf2.partial_fit(X[5:], y2[5:]) y_pred2 = clf2.predict(X) assert_array_equal(y_pred2, y2) y_pred_proba2 = clf2.predict_proba(X) y_pred_log_proba2 = clf2.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8) assert_array_almost_equal(y_pred_proba2, y_pred_proba) assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba) # Partial fit on the whole data at once should be the same as fit too clf3 = MultinomialNB() clf3.partial_fit(X, y2, classes=np.unique(y2)) y_pred3 = clf3.predict(X) assert_array_equal(y_pred3, y2) y_pred_proba3 = clf3.predict_proba(X) y_pred_log_proba3 = clf3.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba3), y_pred_log_proba3, 8) assert_array_almost_equal(y_pred_proba3, y_pred_proba) assert_array_almost_equal(y_pred_log_proba3, y_pred_log_proba) def check_partial_fit(cls): clf1 = cls() clf1.fit([[0, 1], [1, 0]], [0, 1]) clf2 = cls() clf2.partial_fit([[0, 1], [1, 0]], [0, 1], classes=[0, 1]) assert_array_equal(clf1.class_count_, clf2.class_count_) assert_array_equal(clf1.feature_count_, clf2.feature_count_) clf3 = cls() clf3.partial_fit([[0, 1]], [0], classes=[0, 1]) clf3.partial_fit([[1, 0]], [1]) assert_array_equal(clf1.class_count_, clf3.class_count_) assert_array_equal(clf1.feature_count_, clf3.feature_count_) def test_discretenb_partial_fit(): for cls in [MultinomialNB, BernoulliNB]: yield check_partial_fit, cls def test_gnb_partial_fit(): clf = GaussianNB().fit(X, y) clf_pf = GaussianNB().partial_fit(X, y, np.unique(y)) assert_array_almost_equal(clf.theta_, clf_pf.theta_) assert_array_almost_equal(clf.sigma_, clf_pf.sigma_) assert_array_almost_equal(clf.class_prior_, clf_pf.class_prior_) clf_pf2 = GaussianNB().partial_fit(X[0::2, :], y[0::2], np.unique(y)) clf_pf2.partial_fit(X[1::2], y[1::2]) assert_array_almost_equal(clf.theta_, clf_pf2.theta_) assert_array_almost_equal(clf.sigma_, clf_pf2.sigma_) assert_array_almost_equal(clf.class_prior_, clf_pf2.class_prior_) def test_discretenb_pickle(): # Test picklability of discrete naive Bayes classifiers for cls in [BernoulliNB, MultinomialNB, GaussianNB]: clf = cls().fit(X2, y2) y_pred = clf.predict(X2) store = BytesIO() pickle.dump(clf, store) clf = pickle.load(BytesIO(store.getvalue())) assert_array_equal(y_pred, clf.predict(X2)) if cls is not GaussianNB: # TODO re-enable me when partial_fit is implemented for GaussianNB # Test pickling of estimator trained with partial_fit clf2 = cls().partial_fit(X2[:3], y2[:3], classes=np.unique(y2)) clf2.partial_fit(X2[3:], y2[3:]) store = BytesIO() pickle.dump(clf2, store) clf2 = pickle.load(BytesIO(store.getvalue())) assert_array_equal(y_pred, clf2.predict(X2)) def test_input_check_fit(): # Test input checks for the fit method for cls in [BernoulliNB, MultinomialNB, GaussianNB]: # check shape consistency for number of samples at fit time assert_raises(ValueError, cls().fit, X2, y2[:-1]) # check shape consistency for number of input features at predict time clf = cls().fit(X2, y2) assert_raises(ValueError, clf.predict, X2[:, :-1]) def test_input_check_partial_fit(): for cls in [BernoulliNB, MultinomialNB]: # check shape consistency assert_raises(ValueError, cls().partial_fit, X2, y2[:-1], classes=np.unique(y2)) # classes is required for first call to partial fit assert_raises(ValueError, cls().partial_fit, X2, y2) # check consistency of consecutive classes values clf = cls() clf.partial_fit(X2, y2, classes=np.unique(y2)) assert_raises(ValueError, clf.partial_fit, X2, y2, classes=np.arange(42)) # check consistency of input shape for partial_fit assert_raises(ValueError, clf.partial_fit, X2[:, :-1], y2) # check consistency of input shape for predict assert_raises(ValueError, clf.predict, X2[:, :-1]) def test_discretenb_predict_proba(): # Test discrete NB classes' probability scores # The 100s below distinguish Bernoulli from multinomial. # FIXME: write a test to show this. X_bernoulli = [[1, 100, 0], [0, 1, 0], [0, 100, 1]] X_multinomial = [[0, 1], [1, 3], [4, 0]] # test binary case (1-d output) y = [0, 0, 2] # 2 is regression test for binary case, 02e673 for cls, X in zip([BernoulliNB, MultinomialNB], [X_bernoulli, X_multinomial]): clf = cls().fit(X, y) assert_equal(clf.predict(X[-1]), 2) assert_equal(clf.predict_proba(X[0]).shape, (1, 2)) assert_array_almost_equal(clf.predict_proba(X[:2]).sum(axis=1), np.array([1., 1.]), 6) # test multiclass case (2-d output, must sum to one) y = [0, 1, 2] for cls, X in zip([BernoulliNB, MultinomialNB], [X_bernoulli, X_multinomial]): clf = cls().fit(X, y) assert_equal(clf.predict_proba(X[0]).shape, (1, 3)) assert_equal(clf.predict_proba(X[:2]).shape, (2, 3)) assert_almost_equal(np.sum(clf.predict_proba(X[1])), 1) assert_almost_equal(np.sum(clf.predict_proba(X[-1])), 1) assert_almost_equal(np.sum(np.exp(clf.class_log_prior_)), 1) assert_almost_equal(np.sum(np.exp(clf.intercept_)), 1) def test_discretenb_uniform_prior(): # Test whether discrete NB classes fit a uniform prior # when fit_prior=False and class_prior=None for cls in [BernoulliNB, MultinomialNB]: clf = cls() clf.set_params(fit_prior=False) clf.fit([[0], [0], [1]], [0, 0, 1]) prior = np.exp(clf.class_log_prior_) assert_array_equal(prior, np.array([.5, .5])) def test_discretenb_provide_prior(): # Test whether discrete NB classes use provided prior for cls in [BernoulliNB, MultinomialNB]: clf = cls(class_prior=[0.5, 0.5]) clf.fit([[0], [0], [1]], [0, 0, 1]) prior = np.exp(clf.class_log_prior_) assert_array_equal(prior, np.array([.5, .5])) # Inconsistent number of classes with prior assert_raises(ValueError, clf.fit, [[0], [1], [2]], [0, 1, 2]) assert_raises(ValueError, clf.partial_fit, [[0], [1]], [0, 1], classes=[0, 1, 1]) def test_discretenb_provide_prior_with_partial_fit(): # Test whether discrete NB classes use provided prior # when using partial_fit iris = load_iris() iris_data1, iris_data2, iris_target1, iris_target2 = train_test_split( iris.data, iris.target, test_size=0.4, random_state=415) for cls in [BernoulliNB, MultinomialNB]: for prior in [None, [0.3, 0.3, 0.4]]: clf_full = cls(class_prior=prior) clf_full.fit(iris.data, iris.target) clf_partial = cls(class_prior=prior) clf_partial.partial_fit(iris_data1, iris_target1, classes=[0, 1, 2]) clf_partial.partial_fit(iris_data2, iris_target2) assert_array_almost_equal(clf_full.class_log_prior_, clf_partial.class_log_prior_) def test_sample_weight_multiclass(): for cls in [BernoulliNB, MultinomialNB]: # check shape consistency for number of samples at fit time yield check_sample_weight_multiclass, cls def check_sample_weight_multiclass(cls): X = [ [0, 0, 1], [0, 1, 1], [0, 1, 1], [1, 0, 0], ] y = [0, 0, 1, 2] sample_weight = np.array([1, 1, 2, 2], dtype=np.float) sample_weight /= sample_weight.sum() clf = cls().fit(X, y, sample_weight=sample_weight) assert_array_equal(clf.predict(X), [0, 1, 1, 2]) # Check sample weight using the partial_fit method clf = cls() clf.partial_fit(X[:2], y[:2], classes=[0, 1, 2], sample_weight=sample_weight[:2]) clf.partial_fit(X[2:3], y[2:3], sample_weight=sample_weight[2:3]) clf.partial_fit(X[3:], y[3:], sample_weight=sample_weight[3:]) assert_array_equal(clf.predict(X), [0, 1, 1, 2]) def test_sample_weight_mnb(): clf = MultinomialNB() clf.fit([[1, 2], [1, 2], [1, 0]], [0, 0, 1], sample_weight=[1, 1, 4]) assert_array_equal(clf.predict([1, 0]), [1]) positive_prior = np.exp(clf.intercept_[0]) assert_array_almost_equal([1 - positive_prior, positive_prior], [1 / 3., 2 / 3.]) def test_coef_intercept_shape(): # coef_ and intercept_ should have shapes as in other linear models. # Non-regression test for issue #2127. X = [[1, 0, 0], [1, 1, 1]] y = [1, 2] # binary classification for clf in [MultinomialNB(), BernoulliNB()]: clf.fit(X, y) assert_equal(clf.coef_.shape, (1, 3)) assert_equal(clf.intercept_.shape, (1,)) def test_check_accuracy_on_digits(): # Non regression test to make sure that any further refactoring / optim # of the NB models do not harm the performance on a slightly non-linearly # separable dataset digits = load_digits() X, y = digits.data, digits.target binary_3v8 = np.logical_or(digits.target == 3, digits.target == 8) X_3v8, y_3v8 = X[binary_3v8], y[binary_3v8] # Multinomial NB scores = cross_val_score(MultinomialNB(alpha=10), X, y, cv=10) assert_greater(scores.mean(), 0.86) scores = cross_val_score(MultinomialNB(alpha=10), X_3v8, y_3v8, cv=10) assert_greater(scores.mean(), 0.94) # Bernoulli NB scores = cross_val_score(BernoulliNB(alpha=10), X > 4, y, cv=10) assert_greater(scores.mean(), 0.83) scores = cross_val_score(BernoulliNB(alpha=10), X_3v8 > 4, y_3v8, cv=10) assert_greater(scores.mean(), 0.92) # Gaussian NB scores = cross_val_score(GaussianNB(), X, y, cv=10) assert_greater(scores.mean(), 0.77) scores = cross_val_score(GaussianNB(), X_3v8, y_3v8, cv=10) assert_greater(scores.mean(), 0.86) def test_feature_log_prob_bnb(): # Test for issue #4268. # Tests that the feature log prob value computed by BernoulliNB when # alpha=1.0 is equal to the expression given in Manning, Raghavan, # and Schuetze's "Introduction to Information Retrieval" book: # http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html X = np.array([[0, 0, 0], [1, 1, 0], [0, 1, 0], [1, 0, 1], [0, 1, 0]]) Y = np.array([0, 0, 1, 2, 2]) # Fit Bernoulli NB w/ alpha = 1.0 clf = BernoulliNB(alpha=1.0) clf.fit(X, Y) # Manually form the (log) numerator and denominator that # constitute P(feature presence | class) num = np.log(clf.feature_count_ + 1.0) denom = np.tile(np.log(clf.class_count_ + 2.0), (X.shape[1], 1)).T # Check manual estimate matches assert_array_equal(clf.feature_log_prob_, (num - denom)) def test_bnb(): # Tests that BernoulliNB when alpha=1.0 gives the same values as # those given for the toy example in Manning, Raghavan, and # Schuetze's "Introduction to Information Retrieval" book: # http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html # Training data points are: # Chinese Beijing Chinese (class: China) # Chinese Chinese Shanghai (class: China) # Chinese Macao (class: China) # Tokyo Japan Chinese (class: Japan) # Features are Beijing, Chinese, Japan, Macao, Shanghai, and Tokyo X = np.array([[1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1]]) # Classes are China (0), Japan (1) Y = np.array([0, 0, 0, 1]) # Fit BernoulliBN w/ alpha = 1.0 clf = BernoulliNB(alpha=1.0) clf.fit(X, Y) # Check the class prior is correct class_prior = np.array([0.75, 0.25]) assert_array_almost_equal(np.exp(clf.class_log_prior_), class_prior) # Check the feature probabilities are correct feature_prob = np.array([[0.4, 0.8, 0.2, 0.4, 0.4, 0.2], [1/3.0, 2/3.0, 2/3.0, 1/3.0, 1/3.0, 2/3.0]]) assert_array_almost_equal(np.exp(clf.feature_log_prob_), feature_prob) # Testing data point is: # Chinese Chinese Chinese Tokyo Japan X_test = np.array([0, 1, 1, 0, 0, 1]) # Check the predictive probabilities are correct unnorm_predict_proba = np.array([[0.005183999999999999, 0.02194787379972565]]) predict_proba = unnorm_predict_proba / np.sum(unnorm_predict_proba) assert_array_almost_equal(clf.predict_proba(X_test), predict_proba)
bsd-3-clause
pkappesser/youtube-dl
youtube_dl/extractor/anysex.py
224
2085
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( parse_duration, int_or_none, ) class AnySexIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?anysex\.com/(?P<id>\d+)' _TEST = { 'url': 'http://anysex.com/156592/', 'md5': '023e9fbb7f7987f5529a394c34ad3d3d', 'info_dict': { 'id': '156592', 'ext': 'mp4', 'title': 'Busty and sexy blondie in her bikini strips for you', 'description': 'md5:de9e418178e2931c10b62966474e1383', 'categories': ['Erotic'], 'duration': 270, 'age_limit': 18, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) video_url = self._html_search_regex(r"video_url\s*:\s*'([^']+)'", webpage, 'video URL') title = self._html_search_regex(r'<title>(.*?)</title>', webpage, 'title') description = self._html_search_regex( r'<div class="description"[^>]*>([^<]+)</div>', webpage, 'description', fatal=False) thumbnail = self._html_search_regex( r'preview_url\s*:\s*\'(.*?)\'', webpage, 'thumbnail', fatal=False) categories = re.findall( r'<a href="http://anysex\.com/categories/[^"]+" title="[^"]*">([^<]+)</a>', webpage) duration = parse_duration(self._search_regex( r'<b>Duration:</b> (?:<q itemprop="duration">)?(\d+:\d+)', webpage, 'duration', fatal=False)) view_count = int_or_none(self._html_search_regex( r'<b>Views:</b> (\d+)', webpage, 'view count', fatal=False)) return { 'id': video_id, 'url': video_url, 'ext': 'mp4', 'title': title, 'description': description, 'thumbnail': thumbnail, 'categories': categories, 'duration': duration, 'view_count': view_count, 'age_limit': 18, }
unlicense
Edraak/edraak-platform
lms/djangoapps/courseware/tests/test_view_authentication.py
9
17630
import datetime import pytz from django.urls import reverse from mock import patch from nose.plugins.attrib import attr from six import text_type from courseware.access import has_access from courseware.tests.factories import ( BetaTesterFactory, GlobalStaffFactory, InstructorFactory, OrgInstructorFactory, OrgStaffFactory, StaffFactory ) from courseware.tests.helpers import CourseAccessTestMixin, LoginEnrollmentTestCase from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired from student.tests.factories import CourseEnrollmentFactory, UserFactory from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory @attr(shard=1) class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnrollmentTestCase): """ Check that view authentication works properly. """ ACCOUNT_INFO = [('view@test.com', 'foo'), ('view2@test.com', 'foo')] ENABLED_SIGNALS = ['course_published'] @staticmethod def _reverse_urls(names, course): """ Reverse a list of course urls. `names` is a list of URL names that correspond to sections in a course. `course` is the instance of CourseDescriptor whose section URLs are to be returned. Returns a list URLs corresponding to section in the passed in course. """ return [reverse(name, kwargs={'course_id': text_type(course.id)}) for name in names] def _check_non_staff_light(self, course): """ Check that non-staff have access to light urls. `course` is an instance of CourseDescriptor. """ urls = [reverse('about_course', kwargs={'course_id': text_type(course.id)}), reverse('courses')] for url in urls: self.assert_request_status_code(200, url) def _check_non_staff_dark(self, course): """ Check that non-staff don't have access to dark urls. """ names = ['courseware', 'progress'] urls = self._reverse_urls(names, course) urls.extend([ reverse('book', kwargs={'course_id': text_type(course.id), 'book_index': index}) for index, __ in enumerate(course.textbooks) ]) for url in urls: self.assert_request_status_code(302, url) self.assert_request_status_code( 404, reverse('instructor_dashboard', kwargs={'course_id': text_type(course.id)}) ) def _check_staff(self, course): """ Check that access is right for staff in course. """ names = ['about_course', 'instructor_dashboard', 'progress'] urls = self._reverse_urls(names, course) urls.extend([ reverse('book', kwargs={'course_id': text_type(course.id), 'book_index': index}) for index in xrange(len(course.textbooks)) ]) for url in urls: self.assert_request_status_code(200, url) # The student progress tab is not accessible to a student # before launch, so the instructor view-as-student feature # should return a 404. # TODO (vshnayder): If this is not the behavior we want, will need # to make access checking smarter and understand both the effective # user (the student), and the requesting user (the prof) url = reverse( 'student_progress', kwargs={ 'course_id': text_type(course.id), 'student_id': self.enrolled_user.id, } ) self.assert_request_status_code(302, url) # The courseware url should redirect, not 200 url = self._reverse_urls(['courseware'], course)[0] self.assert_request_status_code(302, url) def login(self, user): return super(TestViewAuth, self).login(user.email, 'test') def setUp(self): super(TestViewAuth, self).setUp() self.course = CourseFactory.create(number='999', display_name='Robot_Super_Course') self.courseware_chapter = ItemFactory.create(display_name='courseware') self.overview_chapter = ItemFactory.create( parent_location=self.course.location, display_name='Super Overview' ) self.welcome_section = ItemFactory.create( parent_location=self.overview_chapter.location, display_name='Super Welcome' ) self.welcome_unit = ItemFactory.create( parent_location=self.welcome_section.location, display_name='Super Unit' ) self.course = modulestore().get_course(self.course.id) self.test_course = CourseFactory.create(org=self.course.id.org) self.other_org_course = CourseFactory.create(org='Other_Org_Course') self.sub_courseware_chapter = ItemFactory.create( parent_location=self.test_course.location, display_name='courseware' ) self.sub_overview_chapter = ItemFactory.create( parent_location=self.sub_courseware_chapter.location, display_name='Overview' ) self.sub_welcome_section = ItemFactory.create( parent_location=self.sub_overview_chapter.location, display_name='Welcome' ) self.sub_welcome_unit = ItemFactory.create( parent_location=self.sub_welcome_section.location, display_name='New Unit' ) self.test_course = modulestore().get_course(self.test_course.id) self.global_staff_user = GlobalStaffFactory() self.unenrolled_user = UserFactory(last_name="Unenrolled") self.enrolled_user = UserFactory(last_name="Enrolled") CourseEnrollmentFactory(user=self.enrolled_user, course_id=self.course.id) CourseEnrollmentFactory(user=self.enrolled_user, course_id=self.test_course.id) self.staff_user = StaffFactory(course_key=self.course.id) self.instructor_user = InstructorFactory(course_key=self.course.id) self.org_staff_user = OrgStaffFactory(course_key=self.course.id) self.org_instructor_user = OrgInstructorFactory(course_key=self.course.id) def test_redirection_unenrolled(self): """ Verify unenrolled student is redirected to the 'about' section of the chapter instead of the 'Welcome' section after clicking on the courseware tab. """ self.login(self.unenrolled_user) response = self.client.get(reverse('courseware', kwargs={'course_id': text_type(self.course.id)})) self.assertRedirects( response, reverse( 'about_course', args=[text_type(self.course.id)] ) ) def test_redirection_enrolled(self): """ Verify enrolled student is redirected to the 'Welcome' section of the chapter after clicking on the courseware tab. """ self.login(self.enrolled_user) response = self.client.get( reverse( 'courseware', kwargs={'course_id': text_type(self.course.id)} ) ) self.assertRedirects( response, reverse( 'courseware_section', kwargs={'course_id': text_type(self.course.id), 'chapter': self.overview_chapter.url_name, 'section': self.welcome_section.url_name} ) ) def test_redirection_missing_enterprise_consent(self): """ Verify that enrolled students are redirected to the Enterprise consent URL if a linked Enterprise Customer requires data sharing consent and it has not yet been provided. """ self.login(self.enrolled_user) url = reverse( 'courseware', kwargs={'course_id': text_type(self.course.id)} ) self.verify_consent_required(self.client, url, status_code=302) def test_instructor_page_access_nonstaff(self): """ Verify non-staff cannot load the instructor dashboard, the grade views, and student profile pages. """ self.login(self.enrolled_user) urls = [reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}), reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)})] # Shouldn't be able to get to the instructor pages for url in urls: self.assert_request_status_code(404, url) def test_staff_course_access(self): """ Verify staff can load the staff dashboard, the grade views, and student profile pages for their course. """ self.login(self.staff_user) # Now should be able to get to self.course, but not self.test_course url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(404, url) def test_instructor_course_access(self): """ Verify instructor can load the instructor dashboard, the grade views, and student profile pages for their course. """ self.login(self.instructor_user) # Now should be able to get to self.course, but not self.test_course url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(404, url) def test_org_staff_access(self): """ Verify org staff can load the instructor dashboard, the grade views, and student profile pages for course in their org. """ self.login(self.org_staff_user) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.other_org_course.id)}) self.assert_request_status_code(404, url) def test_org_instructor_access(self): """ Verify org instructor can load the instructor dashboard, the grade views, and student profile pages for course in their org. """ self.login(self.org_instructor_user) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(200, url) url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.other_org_course.id)}) self.assert_request_status_code(404, url) def test_global_staff_access(self): """ Verify the global staff user can access any course. """ self.login(self.global_staff_user) # and now should be able to load both urls = [reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}), reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)})] for url in urls: self.assert_request_status_code(200, url) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_dark_launch_enrolled_student(self): """ Make sure that before course start, students can't access course pages. """ # Make courses start in the future now = datetime.datetime.now(pytz.UTC) tomorrow = now + datetime.timedelta(days=1) self.course.start = tomorrow self.test_course.start = tomorrow self.course = self.update_course(self.course, self.user.id) self.test_course = self.update_course(self.test_course, self.user.id) self.assertFalse(self.course.has_started()) self.assertFalse(self.test_course.has_started()) # First, try with an enrolled student self.login(self.enrolled_user) # shouldn't be able to get to anything except the light pages self._check_non_staff_light(self.course) self._check_non_staff_dark(self.course) self._check_non_staff_light(self.test_course) self._check_non_staff_dark(self.test_course) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_dark_launch_instructor(self): """ Make sure that before course start instructors can access the page for their course. """ now = datetime.datetime.now(pytz.UTC) tomorrow = now + datetime.timedelta(days=1) self.course.start = tomorrow self.test_course.start = tomorrow self.course = self.update_course(self.course, self.user.id) self.test_course = self.update_course(self.test_course, self.user.id) self.login(self.instructor_user) # Enroll in the classes---can't see courseware otherwise. self.enroll(self.course, True) self.enroll(self.test_course, True) # should now be able to get to everything for self.course self._check_staff(self.course) self._check_non_staff_light(self.test_course) self._check_non_staff_dark(self.test_course) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_dark_launch_global_staff(self): """ Make sure that before course start staff can access course pages. """ now = datetime.datetime.now(pytz.UTC) tomorrow = now + datetime.timedelta(days=1) self.course.start = tomorrow self.test_course.start = tomorrow self.course = self.update_course(self.course, self.user.id) self.test_course = self.update_course(self.test_course, self.user.id) self.login(self.global_staff_user) self.enroll(self.course, True) self.enroll(self.test_course, True) # and now should be able to load both self._check_staff(self.course) self._check_staff(self.test_course) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_enrollment_period(self): """ Check that enrollment periods work. """ # Make courses start in the future now = datetime.datetime.now(pytz.UTC) tomorrow = now + datetime.timedelta(days=1) nextday = tomorrow + datetime.timedelta(days=1) yesterday = now - datetime.timedelta(days=1) # self.course's enrollment period hasn't started self.course.enrollment_start = tomorrow self.course.enrollment_end = nextday # test_course course's has self.test_course.enrollment_start = yesterday self.test_course.enrollment_end = tomorrow self.course = self.update_course(self.course, self.user.id) self.test_course = self.update_course(self.test_course, self.user.id) # First, try with an enrolled student self.login(self.unenrolled_user) self.assertFalse(self.enroll(self.course)) self.assertTrue(self.enroll(self.test_course)) # Then, try as an instructor self.logout() self.login(self.instructor_user) self.assertTrue(self.enroll(self.course)) # Then, try as global staff self.logout() self.login(self.global_staff_user) self.assertTrue(self.enroll(self.course)) @attr(shard=1) class TestBetatesterAccess(ModuleStoreTestCase, CourseAccessTestMixin): """ Tests for the beta tester feature """ def setUp(self): super(TestBetatesterAccess, self).setUp() now = datetime.datetime.now(pytz.UTC) tomorrow = now + datetime.timedelta(days=1) self.course = CourseFactory(days_early_for_beta=2, start=tomorrow) self.content = ItemFactory(parent=self.course) self.normal_student = UserFactory() self.beta_tester = BetaTesterFactory(course_key=self.course.id) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_course_beta_period(self): """ Check that beta-test access works for courses. """ self.assertFalse(self.course.has_started()) self.assertCannotAccessCourse(self.normal_student, 'load', self.course) self.assertCanAccessCourse(self.beta_tester, 'load', self.course) @patch.dict('courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_content_beta_period(self): """ Check that beta-test access works for content. """ # student user shouldn't see it self.assertFalse(has_access(self.normal_student, 'load', self.content, self.course.id)) # now the student should see it self.assertTrue(has_access(self.beta_tester, 'load', self.content, self.course.id))
agpl-3.0
goyalankit/po-compiler
object_files/networkx-1.8.1/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py
89
7721
#!/usr/bin/env python from nose.tools import * from nose import SkipTest import networkx from nose.plugins.attrib import attr from networkx import edge_current_flow_betweenness_centrality \ as edge_current_flow from networkx import approximate_current_flow_betweenness_centrality \ as approximate_cfbc class TestFlowBetweennessCentrality(object): numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test @classmethod def setupClass(cls): global np try: import numpy as np import scipy except ImportError: raise SkipTest('NumPy not available.') def test_K4_normalized(self): """Betweenness centrality: K4""" G=networkx.complete_graph(4) b=networkx.current_flow_betweenness_centrality(G,normalized=True) b_answer={0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) G.add_edge(0,1,{'weight':0.5,'other':0.3}) b=networkx.current_flow_betweenness_centrality(G,normalized=True,weight=None) for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) wb_answer={0: 0.2222222, 1: 0.2222222, 2: 0.30555555, 3: 0.30555555} b=networkx.current_flow_betweenness_centrality(G,normalized=True) for n in sorted(G): assert_almost_equal(b[n],wb_answer[n]) wb_answer={0: 0.2051282, 1: 0.2051282, 2: 0.33974358, 3: 0.33974358} b=networkx.current_flow_betweenness_centrality(G,normalized=True,weight='other') for n in sorted(G): assert_almost_equal(b[n],wb_answer[n]) def test_K4(self): """Betweenness centrality: K4""" G=networkx.complete_graph(4) for solver in ['full','lu','cg']: b=networkx.current_flow_betweenness_centrality(G, normalized=False, solver=solver) b_answer={0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) def test_P4_normalized(self): """Betweenness centrality: P4 normalized""" G=networkx.path_graph(4) b=networkx.current_flow_betweenness_centrality(G,normalized=True) b_answer={0: 0, 1: 2./3, 2: 2./3, 3:0} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) def test_P4(self): """Betweenness centrality: P4""" G=networkx.path_graph(4) b=networkx.current_flow_betweenness_centrality(G,normalized=False) b_answer={0: 0, 1: 2, 2: 2, 3: 0} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) def test_star(self): """Betweenness centrality: star """ G=networkx.Graph() G.add_star(['a','b','c','d']) b=networkx.current_flow_betweenness_centrality(G,normalized=True) b_answer={'a': 1.0, 'b': 0.0, 'c': 0.0, 'd':0.0} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) def test_solers(self): """Betweenness centrality: alternate solvers""" G=networkx.complete_graph(4) for solver in ['full','lu','cg']: b=networkx.current_flow_betweenness_centrality(G,normalized=False, solver=solver) b_answer={0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75} for n in sorted(G): assert_almost_equal(b[n],b_answer[n]) class TestApproximateFlowBetweennessCentrality(object): numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test @classmethod def setupClass(cls): global np global assert_allclose try: import numpy as np import scipy from numpy.testing import assert_allclose except ImportError: raise SkipTest('NumPy not available.') def test_K4_normalized(self): "Approximate current-flow betweenness centrality: K4 normalized" G=networkx.complete_graph(4) b=networkx.current_flow_betweenness_centrality(G,normalized=True) epsilon=0.1 ba = approximate_cfbc(G,normalized=True, epsilon=0.5*epsilon) for n in sorted(G): assert_allclose(b[n],ba[n],atol=epsilon) def test_K4(self): "Approximate current-flow betweenness centrality: K4" G=networkx.complete_graph(4) b=networkx.current_flow_betweenness_centrality(G,normalized=False) epsilon=0.1 ba = approximate_cfbc(G,normalized=False, epsilon=0.5*epsilon) for n in sorted(G): assert_allclose(b[n],ba[n],atol=epsilon*len(G)**2) def test_star(self): "Approximate current-flow betweenness centrality: star" G=networkx.Graph() G.add_star(['a','b','c','d']) b=networkx.current_flow_betweenness_centrality(G,normalized=True) epsilon=0.1 ba = approximate_cfbc(G,normalized=True, epsilon=0.5*epsilon) for n in sorted(G): assert_allclose(b[n],ba[n],atol=epsilon) def test_grid(self): "Approximate current-flow betweenness centrality: 2d grid" G=networkx.grid_2d_graph(4,4) b=networkx.current_flow_betweenness_centrality(G,normalized=True) epsilon=0.1 ba = approximate_cfbc(G,normalized=True, epsilon=0.5*epsilon) for n in sorted(G): assert_allclose(b[n],ba[n],atol=epsilon) def test_solvers(self): "Approximate current-flow betweenness centrality: solvers" G=networkx.complete_graph(4) epsilon=0.1 for solver in ['full','lu','cg']: b=approximate_cfbc(G,normalized=False,solver=solver, epsilon=0.5*epsilon) b_answer={0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75} for n in sorted(G): assert_allclose(b[n],b_answer[n],atol=epsilon) class TestWeightedFlowBetweennessCentrality(object): pass class TestEdgeFlowBetweennessCentrality(object): numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test @classmethod def setupClass(cls): global np try: import numpy as np import scipy except ImportError: raise SkipTest('NumPy not available.') def test_K4(self): """Edge flow betweenness centrality: K4""" G=networkx.complete_graph(4) b=edge_current_flow(G,normalized=True) b_answer=dict.fromkeys(G.edges(),0.25) for (s,t),v1 in b_answer.items(): v2=b.get((s,t),b.get((t,s))) assert_almost_equal(v1,v2) def test_K4_normalized(self): """Edge flow betweenness centrality: K4""" G=networkx.complete_graph(4) b=edge_current_flow(G,normalized=False) b_answer=dict.fromkeys(G.edges(),0.75) for (s,t),v1 in b_answer.items(): v2=b.get((s,t),b.get((t,s))) assert_almost_equal(v1,v2) def test_C4(self): """Edge flow betweenness centrality: C4""" G=networkx.cycle_graph(4) b=edge_current_flow(G,normalized=False) b_answer={(0, 1):1.25,(0, 3):1.25, (1, 2):1.25, (2, 3): 1.25} for (s,t),v1 in b_answer.items(): v2=b.get((s,t),b.get((t,s))) assert_almost_equal(v1,v2) def test_P4(self): """Edge betweenness centrality: P4""" G=networkx.path_graph(4) b=edge_current_flow(G,normalized=False) b_answer={(0, 1):1.5,(1, 2):2.0, (2, 3):1.5} for (s,t),v1 in b_answer.items(): v2=b.get((s,t),b.get((t,s))) assert_almost_equal(v1,v2)
apache-2.0
fedebell/Laboratorio3
Laboratorio2/GraficiBestFit/fitAnalistico.py
1
1562
import numpy import pylab from scipy.optimize import curve_fit import math import scipy.stats V, dV, I, dI = pylab.loadtxt("data00.txt", unpack="True") #Best fit analitico #Dy e Dx sono le colonne di errori x = V Dx = dV y = I Dy = dI #set error an statistical weight sigma = Dy w = 1/(sigma**2) #determine the coefficients c1 = (w*(x**2)).sum() c2 = (w*y).sum() c3 = (w*x).sum() c4 = (w*x*y).sum() c5 = (w).sum() Dprime = c5*c1-c3**2 a = (c1*c2-c3*c4)/Dprime b = (c5*c4-c3*c2)/Dprime Da = numpy.sqrt(c1/Dprime) Db = numpy.sqrt(c5/Dprime) #define the linear function #note how paramters are entered #note the syntax def ff(x, aa, bb): return aa+bb*x #calculate the chisquare for the best fit function chi2 = ((w*(y-ff(x, a, b))**2)).sum() #determine the ndof ndof = len(x)-2 #print results on the console print("I_0 = ", a, " DI_0 = ", Da, "R = ", 1/b, Db/(b**2)) print(chi2, ndof) #prepare a dummy xx array (with 100 linearly spaced points) xx = numpy.linspace(min(x), max(x), 100) pylab.title("Best fit analitico") pylab.xlabel("Delta V (V)") pylab.ylabel("I (mA)") #modificare gradi pylab.grid(color = "gray") pylab.xlim(0, 1.1*max(V)) pylab.ylim(0, 1.1*max(I)) pylab.grid(color = "gray") pylab.errorbar(V, I, dI, dV, "o", color="black") #plot the fitting curve pylab.plot(xx, ff(xx, a, b), color = 'red') chisq = (((I - ff(V, a, b))/dI)**2).sum() ndof = len(V) - 2 #Tolgo due parametri estratti dal fit p=1.0-scipy.stats.chi2.cdf(chisq, ndof) print("Chisquare/ndof 2 = %f/%d" % (chisq, ndof)) print("p = ", p) pylab.show()
gpl-3.0
jorsea/odoo-addons
purchase_line_defaults/purchase.py
8
1104
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## from openerp import models, api class purchase_order_line(models.Model): _inherit = "purchase.order.line" @api.model def create(self, vals): if vals.get('order_id') and vals.get('product_id') and any(f not in vals for f in ['name', 'price_unit', 'date_planned', 'product_qty', 'product_uom']): order = self.env['purchase.order'].browse( vals['order_id']) defaults = self.onchange_product_id( order and order.pricelist_id.id or False, vals.get('product_id', False), vals.get('product_qty', False), vals.get('uom_id', False), order and order.partner_id.id or False, )['value'] vals = dict(defaults, **vals) return super(purchase_order_line, self).create(vals)
agpl-3.0
claudep/translate
translate/tools/pydiff.py
1
12227
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2005, 2006 Zuza Software Foundation # # This file is part of translate. # # translate 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. # # translate 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/>. """diff tool like GNU diff, but lets you have special options that are useful in dealing with PO files""" import difflib import fnmatch import os import sys import time from argparse import ArgumentParser lineterm = "\n" def main(): """main program for pydiff""" parser = ArgumentParser() # GNU diff like options parser.add_argument("-i", "--ignore-case", default=False, action="store_true", help='Ignore case differences in file contents.') parser.add_argument("-U", "--unified", type=int, metavar="NUM", default=3, dest="unified_lines", help='Output NUM (default 3) lines of unified context') parser.add_argument("-r", "--recursive", default=False, action="store_true", help='Recursively compare any subdirectories found.') parser.add_argument("-N", "--new-file", default=False, action="store_true", help='Treat absent files as empty.') parser.add_argument("--unidirectional-new-file", default=False, action="store_true", help='Treat absent first files as empty.') parser.add_argument("-s", "--report-identical-files", default=False, action="store_true", help='Report when two files are the same.') parser.add_argument("-x", "--exclude", default=["CVS", "*.po~"], action="append", metavar="PAT", help='Exclude files that match PAT.') # our own options parser.add_argument("--fromcontains", type=str, default=None, metavar="TEXT", help='Only show changes where fromfile contains TEXT') parser.add_argument("--tocontains", type=str, default=None, metavar="TEXT", help='Only show changes where tofile contains TEXT') parser.add_argument("--contains", type=str, default=None, metavar="TEXT", help='Only show changes where fromfile or tofile contains TEXT') parser.add_argument("-I", "--ignore-case-contains", default=False, action="store_true", help='Ignore case differences when matching any of the changes') parser.add_argument("--accelerator", dest="accelchars", default="", metavar="ACCELERATORS", help="ignores the given accelerator characters when matching") parser.add_argument("fromfile", nargs=1) parser.add_argument("tofile", nargs=1) args = parser.parse_args() fromfile, tofile = args.fromfile[0], args.tofile[0] if fromfile == "-" and tofile == "-": parser.error("Only one of fromfile and tofile can be read from stdin") if os.path.isdir(fromfile): if os.path.isdir(tofile): differ = DirDiffer(fromfile, tofile, args) else: parser.error("File %s is a directory while file %s is a regular file" % (fromfile, tofile)) else: if os.path.isdir(tofile): parser.error("File %s is a regular file while file %s is a directory" % (fromfile, tofile)) else: differ = FileDiffer(fromfile, tofile, args) differ.writediff(sys.stdout) class DirDiffer: """generates diffs between directories""" def __init__(self, fromdir, todir, options): """Constructs a comparison between the two dirs using the given options""" self.fromdir = fromdir self.todir = todir self.options = options def isexcluded(self, difffile): """checks if the given filename has been excluded from the diff""" for exclude_pat in self.options.exclude: if fnmatch.fnmatch(difffile, exclude_pat): return True return False def writediff(self, outfile): """writes the actual diff to the given file""" fromfiles = os.listdir(self.fromdir) tofiles = os.listdir(self.todir) difffiles = dict.fromkeys(fromfiles + tofiles).keys() difffiles.sort() for difffile in difffiles: if self.isexcluded(difffile): continue from_ok = (difffile in fromfiles or self.options.new_file or self.options.unidirectional_new_file) to_ok = (difffile in tofiles or self.options.new_file) if from_ok and to_ok: fromfile = os.path.join(self.fromdir, difffile) tofile = os.path.join(self.todir, difffile) if os.path.isdir(fromfile): if os.path.isdir(tofile): if self.options.recursive: differ = DirDiffer(fromfile, tofile, self.options) differ.writediff(outfile) else: outfile.write("Common subdirectories: %s and %s\n" % (fromfile, tofile)) else: outfile.write("File %s is a directory while file %s is a regular file\n" % (fromfile, tofile)) else: if os.path.isdir(tofile): parser.error("File %s is a regular file while file %s is a directory\n" % (fromfile, tofile)) else: filediffer = FileDiffer(fromfile, tofile, self.options) filediffer.writediff(outfile) elif from_ok: outfile.write("Only in %s: %s\n" % (self.fromdir, difffile)) elif to_ok: outfile.write("Only in %s: %s\n" % (self.todir, difffile)) class FileDiffer: """generates diffs between files""" def __init__(self, fromfile, tofile, options): """Constructs a comparison between the two files using the given options""" self.fromfile = fromfile self.tofile = tofile self.options = options def writediff(self, outfile): """writes the actual diff to the given file""" validfiles = True if os.path.exists(self.fromfile): with open(self.fromfile, 'U') as fh: self.from_lines = fh.readlines() fromfiledate = os.stat(self.fromfile).st_mtime elif self.fromfile == "-": self.from_lines = sys.stdin.readlines() fromfiledate = time.time() elif self.options.new_file or self.options.unidirectional_new_file: self.from_lines = [] fromfiledate = 0 else: outfile.write("%s: No such file or directory\n" % self.fromfile) validfiles = False if os.path.exists(self.tofile): with open(self.tofile, 'U') as fh: self.to_lines = fh.readlines() tofiledate = os.stat(self.tofile).st_mtime elif self.tofile == "-": self.to_lines = sys.stdin.readlines() tofiledate = time.time() elif self.options.new_file: self.to_lines = [] tofiledate = 0 else: outfile.write("%s: No such file or directory\n" % self.tofile) validfiles = False if not validfiles: return fromfiledate = time.ctime(fromfiledate) tofiledate = time.ctime(tofiledate) compare_from_lines = self.from_lines compare_to_lines = self.to_lines if self.options.ignore_case: compare_from_lines = [line.lower() for line in compare_from_lines] compare_to_lines = [line.lower() for line in compare_to_lines] matcher = difflib.SequenceMatcher(None, compare_from_lines, compare_to_lines) groups = matcher.get_grouped_opcodes(self.options.unified_lines) started = False fromstring = '--- %s\t%s%s' % (self.fromfile, fromfiledate, lineterm) tostring = '+++ %s\t%s%s' % (self.tofile, tofiledate, lineterm) for group in groups: hunk = "".join([line for line in self.unified_diff(group)]) if self.options.fromcontains: if self.options.ignore_case_contains: hunk_from_lines = "".join([line.lower() for line in self.get_from_lines(group)]) else: hunk_from_lines = "".join(self.get_from_lines(group)) for accelerator in self.options.accelchars: hunk_from_lines = hunk_from_lines.replace(accelerator, "") if self.options.fromcontains not in hunk_from_lines: continue if self.options.tocontains: if self.options.ignore_case_contains: hunk_to_lines = "".join([line.lower() for line in self.get_to_lines(group)]) else: hunk_to_lines = "".join(self.get_to_lines(group)) for accelerator in self.options.accelchars: hunk_to_lines = hunk_to_lines.replace(accelerator, "") if self.options.tocontains not in hunk_to_lines: continue if self.options.contains: if self.options.ignore_case_contains: hunk_lines = "".join([line.lower() for line in self.get_from_lines(group) + self.get_to_lines(group)]) else: hunk_lines = "".join(self.get_from_lines(group) + self.get_to_lines(group)) for accelerator in self.options.accelchars: hunk_lines = hunk_lines.replace(accelerator, "") if self.options.contains not in hunk_lines: continue if not started: outfile.write(fromstring) outfile.write(tostring) started = True outfile.write(hunk) if not started and self.options.report_identical_files: outfile.write("Files %s and %s are identical\n" % (self.fromfile, self.tofile)) def get_from_lines(self, group): """returns the lines referred to by group, from the fromfile""" from_lines = [] for tag, i1, i2, j1, j2 in group: from_lines.extend(self.from_lines[i1:i2]) return from_lines def get_to_lines(self, group): """returns the lines referred to by group, from the tofile""" to_lines = [] for tag, i1, i2, j1, j2 in group: to_lines.extend(self.to_lines[j1:j2]) return to_lines def unified_diff(self, group): """takes the group of opcodes and generates a unified diff line by line""" i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4] yield "@@ -%d,%d +%d,%d @@%s" % (i1 + 1, i2 - i1, j1 + 1, j2 - j1, lineterm) for tag, i1, i2, j1, j2 in group: if tag == 'equal': for line in self.from_lines[i1:i2]: yield ' ' + line continue if tag == 'replace' or tag == 'delete': for line in self.from_lines[i1:i2]: yield '-' + line if tag == 'replace' or tag == 'insert': for line in self.to_lines[j1:j2]: yield '+' + line if __name__ == "__main__": main()
gpl-2.0
marcore/edx-platform
lms/djangoapps/lms_migration/management/commands/manage_course_groups.py
250
2091
#!/usr/bin/python # # File: manage_course_groups # # interactively list and edit membership in course staff and instructor groups import re from django.core.management.base import BaseCommand from django.contrib.auth.models import User, Group #----------------------------------------------------------------------------- # get all staff groups class Command(BaseCommand): help = "Manage course group membership, interactively." def handle(self, *args, **options): gset = Group.objects.all() print "Groups:" for cnt, g in zip(range(len(gset)), gset): print "%d. %s" % (cnt, g) gnum = int(raw_input('Choose group to manage (enter #): ')) group = gset[gnum] #----------------------------------------------------------------------------- # users in group uall = User.objects.all() if uall.count() < 50: print "----" print "List of All Users: %s" % [str(x.username) for x in uall] print "----" else: print "----" print "There are %d users, which is too many to list" % uall.count() print "----" while True: print "Users in the group:" uset = group.user_set.all() for cnt, u in zip(range(len(uset)), uset): print "%d. %s" % (cnt, u) action = raw_input('Choose user to delete (enter #) or enter usernames (comma delim) to add: ') m = re.match('^[0-9]+$', action) if m: unum = int(action) u = uset[unum] print "Deleting user %s" % u u.groups.remove(group) else: for uname in action.split(','): try: user = User.objects.get(username=action) except Exception as err: print "Error %s" % err continue print "adding %s to group %s" % (user, group) user.groups.add(group)
agpl-3.0
swiharta/radres
polls/pygooglechart.py
1
22228
""" PyGoogleChart - A complete Python wrapper for the Google Chart API http://pygooglechart.slowchop.com/ Copyright 2007 Gerald Kaszuba This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os import urllib import urllib2 import math import random import re # Helper variables and functions # ----------------------------------------------------------------------------- __version__ = '0.1.2' reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$') def _check_colour(colour): if not reo_colour.match(colour): raise InvalidParametersException('Colours need to be in ' \ 'RRGGBB or RRGGBBAA format. One of your colours has %s' % \ colour) # Exception Classes # ----------------------------------------------------------------------------- class PyGoogleChartException(Exception): pass class DataOutOfRangeException(PyGoogleChartException): pass class UnknownDataTypeException(PyGoogleChartException): pass class NoDataGivenException(PyGoogleChartException): pass class InvalidParametersException(PyGoogleChartException): pass class BadContentTypeException(PyGoogleChartException): pass # Data Classes # ----------------------------------------------------------------------------- class Data(object): def __init__(self, data): assert(type(self) != Data) # This is an abstract class self.data = data class SimpleData(Data): enc_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' def __repr__(self): encoded_data = [] for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append('_') elif value >= 0 and value <= SimpleData.max_value: sub_data.append(SimpleData.enc_map[value]) else: raise DataOutOfRangeException() encoded_data.append(''.join(sub_data)) return 'chd=s:' + ','.join(encoded_data) @staticmethod def max_value(): return 61 class TextData(Data): def __repr__(self): encoded_data = [] for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append(-1) elif value >= 0 and value <= TextData.max_value: sub_data.append(str(float(value))) else: raise DataOutOfRangeException() encoded_data.append(','.join(sub_data)) return 'chd=t:' + '|'.join(encoded_data) @staticmethod def max_value(): return 100 class ExtendedData(Data): enc_map = \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.' def __repr__(self): encoded_data = [] enc_size = len(ExtendedData.enc_map) for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append('__') elif value >= 0 and value <= ExtendedData.max_value: first, second = divmod(int(value), enc_size) sub_data.append('%s%s' % ( ExtendedData.enc_map[first], ExtendedData.enc_map[second])) else: raise DataOutOfRangeException( \ 'Item #%i "%s" is out of range' % (data.index(value), \ value)) encoded_data.append(''.join(sub_data)) return 'chd=e:' + ','.join(encoded_data) @staticmethod def max_value(): return 4095 # Axis Classes # ----------------------------------------------------------------------------- class Axis(object): BOTTOM = 'x' TOP = 't' LEFT = 'y' RIGHT = 'r' TYPES = (BOTTOM, TOP, LEFT, RIGHT) def __init__(self, axis_index, axis_type, **kw): assert(axis_type in Axis.TYPES) self.has_style = False self.axis_index = axis_index self.axis_type = axis_type self.positions = None def set_index(self, axis_index): self.axis_index = axis_index def set_positions(self, positions): self.positions = positions def set_style(self, colour, font_size=None, alignment=None): _check_colour(colour) self.colour = colour self.font_size = font_size self.alignment = alignment self.has_style = True def style_to_url(self): bits = [] bits.append(str(self.axis_index)) bits.append(self.colour) if self.font_size is not None: bits.append(str(self.font_size)) if self.alignment is not None: bits.append(str(self.alignment)) return ','.join(bits) def positions_to_url(self): bits = [] bits.append(str(self.axis_index)) bits += [str(a) for a in self.positions] return ','.join(bits) class LabelAxis(Axis): def __init__(self, axis_index, axis_type, values, **kwargs): Axis.__init__(self, axis_index, axis_type, **kwargs) self.values = [str(a) for a in values] def __repr__(self): return '%i:|%s' % (self.axis_index, '|'.join(self.values)) class RangeAxis(Axis): def __init__(self, axis_index, axis_type, low, high, **kwargs): Axis.__init__(self, axis_index, axis_type, **kwargs) self.low = low self.high = high def __repr__(self): return '%i,%s,%s' % (self.axis_index, self.low, self.high) # Chart Classes # ----------------------------------------------------------------------------- class Chart(object): """Abstract class for all chart types. width are height specify the dimensions of the image. title sets the title of the chart. legend requires a list that corresponds to datasets. """ BASE_URL = 'http://chart.apis.google.com/chart?' BACKGROUND = 'bg' CHART = 'c' SOLID = 's' LINEAR_GRADIENT = 'lg' LINEAR_STRIPES = 'ls' def __init__(self, width, height, title=None, legend=None, colours=None): assert(type(self) != Chart) # This is an abstract class assert(isinstance(width, int)) assert(isinstance(height, int)) self.width = width self.height = height self.data = [] self.set_title(title) self.set_legend(legend) self.set_colours(colours) self.fill_types = { Chart.BACKGROUND: None, Chart.CHART: None, } self.fill_area = { Chart.BACKGROUND: None, Chart.CHART: None, } # self.axis = { # Axis.TOP: None, # Axis.BOTTOM: None, # Axis.LEFT: None, # Axis.RIGHT: None, # } self.axis = [] self.markers = [] # URL generation # ------------------------------------------------------------------------- def get_url(self): url_bits = self.get_url_bits() return self.BASE_URL + '&'.join(url_bits) def get_url_bits(self): url_bits = [] # required arguments url_bits.append(self.type_to_url()) url_bits.append('chs=%ix%i' % (self.width, self.height)) url_bits.append(self.data_to_url()) # optional arguments if self.title: url_bits.append('chtt=%s' % self.title) if self.legend: url_bits.append('chdl=%s' % '|'.join(self.legend)) if self.colours: url_bits.append('chco=%s' % ','.join(self.colours)) ret = self.fill_to_url() if ret: url_bits.append(ret) ret = self.axis_to_url() if ret: url_bits.append(ret) if self.markers: url_bits.append(self.markers_to_url()) return url_bits # Downloading # ------------------------------------------------------------------------- def download(self, file_name): opener = urllib2.urlopen(self.get_url()) if opener.headers['content-type'] != 'image/png': raise BadContentTypeException('Server responded with a ' \ 'content-type of %s' % opener.headers['content-type']) open(file_name, 'wb').write(urllib.urlopen(self.get_url()).read()) # Simple settings # ------------------------------------------------------------------------- def set_title(self, title): if title: self.title = urllib.quote(title) else: self.title = None def set_legend(self, legend): # legend needs to be a list, tuple or None assert(isinstance(legend, list) or isinstance(legend, tuple) or legend is None) if legend: self.legend = [urllib.quote(a) for a in legend] else: self.legend = None # Chart colours # ------------------------------------------------------------------------- def set_colours(self, colours): # colours needs to be a list, tuple or None assert(isinstance(colours, list) or isinstance(colours, tuple) or colours is None) # make sure the colours are in the right format if colours: for col in colours: _check_colour(col) self.colours = colours # Background/Chart colours # ------------------------------------------------------------------------- def fill_solid(self, area, colour): assert(area in (Chart.BACKGROUND, Chart.CHART)) _check_colour(colour) self.fill_area[area] = colour self.fill_types[area] = Chart.SOLID def _check_fill_linear(self, angle, *args): assert(isinstance(args, list) or isinstance(args, tuple)) assert(angle >= 0 and angle <= 90) assert(len(args) % 2 == 0) args = list(args) # args is probably a tuple and we need to mutate for a in xrange(len(args) / 2): col = args[a * 2] offset = args[a * 2 + 1] _check_colour(col) assert(offset >= 0 and offset <= 1) args[a * 2 + 1] = str(args[a * 2 + 1]) return args def fill_linear_gradient(self, area, angle, *args): assert(area in (Chart.BACKGROUND, Chart.CHART)) args = self._check_fill_linear(angle, *args) self.fill_types[area] = Chart.LINEAR_GRADIENT self.fill_area[area] = ','.join([str(angle)] + args) def fill_linear_stripes(self, area, angle, *args): assert(area in (Chart.BACKGROUND, Chart.CHART)) args = self._check_fill_linear(angle, *args) self.fill_types[area] = Chart.LINEAR_STRIPES self.fill_area[area] = ','.join([str(angle)] + args) def fill_to_url(self): areas = [] for area in (Chart.BACKGROUND, Chart.CHART): if self.fill_types[area]: areas.append('%s,%s,%s' % (area, self.fill_types[area], \ self.fill_area[area])) if areas: return 'chf=' + '|'.join(areas) # Data # ------------------------------------------------------------------------- def data_class_detection(self, data): """ Detects and returns the data type required based on the range of the data given. The data given must be lists of numbers within a list. """ assert(isinstance(data, list) or isinstance(data, tuple)) max_value = None for a in data: assert(isinstance(a, list) or isinstance(a, tuple)) if max_value is None or max(a) > max_value: max_value = max(a) for data_class in (SimpleData, TextData, ExtendedData): if max_value <= data_class.max_value(): return data_class raise DataOutOfRangeException() def add_data(self, data): self.data.append(data) return len(self.data) - 1 # return the "index" of the data set def data_to_url(self, data_class=None): if not data_class: data_class = self.data_class_detection(self.data) if not issubclass(data_class, Data): raise UnknownDataTypeException() return repr(data_class(self.data)) # Axis Labels # ------------------------------------------------------------------------- def set_axis_labels(self, axis_type, values): assert(axis_type in Axis.TYPES) values = [ urllib.quote(a) for a in values ] axis_index = len(self.axis) axis = LabelAxis(axis_index, axis_type, values) self.axis.append(axis) return axis_index def set_axis_range(self, axis_type, low, high): assert(axis_type in Axis.TYPES) axis_index = len(self.axis) axis = RangeAxis(axis_index, axis_type, low, high) self.axis.append(axis) return axis_index def set_axis_positions(self, axis_index, positions): try: self.axis[axis_index].set_positions(positions) except IndexError: raise InvalidParametersException('Axis index %i has not been ' \ 'created' % axis) def set_axis_style(self, axis_index, colour, font_size=None, \ alignment=None): try: self.axis[axis_index].set_style(colour, font_size, alignment) except IndexError: raise InvalidParametersException('Axis index %i has not been ' \ 'created' % axis) def axis_to_url(self): available_axis = [] label_axis = [] range_axis = [] positions = [] styles = [] index = -1 for axis in self.axis: available_axis.append(axis.axis_type) if isinstance(axis, RangeAxis): range_axis.append(repr(axis)) if isinstance(axis, LabelAxis): label_axis.append(repr(axis)) if axis.positions: positions.append(axis.positions_to_url()) if axis.has_style: styles.append(axis.style_to_url()) if not available_axis: return url_bits = [] url_bits.append('chxt=%s' % ','.join(available_axis)) if label_axis: url_bits.append('chxl=%s' % '|'.join(label_axis)) if range_axis: url_bits.append('chxr=%s' % '|'.join(range_axis)) if positions: url_bits.append('chxp=%s' % '|'.join(positions)) if styles: url_bits.append('chxs=%s' % '|'.join(styles)) return '&'.join(url_bits) # Markers, Ranges and Fill area (chm) # ------------------------------------------------------------------------- def markers_to_url(self): return 'chm=%s' % '|'.join([','.join(a) for a in self.markers]) def add_marker(self, index, point, marker_type, colour, size): self.markers.append((marker_type, colour, str(index), str(point), \ str(size))) def add_horizontal_range(self, colour, start, stop): self.markers.append(('r', colour, '1', str(start), str(stop))) def add_vertical_range(self, colour, start, stop): self.markers.append(('R', colour, '1', str(start), str(stop))) def add_fill_range(self, colour, index_start, index_end): self.markers.append(('b', colour, str(index_start), str(index_end), \ '1')) def add_fill_simple(self, colour): self.markers.append(('B', colour, '1', '1', '1')) class ScatterChart(Chart): def __init__(self, *args, **kwargs): Chart.__init__(self, *args, **kwargs) def type_to_url(self): return 'cht=s' class LineChart(Chart): def __init__(self, *args, **kwargs): assert(type(self) != LineChart) # This is an abstract class Chart.__init__(self, *args, **kwargs) self.line_styles = {} self.grid = None def set_line_style(self, index, thickness=1, line_segment=None, \ blank_segment=None): value = [] value.append(str(thickness)) if line_segment: value.append(str(line_segment)) value.append(str(blank_segment)) self.line_styles[index] = value def set_grid(self, x_step, y_step, line_segment=1, \ blank_segment=0): self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment, \ blank_segment) def get_url_bits(self): url_bits = Chart.get_url_bits(self) if self.line_styles: style = [] # for index, values in self.line_style.items(): for index in xrange(max(self.line_styles) + 1): if index in self.line_styles: values = self.line_styles[index] else: values = ('1', ) style.append(','.join(values)) url_bits.append('chls=%s' % '|'.join(style)) if self.grid: url_bits.append('chg=%s' % self.grid) return url_bits class SimpleLineChart(LineChart): def type_to_url(self): return 'cht=lc' class XYLineChart(LineChart): def type_to_url(self): return 'cht=lxy' class BarChart(Chart): def __init__(self, *args, **kwargs): assert(type(self) != BarChart) # This is an abstract class Chart.__init__(self, *args, **kwargs) self.bar_width = None def set_bar_width(self, bar_width): self.bar_width = bar_width def get_url_bits(self): url_bits = Chart.get_url_bits(self) url_bits.append('chbh=%i' % self.bar_width) return url_bits class StackedHorizontalBarChart(BarChart): def type_to_url(self): return 'cht=bhs' class StackedVerticalBarChart(BarChart): def type_to_url(self): return 'cht=bvs' class GroupedBarChart(BarChart): def __init__(self, *args, **kwargs): assert(type(self) != GroupedBarChart) # This is an abstract class BarChart.__init__(self, *args, **kwargs) self.bar_spacing = None def set_bar_spacing(self, spacing): self.bar_spacing = spacing def get_url_bits(self): # Skip 'BarChart.get_url_bits' and call Chart directly so the parent # doesn't add "chbh" before we do. url_bits = Chart.get_url_bits(self) if self.bar_spacing is not None: if self.bar_width is None: raise InvalidParametersException('Bar width is required to ' \ 'be set when setting spacing') url_bits.append('chbh=%i,%i' % (self.bar_width, self.bar_spacing)) else: url_bits.append('chbh=%i' % self.bar_width) return url_bits class GroupedHorizontalBarChart(GroupedBarChart): def type_to_url(self): return 'cht=bhg' class GroupedVerticalBarChart(GroupedBarChart): def type_to_url(self): return 'cht=bvg' class PieChart(Chart): def __init__(self, *args, **kwargs): assert(type(self) != PieChart) # This is an abstract class Chart.__init__(self, *args, **kwargs) self.pie_labels = [] def set_pie_labels(self, labels): self.pie_labels = [urllib.quote(a) for a in labels] def get_url_bits(self): url_bits = Chart.get_url_bits(self) if self.pie_labels: url_bits.append('chl=%s' % '|'.join(self.pie_labels)) return url_bits class PieChart2D(PieChart): def type_to_url(self): return 'cht=p' class PieChart3D(PieChart): def type_to_url(self): return 'cht=p3' class VennChart(Chart): def type_to_url(self): return 'cht=v' def test(): chart = GroupedVerticalBarChart(320, 200) chart = PieChart2D(320, 200) chart = ScatterChart(320, 200) chart = SimpleLineChart(320, 200) sine_data = [math.sin(float(a) / 10) * 2000 + 2000 for a in xrange(100)] random_data = [a * random.random() * 30 for a in xrange(40)] random_data2 = [random.random() * 4000 for a in xrange(10)] # chart.set_bar_width(50) # chart.set_bar_spacing(0) chart.add_data(sine_data) chart.add_data(random_data) chart.add_data(random_data2) # chart.set_line_style(1, thickness=2) # chart.set_line_style(2, line_segment=10, blank_segment=5) # chart.set_title('heloooo') # chart.set_legend(('sine wave', 'random * x')) # chart.set_colours(('ee2000', 'DDDDAA', 'fF03f2')) # chart.fill_solid(Chart.BACKGROUND, '123456') # chart.fill_linear_gradient(Chart.CHART, 20, '004070', 1, '300040', 0, # 'aabbcc00', 0.5) # chart.fill_linear_stripes(Chart.CHART, 20, '204070', .2, '300040', .2, # 'aabbcc00', 0.2) axis_left_index = chart.set_axis_range(Axis.LEFT, 0, 10) axis_left_index = chart.set_axis_range(Axis.LEFT, 0, 10) axis_left_index = chart.set_axis_range(Axis.LEFT, 0, 10) axis_right_index = chart.set_axis_range(Axis.RIGHT, 5, 30) axis_bottom_index = chart.set_axis_labels(Axis.BOTTOM, [1, 25, 95]) chart.set_axis_positions(axis_bottom_index, [1, 25, 95]) chart.set_axis_style(axis_bottom_index, '003050', 15) # chart.set_pie_labels(('apples', 'oranges', 'bananas')) # chart.set_grid(10, 10) # for a in xrange(0, 100, 10): # chart.add_marker(1, a, 'a', 'AACA20', 10) chart.add_horizontal_range('00A020', .2, .5) chart.add_vertical_range('00c030', .2, .4) chart.add_fill_simple('303030A0') chart.download('test.png') url = chart.get_url() print url if 0: data = urllib.urlopen(chart.get_url()).read() open('meh.png', 'wb').write(data) os.system('start meh.png') if __name__ == '__main__': test()
mit
wasidennis/ObjectFlow
caffe-cedn-dev/src/caffe/test/test_data/generate_sample_data.py
4
1152
""" Generate data used in the HDF5DataLayer test. """ import os import numpy as np import h5py num_cols = 8 num_rows = 10 height = 6 width = 5 total_size = num_cols * num_rows * height * width data = np.arange(total_size) data = data.reshape(num_rows, num_cols, height, width) data = data.astype('float32') # We had a bug where data was copied into label, but the tests weren't # catching it, so let's make label 1-indexed. label = 1 + np.arange(num_rows)[:, np.newaxis] label = label.astype('float32') print data print label with h5py.File(os.path.dirname(__file__) + '/sample_data.h5', 'w') as f: f['data'] = data f['label'] = label with h5py.File(os.path.dirname(__file__) + '/sample_data_2_gzip.h5', 'w') as f: f.create_dataset( 'data', data=data + total_size, compression='gzip', compression_opts=1 ) f.create_dataset( 'label', data=label, compression='gzip', compression_opts=1 ) with open(os.path.dirname(__file__) + '/sample_data_list.txt', 'w') as f: f.write(os.path.dirname(__file__) + '/sample_data.h5\n') f.write(os.path.dirname(__file__) + '/sample_data_2_gzip.h5\n')
mit
mrnamingo/vix4-34-enigma2-bcm
lib/python/Plugins/Plugin.py
5
4041
from Components.config import ConfigSubsection, config import os config.plugins = ConfigSubsection() class PluginDescriptor: """An object to describe a plugin.""" # where to list the plugin. Note that there are different call arguments, # so you might not be able to combine them. # supported arguments are: # session # servicereference # reason # you have to ignore unknown kwargs! # argument: session WHERE_EXTENSIONSMENU = 1 WHERE_MAINMENU = 2 WHERE_PLUGINMENU = 3 # argument: session, serviceref (currently selected) WHERE_MOVIELIST = 4 # argument: menuid. Fnc must return list with menuitems (4-tuple of name, fnc to call, entryid or None, weight or None) WHERE_MENU = 5 # reason (0: start, 1: end) WHERE_AUTOSTART = 6 # start as wizard. In that case, fnc must be tuple (priority,class) with class being a screen class! WHERE_WIZARD = 7 # like autostart, but for a session. currently, only session starts are # delivered, and only on pre-loaded plugins WHERE_SESSIONSTART = 8 # start as teletext plugin. arguments: session, serviceref WHERE_TELETEXT = 9 # file-scanner, fnc must return a list of Scanners WHERE_FILESCAN = 10 # fnc must take an interface name as parameter and return None if the plugin supports an extended setup # or return a function which is called with session and the interface name for extended setup of this interface WHERE_NETWORKSETUP = 11 # show up this plugin (or a choicebox with all of them) for long INFO keypress # or return a function which is called with session and the interface name for extended setup of this interface WHERE_EVENTINFO = 12 # reason (True: Networkconfig read finished, False: Networkconfig reload initiated ) WHERE_NETWORKCONFIG_READ = 13 WHERE_AUDIOMENU = 14 # fnc 'SoftwareSupported' or 'AdvancedSoftwareSupported' must take a parameter and return None # if the plugin should not be displayed inside Softwaremanger or return a function which is called with session # and 'None' as parameter to call the plugin from the Softwaremanager menus. "menuEntryName" and "menuEntryDescription" # should be provided to name and describe the new menu entry. WHERE_SOFTWAREMANAGER = 15 # start as channellist context menu plugin. session, serviceref (currently selected) WHERE_CHANNEL_CONTEXT_MENU = 16 # fnc must take an interface name as parameter and return None if the plugin supports an extended setup # or return a function which is called with session and the interface name for extended setup of this interface WHERE_NETWORKMOUNTS = 17 WHERE_VIXMENU = 18 WHERE_SATCONFIGCHANGED = 19 WHERE_SERVICESCAN = 20 WHERE_EXTENSIONSINGLE = 21 def __init__(self, name="Plugin", where=None, description="", icon=None, fnc=None, wakeupfnc=None, needsRestart=None, internal=False, weight=0): if not where: where = [] self.name = name self.internal = internal self.needsRestart = needsRestart self.path = None if isinstance(where, list): self.where = where else: self.where = [ where ] self.description = description if icon is None or isinstance(icon, str): self.iconstr = icon self._icon = None else: self.iconstr = None self._icon = icon self.weight = weight self.wakeupfnc = wakeupfnc self.__call__ = fnc def updateIcon(self, path): self.path = path def getWakeupTime(self): return self.wakeupfnc and self.wakeupfnc() or -1 @property def icon(self): if self.iconstr: from Tools.LoadPixmap import LoadPixmap return LoadPixmap(os.path.join(self.path, self.iconstr)) else: return self._icon def __eq__(self, other): return self.__call__ == other.__call__ def __ne__(self, other): return self.__call__ != other.__call__ def __lt__(self, other): if self.weight < other.weight: return True elif self.weight == other.weight: return self.name < other.name else: return False def __gt__(self, other): return other<self def __ge__(self, other): return not self<other def __le__(self, other): return not other<self
gpl-2.0
turtleloveshoes/kitsune
kitsune/search/tests/test_api.py
11
10186
import json import time from nose.tools import eq_ from rest_framework.test import APIClient from django.conf import settings from kitsune.search.tests.test_es import ElasticTestCase from kitsune.sumo.urlresolvers import reverse from kitsune.questions.tests import question, answer from kitsune.products.tests import product from kitsune.wiki.tests import document, revision class SuggestViewTests(ElasticTestCase): client_class = APIClient def _make_question(self, solved=True, **kwargs): defaults = { 'title': 'Login to website comments disabled ' + str(time.time()), 'content': """ readersupportednews.org, sends me emails with a list of articles to read. The links to the articles work as normal, except that I cannot login from the linked article - as required - to send my comments. I see a javascript activity statement at the bottom left corner of my screen while the left button is depressed on the Login button. it is gone when I release the left button, but no results. I have the latest (7) version of java enabled, on an XP box. Why this inability to login to this website commentary? """, 'save': True, } defaults.update(kwargs) q = question(**defaults) if solved: a = answer(question=q, save=True) q.solution = a # Trigger a reindex for the question. q.save() return q def _make_document(self, **kwargs): defaults = { 'title': 'How to make a pie from scratch with email ' + str(time.time()), 'category': 10, 'save': True } defaults.update(kwargs) d = document(**defaults) revision(document=d, is_approved=True, save=True) d.save() return d def test_invalid_product(self): res = self.client.get(reverse('search.suggest'), { 'product': 'nonexistant', 'q': 'search', }) eq_(res.status_code, 400) eq_(res.data['detail'], {'product': [u'Could not find product with slug "nonexistant".']}) def test_invalid_locale(self): res = self.client.get(reverse('search.suggest'), { 'locale': 'bad-medicine', 'q': 'search', }) eq_(res.status_code, 400) eq_(res.data['detail'], {'locale': [u'Could not find locale "bad-medicine".']}) def test_invalid_fallback_locale_none_case(self): # Test the locale -> locale case. non_none_locale_fallback_pairs = [ (key, val) for key, val in sorted(settings.NON_SUPPORTED_LOCALES.items()) if val is not None ] locale, fallback = non_none_locale_fallback_pairs[0] res = self.client.get(reverse('search.suggest'), { 'locale': locale, 'q': 'search', }) eq_(res.status_code, 400) eq_( res.data['detail'], {'locale': [u'"{0}" is not supported, but has fallback locale "{1}".'.format( locale, fallback)]} ) def test_invalid_fallback_locale_non_none_case(self): # Test the locale -> None case which falls back to WIKI_DEFAULT_LANGUAGE. has_none_locale_fallback_pairs = [ (key, val) for key, val in sorted(settings.NON_SUPPORTED_LOCALES.items()) if val is None ] locale, fallback = has_none_locale_fallback_pairs[0] res = self.client.get(reverse('search.suggest'), { 'locale': locale, 'q': 'search', }) eq_(res.status_code, 400) eq_( res.data['detail'], {'locale': [u'"{0}" is not supported, but has fallback locale "{1}".'.format( locale, settings.WIKI_DEFAULT_LANGUAGE)]} ) def test_invalid_numbers(self): res = self.client.get(reverse('search.suggest'), { 'max_questions': 'a', 'max_documents': 'b', 'q': 'search', }) eq_(res.status_code, 400) eq_(res.data['detail'], { 'max_questions': [u'Enter a whole number.'], 'max_documents': [u'Enter a whole number.'], }) def test_q_required(self): res = self.client.get(reverse('search.suggest')) eq_(res.status_code, 400) eq_(res.data['detail'], {'q': [u'This field is required.']}) def test_it_works(self): q1 = self._make_question() d1 = self._make_document() self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) eq_([q['id'] for q in req.data['questions']], [q1.id]) eq_([d['title'] for d in req.data['documents']], [d1.title]) def test_filters_in_postdata(self): q1 = self._make_question() d1 = self._make_document() self.refresh() data = json.dumps({'q': 'emails'}) # Note: Have to use .generic() because .get() will convert the # data into querystring params and then it's clownshoes all # the way down. req = self.client.generic( 'GET', reverse('search.suggest'), data=data, content_type='application/json') eq_(req.status_code, 200) eq_([q['id'] for q in req.data['questions']], [q1.id]) eq_([d['title'] for d in req.data['documents']], [d1.title]) def test_both_querystring_and_body_raises_error(self): self._make_question() self._make_document() self.refresh() data = json.dumps({'q': 'emails'}) # Note: Have to use .generic() because .get() will convert the # data into querystring params and then it's clownshoes all # the way down. req = self.client.generic( 'GET', reverse('search.suggest') + '?max_documents=3', data=data, content_type='application/json') eq_(req.status_code, 400) eq_(req.data, {u'detail': 'Put all parameters either in the querystring or the HTTP request body.'}) def test_questions_max_results_0(self): self._make_question() self.refresh() # Make sure something matches the query first. req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) eq_(len(req.data['questions']), 1) # If we specify "don't give me any" make sure we don't get any. req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_questions': '0'}) eq_(len(req.data['questions']), 0) def test_questions_max_results_non_0(self): self._make_question() self._make_question() self._make_question() self._make_question() self._make_question() self.refresh() # Make sure something matches the query first. req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) eq_(len(req.data['questions']), 5) # Make sure we get only 3. req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_questions': '3'}) eq_(len(req.data['questions']), 3) def test_documents_max_results_0(self): self._make_document() self.refresh() # Make sure something matches the query first. req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) eq_(len(req.data['documents']), 1) # If we specify "don't give me any" make sure we don't get any. req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_documents': '0'}) eq_(len(req.data['documents']), 0) def test_documents_max_results_non_0(self): self._make_document() self._make_document() self._make_document() self._make_document() self._make_document() self.refresh() # Make sure something matches the query first. req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) eq_(len(req.data['documents']), 5) # Make sure we get only 3. req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_documents': '3'}) eq_(len(req.data['documents']), 3) def test_product_filter_works(self): p1 = product(save=True) p2 = product(save=True) q1 = self._make_question(product=p1) self._make_question(product=p2) self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'product': p1.slug}) eq_([q['id'] for q in req.data['questions']], [q1.id]) def test_locale_filter_works_for_questions(self): q1 = self._make_question(locale='fr') self._make_question(locale='en-US') self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'locale': 'fr'}) eq_([q['id'] for q in req.data['questions']], [q1.id]) def test_locale_filter_works_for_documents(self): d1 = self._make_document(slug='right-doc', locale='fr') self._make_document(slug='wrong-doc', locale='en-US') self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'locale': 'fr'}) eq_([d['slug'] for d in req.data['documents']], [d1.slug]) def test_serializer_fields(self): """Test that fields from the serializer are included.""" self._make_question() self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) # Check that a field that is only available from the DB is in the response. assert 'metadata' in req.data['questions'][0] def test_only_solved(self): """Test that only solved questions are suggested.""" q1 = self._make_question(solved=True) q2 = self._make_question(solved=False) self.refresh() req = self.client.get(reverse('search.suggest'), {'q': 'emails'}) ids = [q['id'] for q in req.data['questions']] assert q1.id in ids assert q2.id not in ids eq_(len(ids), 1)
bsd-3-clause
marvin-jens/fast_ska
setup.py
1
2027
from setuptools import setup from setuptools.extension import Extension try: from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: use_cython = False else: use_cython = True cmdclass = { } ext_modules = [ ] if use_cython: ext_modules += [ #Extension("ska_kmers", [ "ska_kmers.pyx" ], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'],), Extension("ska_kmers", [ "ska_kmers.pyx" ], ), ] cmdclass.update({ 'build_ext': build_ext }) else: ext_modules += [ Extension("ska_kmers", [ "ska_kmers.c" ]), ] setup( name = "fast_ska", version = "0.9.3", description='A fast Cython implementation of the "Streaming K-mer Assignment" algorithm initially described in Lambert et al. 2014 (PMID: 24837674)', url = 'https://github.com/marvin-jens/fast_ska', author = 'Marvin Jens', author_email = 'mjens@mit.edu', license = 'MIT', classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], keywords = 'rna rbns k-mer kmer statistics biology bioinformatics', install_requires=['cython','numpy'], scripts=['ska'], cmdclass = cmdclass, ext_modules=ext_modules, #ext_modules = cythonize("ska_kmers.pyx") )
mit
ImageEngine/gaffer
startup/gui/layouts.py
8
8208
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design 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 John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import GafferUI layouts = GafferUI.Layouts.acquire( application ) # register the editors we want to be available to the user layouts.registerEditor( "Viewer" ) layouts.registerEditor( "NodeEditor" ) layouts.registerEditor( "GraphEditor" ) layouts.registerEditor( "HierarchyView" ) layouts.registerEditor( "SceneInspector" ) layouts.registerEditor( "PythonEditor" ) layouts.registerEditor( "Timeline" ) layouts.registerEditor( "UIEditor" ) layouts.registerEditor( "AnimationEditor" ) layouts.registerEditor( "PrimitiveInspector") layouts.registerEditor( "UVInspector") # Register some predefined layouts # # > Note : The easiest way to edit these layouts is to : # > # > - Edit the layout in Gaffer itself # > - Save the layout so that it is serialised to `${HOME}/gaffer/startup/gui/layouts.py` # > - Copy the layout back into this file # # > Caution : You _must_ omit the `persistent = True` argument when copying layouts into # > this file, to prevent the standard layouts from being serialised into the user's own # > preferences. layouts.add( 'Standard', "GafferUI.CompoundEditor( scriptNode, _state={ 'children' : ( GafferUI.SplitContainer.Orientation.Vertical, 0.953488, ( ( GafferUI.SplitContainer.Orientation.Horizontal, 0.699857, ( ( GafferUI.SplitContainer.Orientation.Vertical, 0.479580, ( {'tabs': (GafferUI.Viewer( scriptNode ), GafferSceneUI.UVInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, False]}, {'tabs': (GafferUI.GraphEditor( scriptNode ), GafferUI.AnimationEditor( scriptNode ), GafferSceneUI.PrimitiveInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [None, False, False]} ) ), ( GafferUI.SplitContainer.Orientation.Vertical, 0.539090, ( {'tabs': (GafferUI.NodeEditor( scriptNode ), GafferSceneUI.SceneInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, False]}, {'tabs': (GafferSceneUI.HierarchyView( scriptNode ), GafferUI.PythonEditor( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, None]} ) ) ) ), {'tabs': (GafferUI.Timeline( scriptNode ),), 'tabsVisible': False, 'currentTab': 0, 'pinned': [None]} ) ), 'detachedPanels' : (), 'windowState' : { 'fullScreen' : False, 'screen' : -1, 'bound' : imath.Box2f( imath.V2f( 0.0473958328, 0.108751059 ), imath.V2f( 0.781770825, 0.906542063 ) ), 'maximized' : True }, 'editorState' : { 'c-0-1-1-0-0': {'driver': 'c-0-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-1-0-0-1': {'driver': 'c-0-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-0-1-0-2': {'driver': 'c-0-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-0-0-0-1': {'driver': 'c-0-0-0-0-0', 'driverMode': 'NodeSet'}} } )" ) layouts.add( 'Standard (multi-monitor)', "GafferUI.CompoundEditor( scriptNode, _state={ 'children' : ( GafferUI.SplitContainer.Orientation.Vertical, 0.953488, ( ( GafferUI.SplitContainer.Orientation.Horizontal, 0.699857, ( {'tabs': (GafferUI.GraphEditor( scriptNode ), GafferUI.AnimationEditor( scriptNode ), GafferSceneUI.PrimitiveInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [None, False, False]}, ( GafferUI.SplitContainer.Orientation.Vertical, 0.539090, ( {'tabs': (GafferUI.NodeEditor( scriptNode ), GafferSceneUI.SceneInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, False]}, {'tabs': (GafferSceneUI.HierarchyView( scriptNode ), GafferUI.PythonEditor( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, None]} ) ) ) ), {'tabs': (GafferUI.Timeline( scriptNode ),), 'tabsVisible': False, 'currentTab': 0, 'pinned': [None]} ) ), 'detachedPanels' : ( { 'children' : {'tabs': (GafferUI.Viewer( scriptNode ), GafferSceneUI.UVInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, False]}, 'windowState' : { 'fullScreen' : False, 'screen' : 1, 'bound' : imath.Box2f( imath.V2f( 0.0472222231, 0.108888887 ), imath.V2f( 0.781944454, 0.906666696 ) ), 'maximized' : True } }, ), 'windowState' : { 'fullScreen' : False, 'screen' : -1, 'bound' : imath.Box2f( imath.V2f( 0.0473958328, 0.108751059 ), imath.V2f( 0.781770825, 0.906542063 ) ), 'maximized' : True }, 'editorState' : {'c-0-0-0-2': {'driver': 'p-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-1-0-0-1': {'driver': 'p-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-1-1-0-0': {'driver': 'p-0-0-0', 'driverMode': 'NodeSet'}, 'p-0-0-1': {'driver': 'p-0-0-0', 'driverMode': 'NodeSet'}} } )" ) layouts.add( "Empty", "GafferUI.CompoundEditor( scriptNode, windowState = {'fullScreen': False, 'screen': -1, 'bound': imath.Box2f(imath.V2f(0.0479166657, 0.108269393), imath.V2f(0.782812476, 0.906223357)), 'maximized': True} )" ) layouts.add( 'Scene', "GafferUI.CompoundEditor( scriptNode, _state={ 'children' : ( GafferUI.SplitContainer.Orientation.Horizontal, 0.772206, ( ( GafferUI.SplitContainer.Orientation.Horizontal, 0.256052, ( {'tabs': (GafferSceneUI.HierarchyView( scriptNode ),), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False]}, ( GafferUI.SplitContainer.Orientation.Vertical, 0.500554, ( ( GafferUI.SplitContainer.Orientation.Vertical, 0.906250, ( {'tabs': (GafferUI.Viewer( scriptNode ), GafferSceneUI.UVInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False, False]}, {'tabs': (GafferUI.Timeline( scriptNode ),), 'tabsVisible': False, 'currentTab': 0, 'pinned': [None]} ) ), {'tabs': (GafferUI.GraphEditor( scriptNode ), GafferUI.AnimationEditor( scriptNode ), GafferSceneUI.PrimitiveInspector( scriptNode )), 'tabsVisible': True, 'currentTab': 0, 'pinned': [None, False, False]} ) ) ) ), ( GafferUI.SplitContainer.Orientation.Vertical, 0.500554, ( {'tabs': (GafferUI.NodeEditor( scriptNode ),), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False]}, {'tabs': (GafferSceneUI.SceneInspector( scriptNode ),), 'tabsVisible': True, 'currentTab': 0, 'pinned': [False]} ) ) ) ), 'detachedPanels' : (), 'windowState' : { 'fullScreen' : False, 'screen' : -1, 'bound' : imath.Box2f( imath.V2f( 0.046875, 0.109600678 ), imath.V2f( 0.78125, 0.907391667 ) ), 'maximized' : True }, 'editorState' : {'c-0-1-1-0-2': {'driver': 'c-0-1-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-0-0-0': {'driver': 'c-0-1-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-1-1-0-0': {'driver': 'c-0-1-0-0-0-0', 'driverMode': 'NodeSet'}, 'c-0-1-0-0-0-1': {'driver': 'c-0-1-0-0-0-0', 'driverMode': 'NodeSet'}} } )" ) layouts.setDefault( "Standard" )
bsd-3-clause
machtfit/django-oscar-accounts
accounts/views.py
6
1083
from django.views import generic from accounts.forms import AccountForm from accounts import security class AccountBalanceView(generic.FormView): form_class = AccountForm template_name = 'accounts/balance_check.html' def get_context_data(self, **kwargs): ctx = super(AccountBalanceView, self).get_context_data(**kwargs) ctx['is_blocked'] = security.is_blocked(self.request) return ctx def post(self, request, *args, **kwargs): # Check for blocked users before trying to validate form if security.is_blocked(request): return self.get(request, *args, **kwargs) return super(AccountBalanceView, self).post(request, *args, **kwargs) def form_invalid(self, form): security.record_failed_request(self.request) return super(AccountBalanceView, self).form_invalid(form) def form_valid(self, form): security.record_successful_request(self.request) ctx = self.get_context_data(form=form) ctx['account'] = form.account return self.render_to_response(ctx)
bsd-3-clause
the-virtual-brain/tvb-hpc
examples/btest.py
1
1617
import numpy as np import loopy as lp target = lp.CudaTarget() kernel = lp.make_kernel( "{ [i_node,j_node]: 0<=i_node,j_node<n_node}", """ <float32> coupling_value = params(1) <float32> speed_value = params(0) <float32> dt=0.1 <float32> M_PI_F = 2.0 <float32> rec_n = 1.0f / n_node <float32> rec_speed_dt = 1.0f / speed_value / dt <float32> omega = 10.0 * 2.0 * M_PI_F / 1e3 <float32> sig = sqrt(dt) * sqrt(2.0 * 1e-5) <float32> rand = 1.0 for i_node tavg[i_node]=0.0f {id = clear} end for i_node <float32> theta_i = state[i_node] {id = coupling1, dep=*} <float32> sum = 0.0 {id = coupling2} for j_node <float32> wij = weights[j_node] {id = coupling3, dep=coupling1:coupling2} if wij != 0.0 <int> dij = lengths[j_node] * rec_speed_dt {id = coupling4, dep=coupling3} <float32> theta_j = state[j_node] sum = sum + wij * sin(theta_j - theta_i) end end theta_i = theta_i + dt * (omega + coupling_value * rec_n * sum) {id = out1, dep=coupling4} theta_i = theta_i + (sig * rand) {id = out2, dep=out1} theta_i = wrap_2_pi(theta_i) {id = out3, dep=out2} tavg[i_node] = tavg[i_node] + sin(theta_i) {id = out4, dep=out3} state[i_node] = theta_i {dep=*coupling1} end """, assumptions="n_node>=0") kernel = lp.add_dtypes(kernel, dict(tavg=np.float32, state=np.float32, weights=np.float32, lengths=np.float32)) kernel = kernel.copy(target=lp.CudaTarget()) code = lp.generate_code_v2(kernel) print (kernel) print (code.host_code()) print (code.device_code())
apache-2.0
hagabbar/pycbc_copy
examples/distributions/spin_spatial_distr_example.py
14
1973
import numpy import matplotlib.pyplot as plt import pycbc.coordinates as co from mpl_toolkits.mplot3d import Axes3D from pycbc import distributions # We can choose any bounds between 0 and pi for this distribution but in units # of pi so we use between 0 and 1. theta_low = 0. theta_high = 1. # Units of pi for the bounds of the azimuthal angle which goes from 0 to 2 pi. phi_low = 0. phi_high = 2. # Create a distribution object from distributions.py # Here we are using the Uniform Solid Angle function which takes # theta = polar_bounds(theta_lower_bound to a theta_upper_bound), and then # phi = azimuthal_bound(phi_lower_bound to a phi_upper_bound). uniform_solid_angle_distribution = distributions.UniformSolidAngle( polar_bounds=(theta_low,theta_high), azimuthal_bounds=(phi_low,phi_high)) # Now we can take a random variable sample from that distribution. # In this case we want 50000 samples. solid_angle_samples = uniform_solid_angle_distribution.rvs(size=10000) # Make a spin 1 magnitude since solid angle is only 2 dimensions and we need a # 3rd dimension for a 3D plot that we make later on. spin_mag = numpy.ndarray(shape=(10000), dtype=float) for i in range(0,10000): spin_mag[i] = 1. # Use pycbc.coordinates as co. Use spherical_to_cartesian function to # convert from spherical polar coordinates to cartesian coordinates. spinx, spiny, spinz = co.spherical_to_cartesian(spin_mag, solid_angle_samples['phi'], solid_angle_samples['theta']) # Plot the spherical distribution of spins to make sure that we # distributed across the surface of a sphere. fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111, projection='3d') ax.scatter(spinx, spiny, spinz, s=1) ax.set_xlabel('Spin X Axis') ax.set_ylabel('Spin Y Axis') ax.set_zlabel('Spin Z Axis') plt.show()
gpl-3.0
shitolepriya/Saloon_erp
erpnext/accounts/report/budget_variance_report/budget_variance_report.py
63
4771
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _, msgprint from frappe.utils import flt from frappe.utils import formatdate import time from erpnext.accounts.utils import get_fiscal_year from erpnext.controllers.trends import get_period_date_ranges, get_period_month_ranges def execute(filters=None): if not filters: filters = {} columns = get_columns(filters) period_month_ranges = get_period_month_ranges(filters["period"], filters["fiscal_year"]) cam_map = get_costcenter_account_month_map(filters) data = [] for cost_center, cost_center_items in cam_map.items(): for account, monthwise_data in cost_center_items.items(): row = [cost_center, account] totals = [0, 0, 0] for relevant_months in period_month_ranges: period_data = [0, 0, 0] for month in relevant_months: month_data = monthwise_data.get(month, {}) for i, fieldname in enumerate(["target", "actual", "variance"]): value = flt(month_data.get(fieldname)) period_data[i] += value totals[i] += value period_data[2] = period_data[0] - period_data[1] row += period_data totals[2] = totals[0] - totals[1] row += totals data.append(row) return columns, sorted(data, key=lambda x: (x[0], x[1])) def get_columns(filters): for fieldname in ["fiscal_year", "period", "company"]: if not filters.get(fieldname): label = (" ".join(fieldname.split("_"))).title() msgprint(_("Please specify") + ": " + label, raise_exception=True) columns = [_("Cost Center") + ":Link/Cost Center:120", _("Account") + ":Link/Account:120"] group_months = False if filters["period"] == "Monthly" else True for from_date, to_date in get_period_date_ranges(filters["period"], filters["fiscal_year"]): for label in [_("Target") + " (%s)", _("Actual") + " (%s)", _("Variance") + " (%s)"]: if group_months: label = label % (formatdate(from_date, format_string="MMM") + " - " + formatdate(from_date, format_string="MMM")) else: label = label % formatdate(from_date, format_string="MMM") columns.append(label+":Float:120") return columns + [_("Total Target") + ":Float:120", _("Total Actual") + ":Float:120", _("Total Variance") + ":Float:120"] #Get cost center & target details def get_costcenter_target_details(filters): return frappe.db.sql("""select cc.name, cc.distribution_id, cc.parent_cost_center, bd.account, bd.budget_allocated from `tabCost Center` cc, `tabBudget Detail` bd where bd.parent=cc.name and bd.fiscal_year=%s and cc.company=%s order by cc.name""" % ('%s', '%s'), (filters.get("fiscal_year"), filters.get("company")), as_dict=1) #Get target distribution details of accounts of cost center def get_target_distribution_details(filters): target_details = {} for d in frappe.db.sql("""select md.name, mdp.month, mdp.percentage_allocation from `tabMonthly Distribution Percentage` mdp, `tabMonthly Distribution` md where mdp.parent=md.name and md.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1): target_details.setdefault(d.name, {}).setdefault(d.month, flt(d.percentage_allocation)) return target_details #Get actual details from gl entry def get_actual_details(filters): ac_details = frappe.db.sql("""select gl.account, gl.debit, gl.credit, gl.cost_center, MONTHNAME(gl.posting_date) as month_name from `tabGL Entry` gl, `tabBudget Detail` bd where gl.fiscal_year=%s and company=%s and bd.account=gl.account and bd.parent=gl.cost_center""" % ('%s', '%s'), (filters.get("fiscal_year"), filters.get("company")), as_dict=1) cc_actual_details = {} for d in ac_details: cc_actual_details.setdefault(d.cost_center, {}).setdefault(d.account, []).append(d) return cc_actual_details def get_costcenter_account_month_map(filters): import datetime costcenter_target_details = get_costcenter_target_details(filters) tdd = get_target_distribution_details(filters) actual_details = get_actual_details(filters) cam_map = {} for ccd in costcenter_target_details: for month_id in range(1, 13): month = datetime.date(2013, month_id, 1).strftime('%B') cam_map.setdefault(ccd.name, {}).setdefault(ccd.account, {})\ .setdefault(month, frappe._dict({ "target": 0.0, "actual": 0.0 })) tav_dict = cam_map[ccd.name][ccd.account][month] month_percentage = tdd.get(ccd.distribution_id, {}).get(month, 0) \ if ccd.distribution_id else 100.0/12 tav_dict.target = flt(ccd.budget_allocated) * month_percentage / 100 for ad in actual_details.get(ccd.name, {}).get(ccd.account, []): if ad.month_name == month: tav_dict.actual += flt(ad.debit) - flt(ad.credit) return cam_map
agpl-3.0
mmazanec22/too-windy
env/lib/python3.5/site-packages/pip/_vendor/packaging/requirements.py
448
4327
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import string import re from pip._vendor.pyparsing import ( stringStart, stringEnd, originalTextFor, ParseException ) from pip._vendor.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine from pip._vendor.pyparsing import Literal as L # noqa from pip._vendor.six.moves.urllib import parse as urlparse from .markers import MARKER_EXPR, Marker from .specifiers import LegacySpecifier, Specifier, SpecifierSet class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ ALPHANUM = Word(string.ascii_letters + string.digits) LBRACKET = L("[").suppress() RBRACKET = L("]").suppress() LPAREN = L("(").suppress() RPAREN = L(")").suppress() COMMA = L(",").suppress() SEMICOLON = L(";").suppress() AT = L("@").suppress() PUNCTUATION = Word("-_.") IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) NAME = IDENTIFIER("name") EXTRA = IDENTIFIER URI = Regex(r'[^ ]+')("url") URL = (AT + URI) EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY VERSION_MANY = Combine(VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False)("_raw_spec") _VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)) _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or '') VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") MARKER_EXPR.setParseAction( lambda s, l, t: Marker(s[t._original_start:t._original_end]) ) MARKER_SEPERATOR = SEMICOLON MARKER = MARKER_SEPERATOR + MARKER_EXPR VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) URL_AND_MARKER = URL + Optional(MARKER) NAMED_REQUIREMENT = \ NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd class Requirement(object): """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string): try: req = REQUIREMENT.parseString(requirement_string) except ParseException as e: raise InvalidRequirement( "Invalid requirement, parse error at \"{0!r}\"".format( requirement_string[e.loc:e.loc + 8])) self.name = req.name if req.url: parsed_url = urlparse.urlparse(req.url) if not (parsed_url.scheme and parsed_url.netloc) or ( not parsed_url.scheme and not parsed_url.netloc): raise InvalidRequirement("Invalid URL given") self.url = req.url else: self.url = None self.extras = set(req.extras.asList() if req.extras else []) self.specifier = SpecifierSet(req.specifier) self.marker = req.marker if req.marker else None def __str__(self): parts = [self.name] if self.extras: parts.append("[{0}]".format(",".join(sorted(self.extras)))) if self.specifier: parts.append(str(self.specifier)) if self.url: parts.append("@ {0}".format(self.url)) if self.marker: parts.append("; {0}".format(self.marker)) return "".join(parts) def __repr__(self): return "<Requirement({0!r})>".format(str(self))
gpl-3.0
wtgme/labeldoc2vec
gensim/summarization/textcleaner.py
53
3647
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html from gensim.summarization.syntactic_unit import SyntacticUnit from gensim.parsing.preprocessing import preprocess_documents from gensim.utils import tokenize from six.moves import xrange import re import logging logger = logging.getLogger('summa.preprocessing.cleaner') try: from pattern.en import tag logger.info("'pattern' package found; tag filters are available for English") HAS_PATTERN = True except ImportError: logger.info("'pattern' package not found; tag filters are not available for English") HAS_PATTERN = False SEPARATOR = r"@" RE_SENTENCE = re.compile('(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)', re.UNICODE) # backup (\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$) AB_SENIOR = re.compile("([A-Z][a-z]{1,2}\.)\s(\w)", re.UNICODE) AB_ACRONYM = re.compile("(\.[a-zA-Z]\.)\s(\w)", re.UNICODE) AB_ACRONYM_LETTERS = re.compile("([a-zA-Z])\.([a-zA-Z])\.", re.UNICODE) UNDO_AB_SENIOR = re.compile("([A-Z][a-z]{1,2}\.)" + SEPARATOR + "(\w)", re.UNICODE) UNDO_AB_ACRONYM = re.compile("(\.[a-zA-Z]\.)" + SEPARATOR + "(\w)", re.UNICODE) def split_sentences(text): processed = replace_abbreviations(text) return [undo_replacement(sentence) for sentence in get_sentences(processed)] def replace_abbreviations(text): return replace_with_separator(text, SEPARATOR, [AB_SENIOR, AB_ACRONYM]) def undo_replacement(sentence): return replace_with_separator(sentence, r" ", [UNDO_AB_SENIOR, UNDO_AB_ACRONYM]) def replace_with_separator(text, separator, regexs): replacement = r"\1" + separator + r"\2" result = text for regex in regexs: result = regex.sub(replacement, result) return result def get_sentences(text): for match in RE_SENTENCE.finditer(text): yield match.group() def merge_syntactic_units(original_units, filtered_units, tags=None): units = [] for i in xrange(len(original_units)): if filtered_units[i] == '': continue text = original_units[i] token = filtered_units[i] tag = tags[i][1] if tags else None sentence = SyntacticUnit(text, token, tag) sentence.index = i units.append(sentence) return units def join_words(words, separator=" "): return separator.join(words) def clean_text_by_sentences(text): """ Tokenizes a given text into sentences, applying filters and lemmatizing them. Returns a SyntacticUnit list. """ original_sentences = split_sentences(text) filtered_sentences = [join_words(sentence) for sentence in preprocess_documents(original_sentences)] return merge_syntactic_units(original_sentences, filtered_sentences) def clean_text_by_word(text): """ Tokenizes a given text into words, applying filters and lemmatizing them. Returns a dict of word -> syntacticUnit. """ text_without_acronyms = replace_with_separator(text, "", [AB_ACRONYM_LETTERS]) original_words = list(tokenize(text_without_acronyms, to_lower=True, deacc=True)) filtered_words = [join_words(word_list, "") for word_list in preprocess_documents(original_words)] if HAS_PATTERN: tags = tag(join_words(original_words)) # tag needs the context of the words in the text else: tags = None units = merge_syntactic_units(original_words, filtered_words, tags) return dict((unit.text, unit) for unit in units) def tokenize_by_word(text): text_without_acronyms = replace_with_separator(text, "", [AB_ACRONYM_LETTERS]) return tokenize(text_without_acronyms, to_lower=True, deacc=True)
lgpl-2.1
guerrerocarlos/odoo
addons/portal_project/__openerp__.py
380
1686
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Portal Project', 'version': '0.1', 'category': 'Tools', 'complexity': 'easy', 'description': """ This module adds project menu and features (tasks) to your portal if project and portal are installed. ====================================================================================================== """, 'author': 'OpenERP SA', 'depends': ['project', 'portal'], 'data': [ 'security/portal_security.xml', 'security/ir.model.access.csv', 'portal_project_view.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'category': 'Hidden', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
jorik041/the-backdoor-factory
backdoor.py
3
26910
#!/usr/bin/env python ''' BackdoorFactory (BDF) v2 - Tertium Quid Many thanks to Ryan O'Neill --ryan 'at' codeslum <d ot> org-- Without him, I would still be trying to do stupid things with the elf format. Also thanks to Silvio Cesare with his 1998 paper (http://vxheaven.org/lib/vsc01.html) which these ELF patching techniques are based on. Special thanks to Travis Morrow for poking holes in my ideas. Copyright (c) 2013-2015, Joshua Pitts All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import sys import os import signal import time from random import choice from optparse import OptionParser from pebin import pebin from elfbin import elfbin from machobin import machobin def signal_handler(signal, frame): print '\nProgram Exit' sys.exit(0) class bdfMain(): version = """\ 2.4.1 """ author = """\ Author: Joshua Pitts Email: the.midnite.runr[a t]gmail<d o t>com Twitter: @midnite_runr """ #ASCII ART menu = ["-.(`-') (`-') _ <-" ".(`-') _(`-') (`-')\n" "__( OO) (OO ).-/ _ __( OO)" "( (OO ).-> .-> .-> <-.(OO ) \n" "'-'---.\ / ,---. \-,-----.'-'. ,--" ".\ .'_ (`-')----. (`-')----. ,------,) \n" "| .-. (/ | \ /`.\ | .--./| .' /" "'`'-..__)( OO).-. '( OO).-. '| /`. ' \n" "| '-' `.) '-'|_.' | /_) (`-')| /)" "| | ' |( _) | | |( _) | | || |_.' | \n" "| /`'. |(| .-. | || |OO )| . ' |" " | / : \| |)| | \| |)| || . .' \n" "| '--' / | | | |(_' '--'\| |\ \|" " '-' / ' '-' ' ' '-' '| |\ \ \n" "`------' `--' `--' `-----'`--' '--'" "`------' `-----' `-----' `--' '--' \n" " (`-') _ (`-') " " (`-') \n" " <-. (OO ).-/ _ ( OO).-> " " .-> <-.(OO ) .-> \n" "(`-')-----./ ,---. \-,-----./ '._" " (`-')----. ,------,) ,--.' ,-. \n" "(OO|(_\---'| \ /`.\ | .--./|'--...__)" "( OO).-. '| /`. '(`-')'.' / \n" " / | '--. '-'|_.' | /_) (`-')`--. .--'" "( _) | | || |_.' |(OO \ / \n" " \_) .--'(| .-. | || |OO ) | | " " \| |)| || . .' | / /) \n" " `| |_) | | | |(_' '--'\ | | " " ' '-' '| |\ \ `-/ /` \n" " `--' `--' `--' `-----' `--' " " `-----' `--' '--' `--' \n", "__________ " " __ .___ \n" "\______ \_____ ____ " "| | __ __| _/____ ___________ \n" " | | _/\__ \ _/ ___\|" " |/ // __ |/ _ \ / _ \_ __ \ \n" " | | \ / __ \\\\ \__" "_| </ /_/ ( <_> | <_> ) | \/\n" " |______ /(____ /\___ >" "__|_ \____ |\____/ \____/|__| \n" " \/ \/ \/" " \/ \/ \n" "___________ " "__ \n" "\_ _____/____ _____/" " |_ ___________ ___.__. \n" " | __) \__ \ _/ ___\ " " __\/ _ \_ __ < | | \n" " | \ / __ \\\\ \__" "_| | ( <_> ) | \/\___ | \n" " \___ / (____ /\___ >_" "_| \____/|__| / ____| \n" " \/ \/ \/ " " \/ \n"] signal.signal(signal.SIGINT, signal_handler) parser = OptionParser() parser.add_option("-f", "--file", dest="FILE", action="store", type="string", help="File to backdoor") parser.add_option("-s", "--shell", default="show", dest="SHELL", action="store", type="string", help="Payloads that are available for use." " Use 'show' to see payloads." ) parser.add_option("-H", "--hostip", default=None, dest="HOST", action="store", type="string", help="IP of the C2 for reverse connections.") parser.add_option("-P", "--port", default=None, dest="PORT", action="store", type="int", help="The port to either connect back to for reverse " "shells or to listen on for bind shells") parser.add_option("-J", "--cave_jumping", dest="CAVE_JUMPING", default=False, action="store_true", help="Select this options if you want to use code cave" " jumping to further hide your shellcode in the binary." ) parser.add_option("-a", "--add_new_section", default=False, dest="ADD_SECTION", action="store_true", help="Mandating that a new section be added to the " "exe (better success) but less av avoidance") parser.add_option("-U", "--user_shellcode", default=None, dest="SUPPLIED_SHELLCODE", action="store", help="User supplied shellcode, make sure that it matches" " the architecture that you are targeting." ) parser.add_option("-c", "--cave", default=False, dest="FIND_CAVES", action="store_true", help="The cave flag will find code caves that " "can be used for stashing shellcode. " "This will print to all the code caves " "of a specific size." "The -l flag can be use with this setting.") parser.add_option("-l", "--shell_length", default=380, dest="SHELL_LEN", action="store", type="int", help="For use with -c to help find code " "caves of different sizes") parser.add_option("-o", "--output-file", default=None, dest="OUTPUT", action="store", type="string", help="The backdoor output file") parser.add_option("-n", "--section", default="sdata", dest="NSECTION", action="store", type="string", help="New section name must be " "less than seven characters") parser.add_option("-d", "--directory", dest="DIR", action="store", type="string", help="This is the location of the files that " "you want to backdoor. " "You can make a directory of file backdooring faster by " "forcing the attaching of a codecave " "to the exe by using the -a setting.") parser.add_option("-w", "--change_access", default=True, dest="CHANGE_ACCESS", action="store_false", help="This flag changes the section that houses " "the codecave to RWE. Sometimes this is necessary. " "Enabled by default. If disabled, the " "backdoor may fail.") parser.add_option("-i", "--injector", default=False, dest="INJECTOR", action="store_true", help="This command turns the backdoor factory in a " "hunt and shellcode inject type of mechanism. Edit " "the target settings in the injector module.") parser.add_option("-u", "--suffix", default=".old", dest="SUFFIX", action="store", type="string", help="For use with injector, places a suffix" " on the original file for easy recovery") parser.add_option("-D", "--delete_original", dest="DELETE_ORIGINAL", default=False, action="store_true", help="For use with injector module. This command" " deletes the original file. Not for use in production " "systems. *Author not responsible for stupid uses.*") parser.add_option("-O", "--disk_offset", dest="DISK_OFFSET", default=0, type="int", action="store", help="Starting point on disk offset, in bytes. " "Some authors want to obfuscate their on disk offset " "to avoid reverse engineering, if you find one of those " "files use this flag, after you find the offset.") parser.add_option("-S", "--support_check", dest="SUPPORT_CHECK", default=False, action="store_true", help="To determine if the file is supported by BDF prior" " to backdooring the file. For use by itself or with " "verbose. This check happens automatically if the " "backdooring is attempted." ) parser.add_option("-M", "--cave-miner", dest="CAVE_MINER", default=False, action="store_true", help="Future use, to help determine smallest shellcode possible in a PE file" ) parser.add_option("-q", "--no_banner", dest="NO_BANNER", default=False, action="store_true", help="Kills the banner." ) parser.add_option("-v", "--verbose", default=False, dest="VERBOSE", action="store_true", help="For debug information output.") parser.add_option("-T", "--image-type", dest="IMAGE_TYPE", default="ALL", type='string', action="store", help="ALL, x86, or x64 type binaries only. Default=ALL") parser.add_option("-Z", "--zero_cert", dest="ZERO_CERT", default=True, action="store_false", help="Allows for the overwriting of the pointer to the PE certificate table" " effectively removing the certificate from the binary for all intents" " and purposes." ) parser.add_option("-R", "--runas_admin", dest="CHECK_ADMIN", default=False, action="store_true", help="Checks the PE binaries for \'requestedExecutionLevel level=\"highestAvailable\"\'" ". If this string is included in the binary, it must run as system/admin. Doing this " "slows patching speed significantly." ) parser.add_option("-L", "--patch_dll", dest="PATCH_DLL", default=True, action="store_false", help="Use this setting if you DON'T want to patch DLLs. Patches by default." ) parser.add_option("-F", "--fat_priority", dest="FAT_PRIORITY", default="x64", action="store", help="For MACH-O format. If fat file, focus on which arch to patch. Default " "is x64. To force x86 use -F x86, to force both archs use -F ALL." ) parser.add_option("-B", "--beacon", dest="BEACON", default=15, action="store", type="int", help="For payloads that have the ability to beacon out, set the time in secs" ) (options, args) = parser.parse_args() def basicDiscovery(FILE): macho_supported = ['\xcf\xfa\xed\xfe', '\xca\xfe\xba\xbe', '\xce\xfa\xed\xfe', ] testBinary = open(FILE, 'rb') header = testBinary.read(4) testBinary.close() if 'MZ' in header: return 'PE' elif 'ELF' in header: return 'ELF' elif header in macho_supported: return "MACHO" else: 'Only support ELF, PE, and MACH-O file formats' return None if options.NO_BANNER is False: print choice(menu) print author print version time.sleep(1) if options.DIR: for root, subFolders, files in os.walk(options.DIR): for _file in files: options.FILE = os.path.join(root, _file) if os.path.isdir(options.FILE) is True: print "Directory found, continuing" continue is_supported = basicDiscovery(options.FILE) if is_supported is "PE": supported_file = pebin(options.FILE, options.OUTPUT, options.SHELL, options.NSECTION, options.DISK_OFFSET, options.ADD_SECTION, options.CAVE_JUMPING, options.PORT, options.HOST, options.SUPPLIED_SHELLCODE, options.INJECTOR, options.CHANGE_ACCESS, options.VERBOSE, options.SUPPORT_CHECK, options.SHELL_LEN, options.FIND_CAVES, options.SUFFIX, options.DELETE_ORIGINAL, options.CAVE_MINER, options.IMAGE_TYPE, options.ZERO_CERT, options.CHECK_ADMIN, options.PATCH_DLL ) elif is_supported is "ELF": supported_file = elfbin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.FIND_CAVES, options.SHELL_LEN, options.SUPPLIED_SHELLCODE, options.IMAGE_TYPE ) elif is_supported is "MACHO": supported_file = machobin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.SUPPLIED_SHELLCODE, options.FAT_PRIORITY, options.BEACON ) if options.SUPPORT_CHECK is True: if os.path.isfile(options.FILE): is_supported = False print "file", options.FILE try: is_supported = supported_file.support_check() except Exception, e: is_supported = False print 'Exception:', str(e), '%s' % options.FILE if is_supported is False or is_supported is None: print "%s is not supported." % options.FILE #continue else: print "%s is supported." % options.FILE # if supported_file.flItms['runas_admin'] is True: # print "%s must be run as admin." % options.FILE print "*" * 50 if options.SUPPORT_CHECK is True: sys.exit() print ("You are going to backdoor the following " "items in the %s directory:" % options.DIR) dirlisting = os.listdir(options.DIR) for item in dirlisting: print " {0}".format(item) answer = raw_input("Do you want to continue? (yes/no) ") if 'yes' in answer.lower(): for item in dirlisting: #print item print "*" * 50 options.File = options.DIR + '/' + item if os.path.isdir(options.FILE) is True: print "Directory found, continuing" continue print ("backdooring file %s" % item) result = None is_supported = basicDiscovery(options.FILE) try: if is_supported is "PE": supported_file = pebin(options.FILE, options.OUTPUT, options.SHELL, options.NSECTION, options.DISK_OFFSET, options.ADD_SECTION, options.CAVE_JUMPING, options.PORT, options.HOST, options.SUPPLIED_SHELLCODE, options.INJECTOR, options.CHANGE_ACCESS, options.VERBOSE, options.SUPPORT_CHECK, options.SHELL_LEN, options.FIND_CAVES, options.SUFFIX, options.DELETE_ORIGINAL, options.CAVE_MINER, options.IMAGE_TYPE, options.ZERO_CERT, options.CHECK_ADMIN, options.PATCH_DLL ) supported_file.OUTPUT = None supported_file.output_options() result = supported_file.patch_pe() elif is_supported is "ELF": supported_file = elfbin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.FIND_CAVES, options.SHELL_LEN, options.SUPPLIED_SHELLCODE, options.IMAGE_TYPE ) supported_file.OUTPUT = None supported_file.output_options() result = supported_file.patch_elf() elif is_supported is "MACHO": supported_file = machobin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.SUPPLIED_SHELLCODE, options.FAT_PRIORITY, options.BEACON ) supported_file.OUTPUT = None supported_file.output_options() result = supported_file.patch_macho() if result is None: print 'Not Supported. Continuing' continue else: print ("[*] File {0} is in backdoored " "directory".format(supported_file.FILE)) except Exception as e: print "DIR ERROR", str(e) else: print("Goodbye") sys.exit() if options.INJECTOR is True: supported_file = pebin(options.FILE, options.OUTPUT, options.SHELL, options.NSECTION, options.DISK_OFFSET, options.ADD_SECTION, options.CAVE_JUMPING, options.PORT, options.HOST, options.SUPPLIED_SHELLCODE, options.INJECTOR, options.CHANGE_ACCESS, options.VERBOSE, options.SUPPORT_CHECK, options.SHELL_LEN, options.FIND_CAVES, options.SUFFIX, options.DELETE_ORIGINAL, options.IMAGE_TYPE, options.ZERO_CERT, options.CHECK_ADMIN, options.PATCH_DLL ) supported_file.injector() sys.exit() if not options.FILE: parser.print_help() sys.exit() #OUTPUT = output_options(options.FILE, options.OUTPUT) is_supported = basicDiscovery(options.FILE) if is_supported is "PE": supported_file = pebin(options.FILE, options.OUTPUT, options.SHELL, options.NSECTION, options.DISK_OFFSET, options.ADD_SECTION, options.CAVE_JUMPING, options.PORT, options.HOST, options.SUPPLIED_SHELLCODE, options.INJECTOR, options.CHANGE_ACCESS, options.VERBOSE, options.SUPPORT_CHECK, options.SHELL_LEN, options.FIND_CAVES, options.SUFFIX, options.DELETE_ORIGINAL, options.CAVE_MINER, options.IMAGE_TYPE, options.ZERO_CERT, options.CHECK_ADMIN, options.PATCH_DLL ) elif is_supported is "ELF": supported_file = elfbin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.FIND_CAVES, options.SHELL_LEN, options.SUPPLIED_SHELLCODE, options.IMAGE_TYPE ) elif is_supported is "MACHO": supported_file = machobin(options.FILE, options.OUTPUT, options.SHELL, options.HOST, options.PORT, options.SUPPORT_CHECK, options.SUPPLIED_SHELLCODE, options.FAT_PRIORITY, options.BEACON ) else: print "Not supported." sys.exit() result = supported_file.run_this() if result is True and options.SUPPORT_CHECK is False: print "File {0} is in the 'backdoored' directory".format(os.path.basename(supported_file.OUTPUT)) #END BDF MAIN if __name__ == "__main__": bdfMain()
bsd-3-clause
ashishnitinpatil/django_appengine_project_template
django/contrib/gis/db/backends/postgis/operations.py
108
24998
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six from django.utils.functional import cached_property from .models import GeometryColumns, SpatialRefSys #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'postgis' postgis = True geom_func_prefix = 'ST_' version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) prefix = self.geom_func_prefix # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), 'dwithin' : (PostGISFunctionParam(prefix, 'DWithin'), dtypes) } # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if self.spatial_version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if self.spatial_version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if self.spatial_version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby': self.geometry_functions['coveredby'], 'covers': self.geometry_functions['covers'], 'intersects': self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps': PostGISOperator('&&'), } # Native geometry type support added in PostGIS 2.0. if self.spatial_version >= (2, 0, 0): self.geometry = True # Creating a dictionary lookup of all GIS terms for PostGIS. self.gis_terms = set(['isnull']) self.gis_terms.update(self.geometry_operators) self.gis_terms.update(self.geometry_functions) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' if self.spatial_version >= (2, 0, 0): self.extent3d = prefix + '3DExtent' self.length3d = prefix + '3DLength' self.perimeter3d = prefix + '3DPerimeter' else: self.extent3d = prefix + 'Extent3D' self.length3d = prefix + 'Length3D' self.perimeter3d = prefix + 'Perimeter3D' @cached_property def spatial_version(self): """Determine the version of the PostGIS library.""" # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. if hasattr(settings, 'POSTGIS_VERSION'): version = settings.POSTGIS_VERSION else: try: vtup = self.postgis_version_tuple() except DatabaseError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) version = vtup[1:] return version def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)' % (f.geom_type, f.srid) elif self.geometry: # Postgis 2.0 supports type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + 'Z' else: geom_type = f.geom_type return 'geometry(%s,%d)' % (geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % self.get_expression_column(value) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute('SELECT %s()' % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param): """ Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param) def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only available from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, ('' if value else 'NOT ')), [] raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): return GeometryColumns def spatial_ref_sys(self): return SpatialRefSys
bsd-2-clause
dbaxa/django
tests/gis_tests/gis_migrations/test_commands.py
276
2723
from __future__ import unicode_literals from django.core.management import call_command from django.db import connection from django.test import TransactionTestCase, skipUnlessDBFeature @skipUnlessDBFeature("gis_enabled") class MigrateTests(TransactionTestCase): """ Tests running the migrate command in Geodjango. """ available_apps = ["gis_tests.gis_migrations"] def get_table_description(self, table): with connection.cursor() as cursor: return connection.introspection.get_table_description(cursor, table) def assertTableExists(self, table): with connection.cursor() as cursor: self.assertIn(table, connection.introspection.table_names(cursor)) def assertTableNotExists(self, table): with connection.cursor() as cursor: self.assertNotIn(table, connection.introspection.table_names(cursor)) def test_migrate_gis(self): """ Tests basic usage of the migrate command when a model uses Geodjango fields. Regression test for ticket #22001: https://code.djangoproject.com/ticket/22001 It's also used to showcase an error in migrations where spatialite is enabled and geo tables are renamed resulting in unique constraint failure on geometry_columns. Regression for ticket #23030: https://code.djangoproject.com/ticket/23030 """ # Make sure the right tables exist self.assertTableExists("gis_migrations_neighborhood") self.assertTableExists("gis_migrations_household") self.assertTableExists("gis_migrations_family") if connection.features.supports_raster: self.assertTableExists("gis_migrations_heatmap") # Unmigrate everything call_command("migrate", "gis_migrations", "zero", verbosity=0) # Make sure it's all gone self.assertTableNotExists("gis_migrations_neighborhood") self.assertTableNotExists("gis_migrations_household") self.assertTableNotExists("gis_migrations_family") if connection.features.supports_raster: self.assertTableNotExists("gis_migrations_heatmap") # Even geometry columns metadata try: GeoColumn = connection.ops.geometry_columns() except NotImplementedError: # Not all GIS backends have geometry columns model pass else: self.assertEqual( GeoColumn.objects.filter( **{'%s__in' % GeoColumn.table_name_col(): ["gis_neighborhood", "gis_household"]} ).count(), 0) # Revert the "unmigration" call_command("migrate", "gis_migrations", verbosity=0)
bsd-3-clause
lecaoquochung/ddnb.django
tests/delete/models.py
148
3676
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class R(models.Model): is_default = models.BooleanField(default=False) def __str__(self): return "%s" % self.pk get_default_r = lambda: R.objects.get_or_create(is_default=True)[0] class S(models.Model): r = models.ForeignKey(R) class T(models.Model): s = models.ForeignKey(S) class U(models.Model): t = models.ForeignKey(T) class RChild(R): pass class A(models.Model): name = models.CharField(max_length=30) auto = models.ForeignKey(R, related_name="auto_set") auto_nullable = models.ForeignKey(R, null=True, related_name='auto_nullable_set') setvalue = models.ForeignKey(R, on_delete=models.SET(get_default_r), related_name='setvalue') setnull = models.ForeignKey(R, on_delete=models.SET_NULL, null=True, related_name='setnull_set') setdefault = models.ForeignKey(R, on_delete=models.SET_DEFAULT, default=get_default_r, related_name='setdefault_set') setdefault_none = models.ForeignKey(R, on_delete=models.SET_DEFAULT, default=None, null=True, related_name='setnull_nullable_set') cascade = models.ForeignKey(R, on_delete=models.CASCADE, related_name='cascade_set') cascade_nullable = models.ForeignKey(R, on_delete=models.CASCADE, null=True, related_name='cascade_nullable_set') protect = models.ForeignKey(R, on_delete=models.PROTECT, null=True) donothing = models.ForeignKey(R, on_delete=models.DO_NOTHING, null=True, related_name='donothing_set') child = models.ForeignKey(RChild, related_name="child") child_setnull = models.ForeignKey(RChild, on_delete=models.SET_NULL, null=True, related_name="child_setnull") # A OneToOneField is just a ForeignKey unique=True, so we don't duplicate # all the tests; just one smoke test to ensure on_delete works for it as # well. o2o_setnull = models.ForeignKey(R, null=True, on_delete=models.SET_NULL, related_name="o2o_nullable_set") def create_a(name): a = A(name=name) for name in ('auto', 'auto_nullable', 'setvalue', 'setnull', 'setdefault', 'setdefault_none', 'cascade', 'cascade_nullable', 'protect', 'donothing', 'o2o_setnull'): r = R.objects.create() setattr(a, name, r) a.child = RChild.objects.create() a.child_setnull = RChild.objects.create() a.save() return a class M(models.Model): m2m = models.ManyToManyField(R, related_name="m_set") m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set") m2m_through_null = models.ManyToManyField(R, through="MRNull", related_name="m_through_null_set") class MR(models.Model): m = models.ForeignKey(M) r = models.ForeignKey(R) class MRNull(models.Model): m = models.ForeignKey(M) r = models.ForeignKey(R, null=True, on_delete=models.SET_NULL) class Avatar(models.Model): desc = models.TextField(null=True) class User(models.Model): avatar = models.ForeignKey(Avatar, null=True) class HiddenUser(models.Model): r = models.ForeignKey(R, related_name="+") class HiddenUserProfile(models.Model): user = models.ForeignKey(HiddenUser) class M2MTo(models.Model): pass class M2MFrom(models.Model): m2m = models.ManyToManyField(M2MTo) class Parent(models.Model): pass class Child(Parent): pass class Base(models.Model): pass class RelToBase(models.Model): base = models.ForeignKey(Base, on_delete=models.DO_NOTHING)
bsd-3-clause
eepalms/gem5-newcache
tests/configs/realview-simple-timing-dual.py
6
2272
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright holders 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. # # Authors: Andreas Sandberg from m5.objects import * from arm_generic import * root = LinuxArmFSSystem(mem_mode='timing', cpu_class=TimingSimpleCPU, num_cpus=2).create_root()
bsd-3-clause
dionyziz/ting
API/chat/tests/message/test_post_view.py
3
6826
from chat.tests.message.common import * from django.utils.dateformat import format class MessageViewPOSTTests(ChatTests): def post_and_get_response(self, message_content, timestamp, username, typing, message_type): """ Posts a message on chat:message and returns the response """ return self.privileged_operation( reverse('chat:message', args=('channel', self.channel.name,)), {'message_content': message_content, 'username': username, 'datetime_start': timestamp, 'typing': typing, 'message_type': message_type}, 'post' ) def test_post_valid_message(self): """ When a valid message is sent, the view should save the message in the database and return the id of the message. """ timestamp = 10 ** 11 username = 'vitsalisa' message_content = 'Message' message_type = 'text' response = self.post_and_get_response( message_content=message_content, timestamp=timestamp, username=username, typing=True, message_type=message_type ) messages = Message.objects.filter(username=username) self.assertTrue(messages.exists()) self.assertEquals(len(messages), 1) self.assertEqual(response.status_code, 200) message = Message.objects.get(username=username); self.assertEqual(int(response.content), message.id); self.assertEqual(message.username, username); self.assertTrue(message.typing) self.assertEqual(message.message_content, message_content) self.assertEqual(datetime_to_timestamp(message.datetime_start), timestamp) def test_post_message_without_datetime_start(self): """ When a message is sent without a datetime_start the view should produce an appropriate error and a 400(Bad Request) status code. The message should not be saved. """ post_dict = {'message_content': 'Message', 'username': 'vitsalis', 'typing': True, 'message_type': 'text'} response = self.privileged_operation( reverse('chat:message', args=('channel', self.channel.name,)), post_dict, 'post' ) self.assertFalse(Message.objects.filter(username='vitsalis').exists()) self.assertEqual(response.status_code, 400) def test_post_message_without_username(self): """ When a message is sent without a username the view should produce an appropriate error and a 400(Bad Request) status code. The message should not be saved. """ timestamp = 10 ** 11 post_dict = {'message_content': 'Message', 'datetime_start': timestamp, 'typing': True, 'message_type': 'text'} response = self.privileged_operation( reverse('chat:message', args=('channel', self.channel.name,)), post_dict, 'post' ) datetime_start_field = timestamp_to_datetime(timestamp) self.assertFalse(Message.objects.filter(datetime_start=datetime_start_field).exists()) self.assertEqual(response.status_code, 400) def test_post_message_with_invalid_channel_name(self): """ When a message is sent with an invalid channel name the view should produce an appropriate error and a 404(Not Found) status code. The message should not be saved. """ timestamp = 10 ** 11 response = self.privileged_operation( reverse('chat:message', args=('channel', 'invalid_channel',)), {'message_content': 'Message', 'username': 'vitsalis', 'datetime_start': timestamp, 'typing': True, 'message_type': 'text'}, 'post' ) self.assertFalse(Message.objects.filter(username='vitsalis').exists()) self.assertEqual(response.status_code, 404) def test_post_message_without_text(self): """ When a message is sent without a channel_id the view should produce an appropriate error and a 400(Bad Request) status code. The message should not be saved. """ timestamp = 10 ** 11 post_dict = {'username': 'vitsalis', 'datetime_start': timestamp, 'typing': True, 'message_type': 'text'} response = self.privileged_operation( reverse('chat:message', args=('channel', self.channel.name,)), post_dict, 'post' ) self.assertFalse(Message.objects.filter(username='vitsalis').exists()) self.assertEqual(response.status_code, 400) def test_post_message_with_invalid_datetime_start(self): """ When a message is sent with an invalid datetime the view should produce an appropriate error and a 400(Bad Request) status code. The message should not be saved. """ response = self.post_and_get_response( message_content='Message', timestamp='wtf', username='vitsalis', typing=True, message_type='text' ) self.assertFalse(Message.objects.filter(username='vitsalis').exists()) self.assertEqual(response.status_code, 400) def test_post_message_with_future_datetime_start(self): """ When a message is sent with a future datetime the view should change the datetime to the current one and save the message. """ timestamp = int(format(datetime.datetime.utcnow() + datetime.timedelta(days=1), 'U')) * 1000 response = self.post_and_get_response( message_content='Message', timestamp=timestamp, username='vitsalis', typing=True, message_type='text' ) messages = Message.objects.filter(username='vitsalis') self.assertTrue(messages.exists()) self.assertEqual(len(messages), 1) self.assertTrue(datetime_to_timestamp(messages[0].datetime_start) < timestamp) self.assertEqual(response.status_code, 200) self.assertEqual(int(response.content), messages[0].id) def test_post_message_with_typing_false(self): """ When typing is False the view should save the message and make its datetime_sent equal to datetime_start. """ timestamp = 10 ** 11 response = self.post_and_get_response( message_content='Message', timestamp=timestamp, username='vitsalis', typing=False, message_type='text' ) messages = Message.objects.filter(username='vitsalis') self.assertTrue(messages.exists()) self.assertEqual(len(messages), 1) self.assertEqual(messages[0].datetime_sent, messages[0].datetime_start)
mit
mywaiting/LifeLogger
tornado/options.py
58
19182
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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. """A command line parsing module that lets modules define their own options. Each module defines its own options which are added to the global option namespace, e.g.:: from tornado.options import define, options define("mysql_host", default="127.0.0.1:3306", help="Main user DB") define("memcache_hosts", default="127.0.0.1:11011", multiple=True, help="Main user memcache servers") def connect(): db = database.Connection(options.mysql_host) ... The ``main()`` method of your application does not need to be aware of all of the options used throughout your program; they are all automatically loaded when the modules are loaded. However, all modules that define options must have been imported before the command line is parsed. Your ``main()`` method can parse the command line or parse a config file with either:: tornado.options.parse_command_line() # or tornado.options.parse_config_file("/etc/server.conf") Command line formats are what you would expect (``--myoption=myvalue``). Config files are just Python files. Global names become options, e.g.:: myoption = "myvalue" myotheroption = "myothervalue" We support `datetimes <datetime.datetime>`, `timedeltas <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to `define`). We also accept multi-value options. See the documentation for `define()` below. `tornado.options.options` is a singleton instance of `OptionParser`, and the top-level functions in this module (`define`, `parse_command_line`, etc) simply call methods on it. You may create additional `OptionParser` instances to define isolated sets of options, such as for subcommands. """ from __future__ import absolute_import, division, print_function, with_statement import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode from tornado.log import define_logging_options from tornado import stack_context from tornado.util import basestring_type, exec_in class Error(Exception): """Exception raised by errors in the options module.""" pass class OptionParser(object): """A collection of options, a dictionary with object-like access. Normally accessed via static functions in the `tornado.options` module, which reference a global instance. """ def __init__(self): # we have to use self.__dict__ because we override setattr. self.__dict__['_options'] = {} self.__dict__['_parse_callbacks'] = [] self.define("help", type=bool, help="show this help information", callback=self._help_callback) def __getattr__(self, name): if isinstance(self._options.get(name), _Option): return self._options[name].value() raise AttributeError("Unrecognized option %r" % name) def __setattr__(self, name, value): if isinstance(self._options.get(name), _Option): return self._options[name].set(value) raise AttributeError("Unrecognized option %r" % name) def __iter__(self): return iter(self._options) def __getitem__(self, item): return self._options[item].value() def items(self): """A sequence of (name, value) pairs. .. versionadded:: 3.1 """ return [(name, opt.value()) for name, opt in self._options.items()] def groups(self): """The set of option-groups created by ``define``. .. versionadded:: 3.1 """ return set(opt.group_name for opt in self._options.values()) def group_dict(self, group): """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application')) .. versionadded:: 3.1 """ return dict( (name, opt.value()) for name, opt in self._options.items() if not group or group == opt.group_name) def as_dict(self): """The names and values of all options. .. versionadded:: 3.1 """ return dict( (name, opt.value()) for name, opt in self._options.items()) def define(self, name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines a new command line option. If ``type`` is given (one of str, float, int, datetime, or timedelta) or can be inferred from the ``default``, we parse the command line arguments based on the given type. If ``multiple`` is True, we accept comma-separated values, and the option value is always a list. For multi-value integers, we also accept the syntax ``x:y``, which turns into ``range(x, y)`` - very useful for long integer ranges. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. They can be parsed from the command line with `parse_command_line` or parsed from a config file with `parse_config_file`. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags. """ if name in self._options: raise Error("Option %r already defined in %s" % (name, self._options[name].file_name)) frame = sys._getframe(0) options_file = frame.f_code.co_filename file_name = frame.f_back.f_code.co_filename if file_name == options_file: file_name = "" if type is None: if not multiple and default is not None: type = default.__class__ else: type = str if group: group_name = group else: group_name = file_name self._options[name] = _Option(name, file_name=file_name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group_name=group_name, callback=callback) def parse_command_line(self, args=None, final=True): """Parses all options given on the command line (defaults to `sys.argv`). Note that ``args[0]`` is ignored since it is the program name in `sys.argv`. We return a list of all arguments that are not parsed as options. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ if args is None: args = sys.argv remaining = [] for i in range(1, len(args)): # All things after the last option are command line arguments if not args[i].startswith("-"): remaining = args[i:] break if args[i] == "--": remaining = args[i + 1:] break arg = args[i].lstrip("-") name, equals, value = arg.partition("=") name = name.replace('-', '_') if not name in self._options: self.print_help() raise Error('Unrecognized command line option: %r' % name) option = self._options[name] if not equals: if option.type == bool: value = "true" else: raise Error('Option %r requires a value' % name) option.parse(value) if final: self.run_parse_callbacks() return remaining def parse_config_file(self, path, final=True): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ config = {} with open(path) as f: exec_in(f.read(), config, config) for name in config: if name in self._options: self._options[name].set(config[name]) if final: self.run_parse_callbacks() def print_help(self, file=None): """Prints all the command line options to stderr (or another file).""" if file is None: file = sys.stderr print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) print("\nOptions:\n", file=file) by_group = {} for option in self._options.values(): by_group.setdefault(option.group_name, []).append(option) for filename, o in sorted(by_group.items()): if filename: print("\n%s options:\n" % os.path.normpath(filename), file=file) o.sort(key=lambda option: option.name) for option in o: prefix = option.name if option.metavar: prefix += "=" + option.metavar description = option.help or "" if option.default is not None and option.default != '': description += " (default %s)" % option.default lines = textwrap.wrap(description, 79 - 35) if len(prefix) > 30 or len(lines) == 0: lines.insert(0, '') print(" --%-30s %s" % (prefix, lines[0]), file=file) for line in lines[1:]: print("%-34s %s" % (' ', line), file=file) print(file=file) def _help_callback(self, value): if value: self.print_help() sys.exit(0) def add_parse_callback(self, callback): """Adds a parse callback, to be invoked when option parsing is done.""" self._parse_callbacks.append(stack_context.wrap(callback)) def run_parse_callbacks(self): for callback in self._parse_callbacks: callback() def mockable(self): """Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`. The `mock.patch <unittest.mock.patch>` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party ``mock`` package for older versions of Python) is incompatible with objects like ``options`` that override ``__getattr__`` and ``__setattr__``. This function returns an object that can be used with `mock.patch.object <unittest.mock.patch.object>` to modify option values:: with mock.patch.object(options.mockable(), 'name', value): assert options.name == value """ return _Mockable(self) class _Mockable(object): """`mock.patch` compatible wrapper for `OptionParser`. As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete the attribute it set instead of setting a new one (assuming that the object does not catpure ``__setattr__``, so the patch created a new attribute in ``__dict__``). _Mockable's getattr and setattr pass through to the underlying OptionParser, and delattr undoes the effect of a previous setattr. """ def __init__(self, options): # Modify __dict__ directly to bypass __setattr__ self.__dict__['_options'] = options self.__dict__['_originals'] = {} def __getattr__(self, name): return getattr(self._options, name) def __setattr__(self, name, value): assert name not in self._originals, "don't reuse mockable objects" self._originals[name] = getattr(self._options, name) setattr(self._options, name, value) def __delattr__(self, name): setattr(self._options, name, self._originals.pop(name)) class _Option(object): def __init__(self, name, default=None, type=basestring_type, help=None, metavar=None, multiple=False, file_name=None, group_name=None, callback=None): if default is None and multiple: default = [] self.name = name self.type = type self.help = help self.metavar = metavar self.multiple = multiple self.file_name = file_name self.group_name = group_name self.callback = callback self.default = default self._value = None def value(self): return self.default if self._value is None else self._value def parse(self, value): _parse = { datetime.datetime: self._parse_datetime, datetime.timedelta: self._parse_timedelta, bool: self._parse_bool, basestring_type: self._parse_string, }.get(self.type, self.type) if self.multiple: self._value = [] for part in value.split(","): if issubclass(self.type, numbers.Integral): # allow ranges of the form X:Y (inclusive at both ends) lo, _, hi = part.partition(":") lo = _parse(lo) hi = _parse(hi) if hi else lo self._value.extend(range(lo, hi + 1)) else: self._value.append(_parse(part)) else: self._value = _parse(value) if self.callback is not None: self.callback(self._value) return self.value() def set(self, value): if self.multiple: if not isinstance(value, list): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) for item in value: if item is not None and not isinstance(item, self.type): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) else: if value is not None and not isinstance(value, self.type): raise Error("Option %r is required to be a %s (%s given)" % (self.name, self.type.__name__, type(value))) self._value = value if self.callback is not None: self.callback(self._value) # Supported date/time formats in our options _DATETIME_FORMATS = [ "%a %b %d %H:%M:%S %Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y%m%d %H:%M:%S", "%Y%m%d %H:%M", "%Y-%m-%d", "%Y%m%d", "%H:%M:%S", "%H:%M", ] def _parse_datetime(self, value): for format in self._DATETIME_FORMATS: try: return datetime.datetime.strptime(value, format) except ValueError: pass raise Error('Unrecognized date/time format: %r' % value) _TIMEDELTA_ABBREVS = [ ('hours', ['h']), ('minutes', ['m', 'min']), ('seconds', ['s', 'sec']), ('milliseconds', ['ms']), ('microseconds', ['us']), ('days', ['d']), ('weeks', ['w']), ] _TIMEDELTA_ABBREV_DICT = dict( (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS for abbrev in abbrevs) _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?' _TIMEDELTA_PATTERN = re.compile( r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE) def _parse_timedelta(self, value): try: sum = datetime.timedelta() start = 0 while start < len(value): m = self._TIMEDELTA_PATTERN.match(value, start) if not m: raise Exception() num = float(m.group(1)) units = m.group(2) or 'seconds' units = self._TIMEDELTA_ABBREV_DICT.get(units, units) sum += datetime.timedelta(**{units: num}) start = m.end() return sum except Exception: raise def _parse_bool(self, value): return value.lower() not in ("false", "0", "f") def _parse_string(self, value): return _unicode(value) options = OptionParser() """Global options object. All defined options are available as attributes on this object. """ def define(name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines an option in the global namespace. See `OptionParser.define`. """ return options.define(name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group=group, callback=callback) def parse_command_line(args=None, final=True): """Parses global options from the command line. See `OptionParser.parse_command_line`. """ return options.parse_command_line(args, final=final) def parse_config_file(path, final=True): """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final) def print_help(file=None): """Prints all the command line options to stderr (or another file). See `OptionParser.print_help`. """ return options.print_help(file) def add_parse_callback(callback): """Adds a parse callback, to be invoked when option parsing is done. See `OptionParser.add_parse_callback` """ options.add_parse_callback(callback) # Default options define_logging_options(options)
mit
ampax/edx-platform
lms/djangoapps/course_api/blocks/transformers/navigation.py
35
3103
""" TODO """ from openedx.core.lib.block_structure.transformer import BlockStructureTransformer from .block_depth import BlockDepthTransformer class DescendantList(object): """ Contain """ def __init__(self): self.items = [] class BlockNavigationTransformer(BlockStructureTransformer): """ Creates a table of contents for the course. Prerequisites: BlockDepthTransformer must be run before this in the transform phase. """ VERSION = 1 BLOCK_NAVIGATION = 'block_nav' BLOCK_NAVIGATION_FOR_CHILDREN = 'children_block_nav' def __init__(self, nav_depth): self.nav_depth = nav_depth @classmethod def name(cls): return "blocks_api:block_navigation" @classmethod def collect(cls, block_structure): """ Collects any information that's necessary to execute this transformer's transform method. """ # collect basic xblock fields block_structure.request_xblock_fields('hide_from_toc') def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ if self.nav_depth is None: return for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) parents_descendants_list = set() for parent_key in parents: parent_nav = block_structure.get_transformer_block_field( parent_key, self, self.BLOCK_NAVIGATION_FOR_CHILDREN, ) if parent_nav is not None: parents_descendants_list |= parent_nav children_descendants_list = None if ( not block_structure.get_xblock_field(block_key, 'hide_from_toc', False) and ( not parents or any(parent_desc_list is not None for parent_desc_list in parents_descendants_list) ) ): # add self to parent's descendants for parent_desc_list in parents_descendants_list: if parent_desc_list is not None: parent_desc_list.items.append(unicode(block_key)) if BlockDepthTransformer.get_block_depth(block_structure, block_key) > self.nav_depth: children_descendants_list = parents_descendants_list else: block_nav_list = DescendantList() children_descendants_list = {block_nav_list} block_structure.set_transformer_block_field( block_key, self, self.BLOCK_NAVIGATION, block_nav_list.items ) block_structure.set_transformer_block_field( block_key, self, self.BLOCK_NAVIGATION_FOR_CHILDREN, children_descendants_list )
agpl-3.0
creativewild/ansible
v1/ansible/runner/lookup_plugins/nested.py
174
2285
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import ansible.utils as utils from ansible.utils import safe_eval import ansible.errors as errors def flatten(terms): ret = [] for term in terms: if isinstance(term, list): ret.extend(term) elif isinstance(term, tuple): ret.extend(term) else: ret.append(term) return ret def combine(a,b): results = [] for x in a: for y in b: results.append(flatten([x,y])) return results class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def __lookup_injects(self, terms, inject): results = [] for x in terms: intermediate = utils.listify_lookup_plugin_terms(x, self.basedir, inject) results.append(intermediate) return results def run(self, terms, inject=None, **kwargs): # this code is common with 'items.py' consider moving to utils if we need it again terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) terms = self.__lookup_injects(terms, inject) my_list = terms[:] my_list.reverse() result = [] if len(my_list) == 0: raise errors.AnsibleError("with_nested requires at least one element in the nested list") result = my_list.pop() while len(my_list) > 0: result2 = combine(result, my_list.pop()) result = result2 new_result = [] for x in result: new_result.append(flatten(x)) return new_result
gpl-3.0
fossoult/odoo
addons/hr_evaluation/__init__.py
432
1084
# -*- 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 hr_evaluation import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
zaxliu/deepnap
experiments/kdd-exps/experiment_DynaQNN_130_Feb10_2317.py
1
5180
# System built-in modules import time from datetime import datetime import sys import os from multiprocessing import Pool # Project dependency modules import pandas as pd pd.set_option('mode.chained_assignment', None) # block warnings due to DataFrame value assignment import lasagne # Project modules sys.path.append('../') from sleep_control.traffic_emulator import TrafficEmulator from sleep_control.traffic_server import TrafficServer from sleep_control.controller import QController, DummyController, NController from sleep_control.integration import Emulation from sleep_control.env_models import SJTUModel from rl.qtable import QAgent from rl.qnn_theano import QAgentNN from rl.mixin import PhiMixin, DynaMixin sys_stdout = sys.stdout log_prefix = '_'.join(['msg'] + os.path.basename(__file__).replace('.', '_').split('_')[1:5]) log_file_name = "{}_{}.log".format(log_prefix, sys.argv[1]) # Composite classes class Dyna_QAgentNN(DynaMixin, QAgentNN): def __init__(self, **kwargs): super(Dyna_QAgentNN, self).__init__(**kwargs) # Parameters # |- Data location = 'dmW' # |- Agent # |- QAgent actions = [(True, None), (False, 'serve_all')] gamma, alpha = 0.9, 0.9 # TD backup explore_strategy, epsilon = 'epsilon', 0.02 # exploration # |- QAgentNN # | - Phi # phi_length = 5 # dim_state = (1, phi_length, 3+2) # range_state_slice = [(0, 10), (0, 10), (0, 10), (0, 1), (0, 1)] # range_state = [[range_state_slice]*phi_length] # | - No Phi phi_length = 0 dim_state = (1, 1, 3) range_state = ((((0, 10), (0, 10), (0, 10)),),) # | - Other params momentum, learning_rate = 0.9, 0.01 # SGD num_buffer, memory_size, batch_size, update_period, freeze_period = 2, 200, 100, 4, 16 reward_scaling, reward_scaling_update, rs_period = 1, 'adaptive', 32 # reward scaling # |- Env model model_type, traffic_window_size = 'IPP', 50 stride, n_iter, adjust_offset = 2, 3, 1e-22 eval_period, eval_len = 4, 100 n_belief_bins, max_queue_len = 0, 20 Rs, Rw, Rf, Co, Cw = 1.0, -1.0, -10.0, -5.0, -0.5 traffic_params = (model_type, traffic_window_size, stride, n_iter, adjust_offset, eval_period, eval_len, n_belief_bins) queue_params = (max_queue_len,) beta = 0.5 # R = (1-beta)*ServiceReward + beta*Cost reward_params = (Rs, Rw, Rf, Co, Cw, beta) # |- DynaQ num_sim = 2 # |- Env # |- Time start_time = pd.to_datetime("2014-10-15 09:40:00") total_time = pd.Timedelta(days=7) time_step = pd.Timedelta(seconds=2) backoff_epochs = num_buffer*memory_size+phi_length head_datetime = start_time - time_step*backoff_epochs tail_datetime = head_datetime + total_time TOTAL_EPOCHS = int(total_time/time_step) # |- Reward rewarding = {'serve': Rs, 'wait': Rw, 'fail': Rf} # load from processed data session_df =pd.read_csv( filepath_or_buffer='../data/trace_{}.dat'.format(location), parse_dates=['startTime_datetime', 'endTime_datetime'] ) te = TrafficEmulator( session_df=session_df, time_step=time_step, head_datetime=head_datetime, tail_datetime=tail_datetime, rewarding=rewarding, verbose=2) ts = TrafficServer(cost=(Co, Cw), verbose=2) env_model = SJTUModel(traffic_params, queue_params, reward_params, 2) agent = Dyna_QAgentNN( env_model=env_model, num_sim=num_sim, dim_state=dim_state, range_state=range_state, f_build_net = None, batch_size=batch_size, learning_rate=learning_rate, momentum=momentum, reward_scaling=reward_scaling, reward_scaling_update=reward_scaling_update, rs_period=rs_period, update_period=update_period, freeze_period=freeze_period, memory_size=memory_size, num_buffer=num_buffer, # Below is QAgent params actions=actions, alpha=alpha, gamma=gamma, explore_strategy=explore_strategy, epsilon=epsilon, verbose=2) c = QController(agent=agent) emu = Emulation(te=te, ts=ts, c=c, beta=beta) # Heavyliftings t = time.time() sys.stdout = sys_stdout log_path = './log/' if os.path.isfile(log_path+log_file_name): print "Log file {} already exist. Experiment cancelled.".format(log_file_name) else: log_file = open(log_path+log_file_name,"w") print datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), print '{}%'.format(int(100.0*emu.epoch/TOTAL_EPOCHS)), print log_file_name time.sleep(1) sys.stdout = log_file while emu.epoch is not None and emu.epoch<TOTAL_EPOCHS: # log time print "Epoch {},".format(emu.epoch), left = emu.te.head_datetime + emu.te.epoch*emu.te.time_step right = left + emu.te.time_step print "{} - {}".format(left.strftime("%Y-%m-%d %H:%M:%S"), right.strftime("%Y-%m-%d %H:%M:%S")) emu.step() print if emu.epoch%(0.05*TOTAL_EPOCHS)==0: sys.stdout = sys_stdout print datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), print '{}%'.format(int(100.0*emu.epoch/TOTAL_EPOCHS)), print log_file_name time.sleep(1) sys.stdout = log_file sys.stdout = sys_stdout log_file.close() print print log_file_name, print '{:.3f} sec,'.format(time.time()-t), print '{:.3f} min'.format((time.time()-t)/60)
bsd-3-clause
ebeshero/Pittsburgh_Frankenstein
collateXPrep/svg_tester_collation.py
1
6475
from typing import Pattern from collatex import * from xml.dom import pulldom import string import re import json import glob regexWhitespace = re.compile(r'\s+') regexNonWhitespace = re.compile(r'\S+') regexEmptyTag = re.compile(r'/>$') regexBlankLine = re.compile(r'\n{2,}') regexLeadingBlankLine = re.compile(r'^\n') regexPageBreak = re.compile(r'<pb.+?/>') RE_MARKUP = re.compile(r'<.+?>') RE_AMP = re.compile(r'&amp;') RE_AND = re.compile(r'and') RE_mOrning = re.compile(r'mOrning') # Element types: xml, div, head, p, hi, pb, note, lg, l; comment() # Tags to ignore, with content to keep: xml, comment, anchor # Structural elements: div, p, lg, l # Inline elements (empty) retained in normalization: pb, milestone, xi:include # Inline and block elements (with content) retained in normalization: note, hi, head, ab # GIs fall into one three classes # 2017-05-21 ebb: Due to trouble with pulldom parsing XML comments, I have converted these to comment elements # 2017-05-22 ebb: I've set anchor elements with @xml:ids to be the indicators of collation "chunks" to process together ignore = ['xml'] inlineEmpty = ['milestone', 'anchor', 'include', 'pb'] inlineContent = ['hi'] blockElement = ['p', 'div', 'lg', 'l', 'head', 'comment', 'note', 'ab', 'cit', 'quote', 'bibl', 'header'] def normalizeSpace(inText): """Replaces all whitespace spans with single space characters""" if regexNonWhitespace.search(inText): return regexWhitespace.sub('\n', inText) else: return '' def extract(input_xml): """Process entire input XML document, firing on events""" # Start pulling; it continues automatically doc = pulldom.parseString(input_xml) output = '' for event, node in doc: # elements to ignore: xml if event == pulldom.START_ELEMENT and node.localName in ignore: continue # copy comments intact elif event == pulldom.COMMENT: doc.expandNode(node) output += node.toxml() # empty inline elements: pb, milestone elif event == pulldom.START_ELEMENT and node.localName in inlineEmpty: output += node.toxml() # non-empty inline elements: note, hi, head, l, lg, div, p, ab, elif event == pulldom.START_ELEMENT and node.localName in inlineContent: output += regexEmptyTag.sub('>', node.toxml()) elif event == pulldom.END_ELEMENT and node.localName in inlineContent: output += '</' + node.localName + '>' elif event == pulldom.START_ELEMENT and node.localName in blockElement: output += '\n<' + node.localName + '>\n' elif event == pulldom.END_ELEMENT and node.localName in blockElement: output += '\n</' + node.localName + '>' elif event == pulldom.CHARACTERS: output += normalizeSpace(node.data) else: continue return output # def normalize(inputText): # return regexPageBreak.sub('',inputText) def normalize(inputText): return RE_AMP.sub('and',\ RE_MARKUP.sub('', inputText)).lower() def processToken(inputText): return {"t": inputText + ' ', "n": normalize(inputText)} def processWitness(inputWitness, id): return {'id': id, 'tokens' : [processToken(token) for token in inputWitness]} fms_input = '''It was on a dreary night of November that I beheld the frame on whic my man completeed, and with an anxiety that almost amounted to agony I collected the instruments of life around me that I might infuse a spark of being into the lifeless thing that lay at my feet. ''' f1818_input = '''From this time Elizabeth Lavenza became my playfellow, and, as we grew older, my friend. She was docile and good tempered, yet gay and playful as a summer insect. Although she was lively and animated, her feelings were strong and deep, and her disposition uncommonly affectionate. No one could better enjoy liberty, yet no one could submit with more grace than she did to constraint and caprice.''' fThomas_input=''' ''' f1823_input = '''<p>The following morning the rain poured down in torrents, and thick mists hid the summits of the mountains. I rose early, but felt unusually melancholy. The rain depressed me; my old feelings recurred, and I was miserable. I knew how disappointed my father would be at this sudden change, and I wished to avoid him until I had recovered myself so far as to be enabled to conceal those feelings that overpowered me. I knew that they would remain that day at the inn; <pb xml:id="F1823_v1_218" n="199"/>and as I had ever inured myself to rain, moisture, and cold, I resolved to go alone to the summit of Montanvert. I remembered the effect that the view of the tremendous and ever-moving glacier had produced upon my mind when I first saw it. It had then filled me with a sublime ecstacy that gave wings to the soul, and allowed it to soar from the obscure world to light and joy. The sight of the awful and majestic in nature had indeed always the effect of solemnizing my mind, and causing me to forget the passing cares of life. I determined to go alone, for I was well acquainted with the path, and the presence of another would destroy the solitary grandeur of the scene.</p>''' f1831_input = ''' ''' fms_tokens = regexLeadingBlankLine.sub('',regexBlankLine.sub('\n', extract(fms_input))).split('\n') f1818_tokens = regexLeadingBlankLine.sub('',regexBlankLine.sub('\n', extract(f1818_input))).split('\n') fThomas_tokens = regexLeadingBlankLine.sub('',regexBlankLine.sub('\n', extract(fThomas_input))).split('\n') f1823_tokens = regexLeadingBlankLine.sub('',regexBlankLine.sub('\n', extract(f1823_input))).split('\n') f1831_input = regexLeadingBlankLine.sub('',regexBlankLine.sub('\n', extract(f1831_input))).split('\n') f1818_tokenlist = processWitness(f1818_tokens, 'f1818') f1823_tokenlist = processWitness(f1823_tokens, 'f1823') collation_input = {"witnesses": [f1818_tokenlist, f1823_tokenlist]} table = collate(collation_input, segmentation=True, output="svg") outputFile = open('C10-NormalizedTokens/C-10portion' + '.svg', 'w') print(table, file=outputFile) # table = collate(collation_input, segmentation=True, layout='vertical') # test = normalize(f1818_input) # print(test, table) # print(f1818_tokenlist)
agpl-3.0
simartin/servo
components/script/dom/bindings/codegen/ply/ply/lex.py
4
35150
# ----------------------------------------------------------------------------- # ply: lex.py # # Copyright (C) 2001-2020 # David M. Beazley (Dabeaz LLC) # All rights reserved. # # Latest version: https://github.com/dabeaz/ply # # 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 David Beazley or Dabeaz LLC may be used to # endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ----------------------------------------------------------------------------- import re import sys import types import copy import os import inspect # This tuple contains acceptable string types StringTypes = (str, bytes) # This regular expression is used to match valid token names _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$') # Exception thrown when invalid token encountered and no default error # handler is defined. class LexError(Exception): def __init__(self, message, s): self.args = (message,) self.text = s # Token class. This class is used to represent the tokens produced. class LexToken(object): def __repr__(self): return f'LexToken({self.type},{self.value!r},{self.lineno},{self.lexpos})' # This object is a stand-in for a logging object created by the # logging module. class PlyLogger(object): def __init__(self, f): self.f = f def critical(self, msg, *args, **kwargs): self.f.write((msg % args) + '\n') def warning(self, msg, *args, **kwargs): self.f.write('WARNING: ' + (msg % args) + '\n') def error(self, msg, *args, **kwargs): self.f.write('ERROR: ' + (msg % args) + '\n') info = critical debug = critical # ----------------------------------------------------------------------------- # === Lexing Engine === # # The following Lexer class implements the lexer runtime. There are only # a few public methods and attributes: # # input() - Store a new string in the lexer # token() - Get the next token # clone() - Clone the lexer # # lineno - Current line number # lexpos - Current position in the input string # ----------------------------------------------------------------------------- class Lexer: def __init__(self): self.lexre = None # Master regular expression. This is a list of # tuples (re, findex) where re is a compiled # regular expression and findex is a list # mapping regex group numbers to rules self.lexretext = None # Current regular expression strings self.lexstatere = {} # Dictionary mapping lexer states to master regexs self.lexstateretext = {} # Dictionary mapping lexer states to regex strings self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names self.lexstate = 'INITIAL' # Current lexer state self.lexstatestack = [] # Stack of lexer states self.lexstateinfo = None # State information self.lexstateignore = {} # Dictionary of ignored characters for each state self.lexstateerrorf = {} # Dictionary of error functions for each state self.lexstateeoff = {} # Dictionary of eof functions for each state self.lexreflags = 0 # Optional re compile flags self.lexdata = None # Actual input data (as a string) self.lexpos = 0 # Current position in input text self.lexlen = 0 # Length of the input text self.lexerrorf = None # Error rule (if any) self.lexeoff = None # EOF rule (if any) self.lextokens = None # List of valid tokens self.lexignore = '' # Ignored characters self.lexliterals = '' # Literal characters that can be passed through self.lexmodule = None # Module self.lineno = 1 # Current line number def clone(self, object=None): c = copy.copy(self) # If the object parameter has been supplied, it means we are attaching the # lexer to a new object. In this case, we have to rebind all methods in # the lexstatere and lexstateerrorf tables. if object: newtab = {} for key, ritem in self.lexstatere.items(): newre = [] for cre, findex in ritem: newfindex = [] for f in findex: if not f or not f[0]: newfindex.append(f) continue newfindex.append((getattr(object, f[0].__name__), f[1])) newre.append((cre, newfindex)) newtab[key] = newre c.lexstatere = newtab c.lexstateerrorf = {} for key, ef in self.lexstateerrorf.items(): c.lexstateerrorf[key] = getattr(object, ef.__name__) c.lexmodule = object return c # ------------------------------------------------------------ # input() - Push a new string into the lexer # ------------------------------------------------------------ def input(self, s): self.lexdata = s self.lexpos = 0 self.lexlen = len(s) # ------------------------------------------------------------ # begin() - Changes the lexing state # ------------------------------------------------------------ def begin(self, state): if state not in self.lexstatere: raise ValueError(f'Undefined state {state!r}') self.lexre = self.lexstatere[state] self.lexretext = self.lexstateretext[state] self.lexignore = self.lexstateignore.get(state, '') self.lexerrorf = self.lexstateerrorf.get(state, None) self.lexeoff = self.lexstateeoff.get(state, None) self.lexstate = state # ------------------------------------------------------------ # push_state() - Changes the lexing state and saves old on stack # ------------------------------------------------------------ def push_state(self, state): self.lexstatestack.append(self.lexstate) self.begin(state) # ------------------------------------------------------------ # pop_state() - Restores the previous state # ------------------------------------------------------------ def pop_state(self): self.begin(self.lexstatestack.pop()) # ------------------------------------------------------------ # current_state() - Returns the current lexing state # ------------------------------------------------------------ def current_state(self): return self.lexstate # ------------------------------------------------------------ # skip() - Skip ahead n characters # ------------------------------------------------------------ def skip(self, n): self.lexpos += n # ------------------------------------------------------------ # token() - Return the next token from the Lexer # # Note: This function has been carefully implemented to be as fast # as possible. Don't make changes unless you really know what # you are doing # ------------------------------------------------------------ def token(self): # Make local copies of frequently referenced attributes lexpos = self.lexpos lexlen = self.lexlen lexignore = self.lexignore lexdata = self.lexdata while lexpos < lexlen: # This code provides some short-circuit code for whitespace, tabs, and other ignored characters if lexdata[lexpos] in lexignore: lexpos += 1 continue # Look for a regular expression match for lexre, lexindexfunc in self.lexre: m = lexre.match(lexdata, lexpos) if not m: continue # Create a token for return tok = LexToken() tok.value = m.group() tok.lineno = self.lineno tok.lexpos = lexpos i = m.lastindex func, tok.type = lexindexfunc[i] if not func: # If no token type was set, it's an ignored token if tok.type: self.lexpos = m.end() return tok else: lexpos = m.end() break lexpos = m.end() # If token is processed by a function, call it tok.lexer = self # Set additional attributes useful in token rules self.lexmatch = m self.lexpos = lexpos newtok = func(tok) del tok.lexer del self.lexmatch # Every function must return a token, if nothing, we just move to next token if not newtok: lexpos = self.lexpos # This is here in case user has updated lexpos. lexignore = self.lexignore # This is here in case there was a state change break return newtok else: # No match, see if in literals if lexdata[lexpos] in self.lexliterals: tok = LexToken() tok.value = lexdata[lexpos] tok.lineno = self.lineno tok.type = tok.value tok.lexpos = lexpos self.lexpos = lexpos + 1 return tok # No match. Call t_error() if defined. if self.lexerrorf: tok = LexToken() tok.value = self.lexdata[lexpos:] tok.lineno = self.lineno tok.type = 'error' tok.lexer = self tok.lexpos = lexpos self.lexpos = lexpos newtok = self.lexerrorf(tok) if lexpos == self.lexpos: # Error method didn't change text position at all. This is an error. raise LexError(f"Scanning error. Illegal character {lexdata[lexpos]!r}", lexdata[lexpos:]) lexpos = self.lexpos if not newtok: continue return newtok self.lexpos = lexpos raise LexError(f"Illegal character {lexdata[lexpos]!r} at index {lexpos}", lexdata[lexpos:]) if self.lexeoff: tok = LexToken() tok.type = 'eof' tok.value = '' tok.lineno = self.lineno tok.lexpos = lexpos tok.lexer = self self.lexpos = lexpos newtok = self.lexeoff(tok) return newtok self.lexpos = lexpos + 1 if self.lexdata is None: raise RuntimeError('No input string given with input()') return None # Iterator interface def __iter__(self): return self def __next__(self): t = self.token() if t is None: raise StopIteration return t # ----------------------------------------------------------------------------- # ==== Lex Builder === # # The functions and classes below are used to collect lexing information # and build a Lexer object from it. # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # _get_regex(func) # # Returns the regular expression assigned to a function either as a doc string # or as a .regex attribute attached by the @TOKEN decorator. # ----------------------------------------------------------------------------- def _get_regex(func): return getattr(func, 'regex', func.__doc__) # ----------------------------------------------------------------------------- # get_caller_module_dict() # # This function returns a dictionary containing all of the symbols defined within # a caller further down the call stack. This is used to get the environment # associated with the yacc() call if none was provided. # ----------------------------------------------------------------------------- def get_caller_module_dict(levels): f = sys._getframe(levels) return { **f.f_globals, **f.f_locals } # ----------------------------------------------------------------------------- # _form_master_re() # # This function takes a list of all of the regex components and attempts to # form the master regular expression. Given limitations in the Python re # module, it may be necessary to break the master regex into separate expressions. # ----------------------------------------------------------------------------- def _form_master_re(relist, reflags, ldict, toknames): if not relist: return [], [], [] regex = '|'.join(relist) try: lexre = re.compile(regex, reflags) # Build the index to function map for the matching engine lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1) lexindexnames = lexindexfunc[:] for f, i in lexre.groupindex.items(): handle = ldict.get(f, None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle, toknames[f]) lexindexnames[i] = f elif handle is not None: lexindexnames[i] = f if f.find('ignore_') > 0: lexindexfunc[i] = (None, None) else: lexindexfunc[i] = (None, toknames[f]) return [(lexre, lexindexfunc)], [regex], [lexindexnames] except Exception: m = (len(relist) // 2) + 1 llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames) rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames) return (llist+rlist), (lre+rre), (lnames+rnames) # ----------------------------------------------------------------------------- # def _statetoken(s,names) # # Given a declaration name s of the form "t_" and a dictionary whose keys are # state names, this function returns a tuple (states,tokenname) where states # is a tuple of state names and tokenname is the name of the token. For example, # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') # ----------------------------------------------------------------------------- def _statetoken(s, names): parts = s.split('_') for i, part in enumerate(parts[1:], 1): if part not in names and part != 'ANY': break if i > 1: states = tuple(parts[1:i]) else: states = ('INITIAL',) if 'ANY' in states: states = tuple(names) tokenname = '_'.join(parts[i:]) return (states, tokenname) # ----------------------------------------------------------------------------- # LexerReflect() # # This class represents information needed to build a lexer as extracted from a # user's input file. # ----------------------------------------------------------------------------- class LexerReflect(object): def __init__(self, ldict, log=None, reflags=0): self.ldict = ldict self.error_func = None self.tokens = [] self.reflags = reflags self.stateinfo = {'INITIAL': 'inclusive'} self.modules = set() self.error = False self.log = PlyLogger(sys.stderr) if log is None else log # Get all of the basic information def get_all(self): self.get_tokens() self.get_literals() self.get_states() self.get_rules() # Validate all of the information def validate_all(self): self.validate_tokens() self.validate_literals() self.validate_rules() return self.error # Get the tokens map def get_tokens(self): tokens = self.ldict.get('tokens', None) if not tokens: self.log.error('No token list is defined') self.error = True return if not isinstance(tokens, (list, tuple)): self.log.error('tokens must be a list or tuple') self.error = True return if not tokens: self.log.error('tokens is empty') self.error = True return self.tokens = tokens # Validate the tokens def validate_tokens(self): terminals = {} for n in self.tokens: if not _is_identifier.match(n): self.log.error(f"Bad token name {n!r}") self.error = True if n in terminals: self.log.warning(f"Token {n!r} multiply defined") terminals[n] = 1 # Get the literals specifier def get_literals(self): self.literals = self.ldict.get('literals', '') if not self.literals: self.literals = '' # Validate literals def validate_literals(self): try: for c in self.literals: if not isinstance(c, StringTypes) or len(c) > 1: self.log.error(f'Invalid literal {c!r}. Must be a single character') self.error = True except TypeError: self.log.error('Invalid literals specification. literals must be a sequence of characters') self.error = True def get_states(self): self.states = self.ldict.get('states', None) # Build statemap if self.states: if not isinstance(self.states, (tuple, list)): self.log.error('states must be defined as a tuple or list') self.error = True else: for s in self.states: if not isinstance(s, tuple) or len(s) != 2: self.log.error("Invalid state specifier %r. Must be a tuple (statename,'exclusive|inclusive')", s) self.error = True continue name, statetype = s if not isinstance(name, StringTypes): self.log.error('State name %r must be a string', name) self.error = True continue if not (statetype == 'inclusive' or statetype == 'exclusive'): self.log.error("State type for state %r must be 'inclusive' or 'exclusive'", name) self.error = True continue if name in self.stateinfo: self.log.error("State %r already defined", name) self.error = True continue self.stateinfo[name] = statetype # Get all of the symbols with a t_ prefix and sort them into various # categories (functions, strings, error functions, and ignore characters) def get_rules(self): tsymbols = [f for f in self.ldict if f[:2] == 't_'] # Now build up a list of functions and a list of strings self.toknames = {} # Mapping of symbols to token names self.funcsym = {} # Symbols defined as functions self.strsym = {} # Symbols defined as strings self.ignore = {} # Ignore strings by state self.errorf = {} # Error functions by state self.eoff = {} # EOF functions by state for s in self.stateinfo: self.funcsym[s] = [] self.strsym[s] = [] if len(tsymbols) == 0: self.log.error('No rules of the form t_rulename are defined') self.error = True return for f in tsymbols: t = self.ldict[f] states, tokname = _statetoken(f, self.stateinfo) self.toknames[f] = tokname if hasattr(t, '__call__'): if tokname == 'error': for s in states: self.errorf[s] = t elif tokname == 'eof': for s in states: self.eoff[s] = t elif tokname == 'ignore': line = t.__code__.co_firstlineno file = t.__code__.co_filename self.log.error("%s:%d: Rule %r must be defined as a string", file, line, t.__name__) self.error = True else: for s in states: self.funcsym[s].append((f, t)) elif isinstance(t, StringTypes): if tokname == 'ignore': for s in states: self.ignore[s] = t if '\\' in t: self.log.warning("%s contains a literal backslash '\\'", f) elif tokname == 'error': self.log.error("Rule %r must be defined as a function", f) self.error = True else: for s in states: self.strsym[s].append((f, t)) else: self.log.error('%s not defined as a function or string', f) self.error = True # Sort the functions by line number for f in self.funcsym.values(): f.sort(key=lambda x: x[1].__code__.co_firstlineno) # Sort the strings by regular expression length for s in self.strsym.values(): s.sort(key=lambda x: len(x[1]), reverse=True) # Validate all of the t_rules collected def validate_rules(self): for state in self.stateinfo: # Validate all rules defined by functions for fname, f in self.funcsym[state]: line = f.__code__.co_firstlineno file = f.__code__.co_filename module = inspect.getmodule(f) self.modules.add(module) tokname = self.toknames[fname] if isinstance(f, types.MethodType): reqargs = 2 else: reqargs = 1 nargs = f.__code__.co_argcount if nargs > reqargs: self.log.error("%s:%d: Rule %r has too many arguments", file, line, f.__name__) self.error = True continue if nargs < reqargs: self.log.error("%s:%d: Rule %r requires an argument", file, line, f.__name__) self.error = True continue if not _get_regex(f): self.log.error("%s:%d: No regular expression defined for rule %r", file, line, f.__name__) self.error = True continue try: c = re.compile('(?P<%s>%s)' % (fname, _get_regex(f)), self.reflags) if c.match(''): self.log.error("%s:%d: Regular expression for rule %r matches empty string", file, line, f.__name__) self.error = True except re.error as e: self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e) if '#' in _get_regex(f): self.log.error("%s:%d. Make sure '#' in rule %r is escaped with '\\#'", file, line, f.__name__) self.error = True # Validate all rules defined by strings for name, r in self.strsym[state]: tokname = self.toknames[name] if tokname == 'error': self.log.error("Rule %r must be defined as a function", name) self.error = True continue if tokname not in self.tokens and tokname.find('ignore_') < 0: self.log.error("Rule %r defined for an unspecified token %s", name, tokname) self.error = True continue try: c = re.compile('(?P<%s>%s)' % (name, r), self.reflags) if (c.match('')): self.log.error("Regular expression for rule %r matches empty string", name) self.error = True except re.error as e: self.log.error("Invalid regular expression for rule %r. %s", name, e) if '#' in r: self.log.error("Make sure '#' in rule %r is escaped with '\\#'", name) self.error = True if not self.funcsym[state] and not self.strsym[state]: self.log.error("No rules defined for state %r", state) self.error = True # Validate the error function efunc = self.errorf.get(state, None) if efunc: f = efunc line = f.__code__.co_firstlineno file = f.__code__.co_filename module = inspect.getmodule(f) self.modules.add(module) if isinstance(f, types.MethodType): reqargs = 2 else: reqargs = 1 nargs = f.__code__.co_argcount if nargs > reqargs: self.log.error("%s:%d: Rule %r has too many arguments", file, line, f.__name__) self.error = True if nargs < reqargs: self.log.error("%s:%d: Rule %r requires an argument", file, line, f.__name__) self.error = True for module in self.modules: self.validate_module(module) # ----------------------------------------------------------------------------- # validate_module() # # This checks to see if there are duplicated t_rulename() functions or strings # in the parser input file. This is done using a simple regular expression # match on each line in the source code of the given module. # ----------------------------------------------------------------------------- def validate_module(self, module): try: lines, linen = inspect.getsourcelines(module) except IOError: return fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = {} linen += 1 for line in lines: m = fre.match(line) if not m: m = sre.match(line) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: filename = inspect.getsourcefile(module) self.log.error('%s:%d: Rule %s redefined. Previously defined on line %d', filename, linen, name, prev) self.error = True linen += 1 # ----------------------------------------------------------------------------- # lex(module) # # Build all of the regular expression rules from definitions in the supplied module # ----------------------------------------------------------------------------- def lex(*, module=None, object=None, debug=False, reflags=int(re.VERBOSE), debuglog=None, errorlog=None): global lexer ldict = None stateinfo = {'INITIAL': 'inclusive'} lexobj = Lexer() global token, input if errorlog is None: errorlog = PlyLogger(sys.stderr) if debug: if debuglog is None: debuglog = PlyLogger(sys.stderr) # Get the module dictionary used for the lexer if object: module = object # Get the module dictionary used for the parser if module: _items = [(k, getattr(module, k)) for k in dir(module)] ldict = dict(_items) # If no __file__ attribute is available, try to obtain it from the __module__ instead if '__file__' not in ldict: ldict['__file__'] = sys.modules[ldict['__module__']].__file__ else: ldict = get_caller_module_dict(2) # Collect parser information from the dictionary linfo = LexerReflect(ldict, log=errorlog, reflags=reflags) linfo.get_all() if linfo.validate_all(): raise SyntaxError("Can't build lexer") # Dump some basic debugging information if debug: debuglog.info('lex: tokens = %r', linfo.tokens) debuglog.info('lex: literals = %r', linfo.literals) debuglog.info('lex: states = %r', linfo.stateinfo) # Build a dictionary of valid token names lexobj.lextokens = set() for n in linfo.tokens: lexobj.lextokens.add(n) # Get literals specification if isinstance(linfo.literals, (list, tuple)): lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals) else: lexobj.lexliterals = linfo.literals lexobj.lextokens_all = lexobj.lextokens | set(lexobj.lexliterals) # Get the stateinfo dictionary stateinfo = linfo.stateinfo regexs = {} # Build the master regular expressions for state in stateinfo: regex_list = [] # Add rules defined by functions first for fname, f in linfo.funcsym[state]: regex_list.append('(?P<%s>%s)' % (fname, _get_regex(f))) if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", fname, _get_regex(f), state) # Now add all of the simple rules for name, r in linfo.strsym[state]: regex_list.append('(?P<%s>%s)' % (name, r)) if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", name, r, state) regexs[state] = regex_list # Build the master regular expressions if debug: debuglog.info('lex: ==== MASTER REGEXS FOLLOW ====') for state in regexs: lexre, re_text, re_names = _form_master_re(regexs[state], reflags, ldict, linfo.toknames) lexobj.lexstatere[state] = lexre lexobj.lexstateretext[state] = re_text lexobj.lexstaterenames[state] = re_names if debug: for i, text in enumerate(re_text): debuglog.info("lex: state '%s' : regex[%d] = '%s'", state, i, text) # For inclusive states, we need to add the regular expressions from the INITIAL state for state, stype in stateinfo.items(): if state != 'INITIAL' and stype == 'inclusive': lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL']) lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL']) lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL']) lexobj.lexstateinfo = stateinfo lexobj.lexre = lexobj.lexstatere['INITIAL'] lexobj.lexretext = lexobj.lexstateretext['INITIAL'] lexobj.lexreflags = reflags # Set up ignore variables lexobj.lexstateignore = linfo.ignore lexobj.lexignore = lexobj.lexstateignore.get('INITIAL', '') # Set up error functions lexobj.lexstateerrorf = linfo.errorf lexobj.lexerrorf = linfo.errorf.get('INITIAL', None) if not lexobj.lexerrorf: errorlog.warning('No t_error rule is defined') # Set up eof functions lexobj.lexstateeoff = linfo.eoff lexobj.lexeoff = linfo.eoff.get('INITIAL', None) # Check state information for ignore and error rules for s, stype in stateinfo.items(): if stype == 'exclusive': if s not in linfo.errorf: errorlog.warning("No error rule is defined for exclusive state %r", s) if s not in linfo.ignore and lexobj.lexignore: errorlog.warning("No ignore rule is defined for exclusive state %r", s) elif stype == 'inclusive': if s not in linfo.errorf: linfo.errorf[s] = linfo.errorf.get('INITIAL', None) if s not in linfo.ignore: linfo.ignore[s] = linfo.ignore.get('INITIAL', '') # Create global versions of the token() and input() functions token = lexobj.token input = lexobj.input lexer = lexobj return lexobj # ----------------------------------------------------------------------------- # runmain() # # This runs the lexer as a main program # ----------------------------------------------------------------------------- def runmain(lexer=None, data=None): if not data: try: filename = sys.argv[1] with open(filename) as f: data = f.read() except IndexError: sys.stdout.write('Reading from standard input (type EOF to end):\n') data = sys.stdin.read() if lexer: _input = lexer.input else: _input = input _input(data) if lexer: _token = lexer.token else: _token = token while True: tok = _token() if not tok: break sys.stdout.write(f'({tok.type},{tok.value!r},{tok.lineno},{tok.lexpos})\n') # ----------------------------------------------------------------------------- # @TOKEN(regex) # # This decorator function can be used to set the regex expression on a function # when its docstring might need to be set in an alternative way # ----------------------------------------------------------------------------- def TOKEN(r): def set_regex(f): if hasattr(r, '__call__'): f.regex = _get_regex(r) else: f.regex = r return f return set_regex
mpl-2.0
binhqnguyen/lena
.waf-1.7.13-5a064c2686fe54de4e11018d22148cfc/waflib/Tools/kde4.py
275
2007
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,sys,re from waflib import Options,TaskGen,Task,Utils from waflib.TaskGen import feature,after_method @feature('msgfmt') def apply_msgfmt(self): for lang in self.to_list(self.langs): node=self.path.find_resource(lang+'.po') task=self.create_task('msgfmt',node,node.change_ext('.mo')) langname=lang.split('/') langname=langname[-1] inst=getattr(self,'install_path','${KDE4_LOCALE_INSTALL_DIR}') self.bld.install_as(inst+os.sep+langname+os.sep+'LC_MESSAGES'+os.sep+getattr(self,'appname','set_your_appname')+'.mo',task.outputs[0],chmod=getattr(self,'chmod',Utils.O644)) class msgfmt(Task.Task): color='BLUE' run_str='${MSGFMT} ${SRC} -o ${TGT}' def configure(self): kdeconfig=self.find_program('kde4-config') prefix=self.cmd_and_log('%s --prefix'%kdeconfig).strip() fname='%s/share/apps/cmake/modules/KDELibsDependencies.cmake'%prefix try:os.stat(fname) except OSError: fname='%s/share/kde4/apps/cmake/modules/KDELibsDependencies.cmake'%prefix try:os.stat(fname) except OSError:self.fatal('could not open %s'%fname) try: txt=Utils.readf(fname) except(OSError,IOError): self.fatal('could not read %s'%fname) txt=txt.replace('\\\n','\n') fu=re.compile('#(.*)\n') txt=fu.sub('',txt) setregexp=re.compile('([sS][eE][tT]\s*\()\s*([^\s]+)\s+\"([^"]+)\"\)') found=setregexp.findall(txt) for(_,key,val)in found: self.env[key]=val self.env['LIB_KDECORE']=['kdecore'] self.env['LIB_KDEUI']=['kdeui'] self.env['LIB_KIO']=['kio'] self.env['LIB_KHTML']=['khtml'] self.env['LIB_KPARTS']=['kparts'] self.env['LIBPATH_KDECORE']=[os.path.join(self.env.KDE4_LIB_INSTALL_DIR,'kde4','devel'),self.env.KDE4_LIB_INSTALL_DIR] self.env['INCLUDES_KDECORE']=[self.env['KDE4_INCLUDE_INSTALL_DIR']] self.env.append_value('INCLUDES_KDECORE',[self.env['KDE4_INCLUDE_INSTALL_DIR']+os.sep+'KDE']) self.find_program('msgfmt',var='MSGFMT')
gpl-2.0
Imaginashion/cloud-vision
.fr-d0BNfn/django-jquery-file-upload/venv/lib/python3.5/site-packages/django/conf/locale/de_CH/formats.py
504
1445
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date from __future__ import unicode_literals DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' ] # these are the separators for non-monetary numbers. For monetary numbers, # the DECIMAL_SEPARATOR is a . (decimal point) and the THOUSAND_SEPARATOR is a # ' (single quote). # For details, please refer to http://www.bk.admin.ch/dokumentation/sprachen/04915/05016/index.html?lang=de # (in German) and the documentation DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
mit
mcus/SickRage
lib/feedparser/namespaces/dc.py
43
4477
# Support for the Dublin Core metadata extensions # Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is a part of feedparser. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. from __future__ import absolute_import, unicode_literals from ..util import FeedParserDict from ..datetimes import _parse_date class Namespace(object): supported_namespaces = { 'http://purl.org/dc/elements/1.1/': 'dc', 'http://purl.org/dc/terms/': 'dcterms', } def _end_dc_author(self): self._end_author() def _end_dc_creator(self): self._end_author() def _end_dc_date(self): self._end_updated() def _end_dc_description(self): self._end_description() def _end_dc_language(self): self._end_language() def _end_dc_publisher(self): self._end_webmaster() def _end_dc_rights(self): self._end_rights() def _end_dc_subject(self): self._end_category() def _end_dc_title(self): self._end_title() def _end_dcterms_created(self): self._end_created() def _end_dcterms_issued(self): self._end_published() def _end_dcterms_modified(self): self._end_updated() def _start_dc_author(self, attrsD): self._start_author(attrsD) def _start_dc_creator(self, attrsD): self._start_author(attrsD) def _start_dc_date(self, attrsD): self._start_updated(attrsD) def _start_dc_description(self, attrsD): self._start_description(attrsD) def _start_dc_language(self, attrsD): self._start_language(attrsD) def _start_dc_publisher(self, attrsD): self._start_webmaster(attrsD) def _start_dc_rights(self, attrsD): self._start_rights(attrsD) def _start_dc_subject(self, attrsD): self._start_category(attrsD) def _start_dc_title(self, attrsD): self._start_title(attrsD) def _start_dcterms_created(self, attrsD): self._start_created(attrsD) def _start_dcterms_issued(self, attrsD): self._start_published(attrsD) def _start_dcterms_modified(self, attrsD): self._start_updated(attrsD) def _start_dcterms_valid(self, attrsD): self.push('validity', 1) def _end_dcterms_valid(self): for validity_detail in self.pop('validity').split(';'): if '=' in validity_detail: key, value = validity_detail.split('=', 1) if key == 'start': self._save('validity_start', value, overwrite=True) self._save('validity_start_parsed', _parse_date(value), overwrite=True) elif key == 'end': self._save('validity_end', value, overwrite=True) self._save('validity_end_parsed', _parse_date(value), overwrite=True) def _start_dc_contributor(self, attrsD): self.incontributor = 1 context = self._getContext() context.setdefault('contributors', []) context['contributors'].append(FeedParserDict()) self.push('name', 0) def _end_dc_contributor(self): self._end_name() self.incontributor = 0
gpl-3.0
sqlalchemy/sqlalchemy
examples/asyncio/basic.py
3
2210
"""Illustrates the asyncio engine / connection interface. In this example, we have an async engine created by :func:`_engine.create_async_engine`. We then use it using await within a coroutine. """ import asyncio from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import Table from sqlalchemy.ext.asyncio import create_async_engine meta = MetaData() t1 = Table( "t1", meta, Column("id", Integer, primary_key=True), Column("name", String) ) async def async_main(): # engine is an instance of AsyncEngine engine = create_async_engine( "postgresql+asyncpg://scott:tiger@localhost/test", echo=True, ) # conn is an instance of AsyncConnection async with engine.begin() as conn: # to support SQLAlchemy DDL methods as well as legacy functions, the # AsyncConnection.run_sync() awaitable method will pass a "sync" # version of the AsyncConnection object to any synchronous method, # where synchronous IO calls will be transparently translated for # await. await conn.run_sync(meta.drop_all) await conn.run_sync(meta.create_all) # for normal statement execution, a traditional "await execute()" # pattern is used. await conn.execute( t1.insert(), [{"name": "some name 1"}, {"name": "some name 2"}] ) async with engine.connect() as conn: # the default result object is the # sqlalchemy.engine.Result object result = await conn.execute(t1.select()) # the results are buffered so no await call is necessary # for this case. print(result.fetchall()) # for a streaming result that buffers only segments of the # result at time, the AsyncConnection.stream() method is used. # this returns a sqlalchemy.ext.asyncio.AsyncResult object. async_result = await conn.stream(t1.select()) # this object supports async iteration and awaitable # versions of methods like .all(), fetchmany(), etc. async for row in async_result: print(row) asyncio.run(async_main())
mit
randynobx/ansible
lib/ansible/modules/cloud/openstack/os_zone.py
29
7527
#!/usr/bin/python # Copyright (c) 2016 Hewlett-Packard Enterprise # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software 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 software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_zone short_description: Manage OpenStack DNS zones extends_documentation_fragment: openstack version_added: "2.2" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" description: - Manage OpenStack DNS zones. Zones can be created, deleted or updated. Only the I(email), I(description), I(ttl) and I(masters) values can be updated. options: name: description: - Zone name required: true zone_type: description: - Zone type choices: [primary, secondary] default: None email: description: - Email of the zone owner (only applies if zone_type is primary) required: false description: description: - Zone description required: false default: None ttl: description: - TTL (Time To Live) value in seconds required: false default: None masters: description: - Master nameservers (only applies if zone_type is secondary) required: false default: None state: description: - Should the resource be present or absent. choices: [present, absent] default: present availability_zone: description: - Ignored. Present for backwards compatibility required: false requirements: - "python >= 2.6" - "shade" ''' EXAMPLES = ''' # Create a zone named "example.net" - os_zone: cloud: mycloud state: present name: example.net. zone_type: primary email: test@example.net description: Test zone ttl: 3600 # Update the TTL on existing "example.net." zone - os_zone: cloud: mycloud state: present name: example.net. ttl: 7200 # Delete zone named "example.net." - os_zone: cloud: mycloud state: absent name: example.net. ''' RETURN = ''' zone: description: Dictionary describing the zone. returned: On success when I(state) is 'present'. type: complex contains: id: description: Unique zone ID type: string sample: "c1c530a3-3619-46f3-b0f6-236927b2618c" name: description: Zone name type: string sample: "example.net." type: description: Zone type type: string sample: "PRIMARY" email: description: Zone owner email type: string sample: "test@example.net" description: description: Zone description type: string sample: "Test description" ttl: description: Zone TTL value type: int sample: 3600 masters: description: Zone master nameservers type: list sample: [] ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False from distutils.version import StrictVersion def _system_state_change(state, email, description, ttl, masters, zone): if state == 'present': if not zone: return True if email is not None and zone.email != email: return True if description is not None and zone.description != description: return True if ttl is not None and zone.ttl != ttl: return True if masters is not None and zone.masters != masters: return True if state == 'absent' and zone: return True return False def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), zone_type=dict(required=False, choice=['primary', 'secondary']), email=dict(required=False, default=None), description=dict(required=False, default=None), ttl=dict(required=False, default=None, type='int'), masters=dict(required=False, default=None, type='list'), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') if StrictVersion(shade.__version__) < StrictVersion('1.8.0'): module.fail_json(msg="To utilize this module, the installed version of" "the shade library MUST be >=1.8.0") name = module.params.get('name') state = module.params.get('state') try: cloud = shade.openstack_cloud(**module.params) zone = cloud.get_zone(name) if state == 'present': zone_type = module.params.get('zone_type') email = module.params.get('email') description = module.params.get('description') ttl = module.params.get('ttl') masters = module.params.get('masters') if module.check_mode: module.exit_json(changed=_system_state_change(state, email, description, ttl, masters, zone)) if zone is None: zone = cloud.create_zone( name=name, zone_type=zone_type, email=email, description=description, ttl=ttl, masters=masters) changed = True else: if masters is None: masters = [] pre_update_zone = zone changed = _system_state_change(state, email, description, ttl, masters, pre_update_zone) if changed: zone = cloud.update_zone( name, email=email, description=description, ttl=ttl, masters=masters) module.exit_json(changed=changed, zone=zone) elif state == 'absent': if module.check_mode: module.exit_json(changed=_system_state_change(state, None, None, None, None, zone)) if zone is None: changed=False else: cloud.delete_zone(name) changed=True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0
gadomski/cpd
vendor/googletest-release-1.10.0/googletest/scripts/common.py
1180
2919
# Copyright 2013 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. """Shared utilities for writing scripts for Google Test/Mock.""" __author__ = 'wan@google.com (Zhanyong Wan)' import os import re # Matches the line from 'svn info .' output that describes what SVN # path the current local directory corresponds to. For example, in # a googletest SVN workspace's trunk/test directory, the output will be: # # URL: https://googletest.googlecode.com/svn/trunk/test _SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)') def GetCommandOutput(command): """Runs the shell command and returns its stdout as a list of lines.""" f = os.popen(command, 'r') lines = [line.strip() for line in f.readlines()] f.close() return lines def GetSvnInfo(): """Returns the project name and the current SVN workspace's root path.""" for line in GetCommandOutput('svn info .'): m = _SVN_INFO_URL_RE.match(line) if m: project = m.group(1) # googletest or googlemock rel_path = m.group(2) root = os.path.realpath(rel_path.count('/') * '../') return project, root return None, None def GetSvnTrunk(): """Returns the current SVN workspace's trunk root path.""" _, root = GetSvnInfo() return root + '/trunk' if root else None def IsInGTestSvn(): project, _ = GetSvnInfo() return project == 'googletest' def IsInGMockSvn(): project, _ = GetSvnInfo() return project == 'googlemock'
gpl-2.0
tylertian/Openstack
openstack F/horizon/horizon/tests/test_data/exceptions.py
3
2423
# Copyright 2012 Nebula, 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. import glanceclient.exc as glance_exceptions from keystoneclient import exceptions as keystone_exceptions from novaclient import exceptions as nova_exceptions from quantumclient.common import exceptions as quantum_exceptions from swiftclient import client as swift_exceptions from cinderclient import exceptions as cinder_exceptions from .utils import TestDataContainer def create_stubbed_exception(cls, status_code=500): msg = "Expected failure." def fake_init_exception(self, code, message): self.code = code self.message = message def fake_str(self): return str(self.message) def fake_unicode(self): return unicode(self.message) cls.__init__ = fake_init_exception cls.__str__ = fake_str cls.__unicode__ = fake_unicode cls.silence_logging = True return cls(status_code, msg) def data(TEST): TEST.exceptions = TestDataContainer() unauth = keystone_exceptions.Unauthorized TEST.exceptions.keystone_unauthorized = create_stubbed_exception(unauth) keystone_exception = keystone_exceptions.ClientException TEST.exceptions.keystone = create_stubbed_exception(keystone_exception) nova_exception = nova_exceptions.ClientException TEST.exceptions.nova = create_stubbed_exception(nova_exception) glance_exception = glance_exceptions.ClientException TEST.exceptions.glance = create_stubbed_exception(glance_exception) quantum_exception = quantum_exceptions.QuantumClientException TEST.exceptions.quantum = create_stubbed_exception(quantum_exception) swift_exception = swift_exceptions.ClientException TEST.exceptions.swift = create_stubbed_exception(swift_exception) cinder_exception = cinder_exceptions.BadRequest TEST.exceptions.cinder = create_stubbed_exception(cinder_exception)
apache-2.0
mapr/hue
desktop/core/ext-py/Paste-2.0.1/paste/exceptions/reporter.py
50
4576
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib import time try: from socket import sslerror except ImportError: sslerror = None from paste.exceptions import formatter class Reporter(object): def __init__(self, **conf): for name, value in conf.items(): if not hasattr(self, name): raise TypeError( "The keyword argument %s was not expected" % name) setattr(self, name, value) self.check_params() def check_params(self): pass def format_date(self, exc_data): return time.strftime('%c', exc_data.date) def format_html(self, exc_data, **kw): return formatter.format_html(exc_data, **kw) def format_text(self, exc_data, **kw): return formatter.format_text(exc_data, **kw) class EmailReporter(Reporter): to_addresses = None from_address = None smtp_server = 'localhost' smtp_username = None smtp_password = None smtp_use_tls = False subject_prefix = '' def report(self, exc_data): msg = self.assemble_email(exc_data) server = smtplib.SMTP(self.smtp_server) if self.smtp_use_tls: server.ehlo() server.starttls() server.ehlo() if self.smtp_username and self.smtp_password: server.login(self.smtp_username, self.smtp_password) server.sendmail(self.from_address, self.to_addresses, msg.as_string()) try: server.quit() except sslerror: # sslerror is raised in tls connections on closing sometimes pass def check_params(self): if not self.to_addresses: raise ValueError("You must set to_addresses") if not self.from_address: raise ValueError("You must set from_address") if isinstance(self.to_addresses, (str, unicode)): self.to_addresses = [self.to_addresses] def assemble_email(self, exc_data): short_html_version = self.format_html( exc_data, show_hidden_frames=False) long_html_version = self.format_html( exc_data, show_hidden_frames=True) text_version = self.format_text( exc_data, show_hidden_frames=False) msg = MIMEMultipart() msg.set_type('multipart/alternative') msg.preamble = msg.epilogue = '' text_msg = MIMEText(text_version) text_msg.set_type('text/plain') text_msg.set_param('charset', 'ASCII') msg.attach(text_msg) html_msg = MIMEText(short_html_version) html_msg.set_type('text/html') # @@: Correct character set? html_msg.set_param('charset', 'UTF-8') html_long = MIMEText(long_html_version) html_long.set_type('text/html') html_long.set_param('charset', 'UTF-8') msg.attach(html_msg) msg.attach(html_long) subject = '%s: %s' % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value))) msg['Subject'] = self.subject_prefix + subject msg['From'] = self.from_address msg['To'] = ', '.join(self.to_addresses) return msg class LogReporter(Reporter): filename = None show_hidden_frames = True def check_params(self): assert self.filename is not None, ( "You must give a filename") def report(self, exc_data): text = self.format_text( exc_data, show_hidden_frames=self.show_hidden_frames) f = open(self.filename, 'a') try: f.write(text + '\n' + '-'*60 + '\n') finally: f.close() class FileReporter(Reporter): file = None show_hidden_frames = True def check_params(self): assert self.file is not None, ( "You must give a file object") def report(self, exc_data): text = self.format_text( exc_data, show_hidden_frames=self.show_hidden_frames) self.file.write(text + '\n' + '-'*60 + '\n') class WSGIAppReporter(Reporter): def __init__(self, exc_data): self.exc_data = exc_data def __call__(self, environ, start_response): start_response('500 Server Error', [('Content-type', 'text/html')]) return [formatter.format_html(self.exc_data)]
apache-2.0
kedz/sumpy
sumpy/io.py
1
4037
import os import re import pandas as pd def load_duc_docset(input_source): docs = DucSgmlReader().read(input_source) return docs def load_duc_abstractive_summaries(input_source): models = DucAbstractSgmlReader().read(input_source) return models class FileInput(object): def gather_paths(self, source): """Determines the type of source and return an iterator over input document paths. If source is a str or unicode object, determine if it is also a directory and return an iterator for all directory files; otherwise treat as a single document input. If source is any other iterable, treat as an iterable of file paths.""" if isinstance(source, str) or isinstance(source, unicode): if os.path.isdir(source): paths = [os.path.join(source, fname) for fname in os.listdir(source)] for path in paths: yield path else: yield source else: try: for path in source: yield path except TypeError: print source, 'is not iterable' class DucSgmlReader(FileInput): def read(self, input_source): docs = [] for path in self.gather_paths(input_source): with open(path, u"r") as f: sgml = "".join(f.readlines()) m = re.search(r"<TEXT>(.*?)</TEXT>", sgml, flags=re.DOTALL) if m is None: raise Exception("TEXT not found in " + path) text = m.group(1).strip() text_clean = re.sub(r"<[^>]*?>", r"", text) docs.append(text_clean) return docs class DucAbstractSgmlReader(FileInput): def read(self, input_source): docs = [] for path in self.gather_paths(input_source): with open(path, u"r") as f: sgml = "".join(f.readlines()) m = re.search(r"<SUM[^>]+>(.*?)</SUM>", sgml, flags=re.DOTALL) if m is None: raise Exception("SUM not found in " + path) text = m.group(1).strip() docs.append(text) return docs class MeadDocSentReader(FileInput): docsent_patt = (r"<DOCSENT DID='([^']+)'\s+DOCNO='([^']+)'\s+" r"LANG='([^']+)'\s+CORR-DOC='([^']+)'>") sent_patt = (r"<S PAR=['\"]([^']+)['\"]\s+" r"RSNT=['\"]([^']+)['\"]\s+" r"SNO=['\"]([^']+)['\"]>(.*?)</S>") def read(self, input_source): docs = [] for path in self.gather_paths(input_source): sents = [] with open(path, u"r") as f: xml = "".join(f.readlines()) m = re.search(self.docsent_patt, xml, flags=re.DOTALL) if m is None: raise Exception("DOCSENT not found in " + path) doc_id = m.group(1) lang = m.group(3) for s in re.finditer(self.sent_patt, xml, flags=re.DOTALL): par = int(s.group(1)) rsnt = s.group(2) sno = s.group(3) text = s.group(4).strip() if par > 1: sents.append(text) #sents.append({u"doc id": doc_id, u"sent id": int(rsnt), # u"type": u"body" if par > 1 else u"headline", # u"text": text.decode("utf-8")}) docs.append("\n".join(sents).decode("utf-8")) #df = pd.DataFrame( # sents, columns=[u"doc id", u"type", u"sent id", u"text"]) #df.set_index([u"doc id", u"sent id"], inplace=True) return docs def load_demo_docs(): import pkg_resources input_source = pkg_resources.resource_filename( "sumpy", os.path.join("data", "mead_example_docs")) return MeadDocSentReader().read(input_source)
apache-2.0
luhanhan/horizon
horizon/templatetags/branding.py
88
2028
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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. """ Template tags for customizing Horizon. """ from django.conf import settings from django.core.urlresolvers import reverse from django import template from django.utils.translation import ugettext_lazy as _ register = template.Library() class SiteBrandingNode(template.Node): def render(self, context): return getattr(settings, "SITE_BRANDING", _("Horizon")) @register.tag def site_branding(parser, token): return SiteBrandingNode() @register.tag def site_title(parser, token): return settings.SITE_BRANDING @register.simple_tag def site_branding_link(): return getattr(settings, "SITE_BRANDING_LINK", reverse("horizon:user_home")) # TODO(jeffjapan): This is just an assignment tag version of the above, replace # when the dashboard is upgraded to a django version that # supports the @assignment_tag decorator syntax instead. class SaveBrandingNode(template.Node): def __init__(self, var_name): self.var_name = var_name def render(self, context): context[self.var_name] = settings.SITE_BRANDING return "" @register.tag def save_site_branding(parser, token): tagname = token.contents.split() return SaveBrandingNode(tagname[-1])
apache-2.0
lyft/incubator-airflow
airflow/example_dags/example_passing_params_via_test_command.py
4
2352
# # 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. """Example DAG demonstrating the usage of the params arguments in templated arguments.""" from datetime import timedelta from airflow import DAG from airflow.operators.bash import BashOperator from airflow.operators.python import PythonOperator from airflow.utils.dates import days_ago dag = DAG( "example_passing_params_via_test_command", default_args={ "owner": "airflow", "start_date": days_ago(1), }, schedule_interval='*/1 * * * *', dagrun_timeout=timedelta(minutes=4), tags=['example'] ) def my_py_command(test_mode, params): """ Print out the "foo" param passed in via `airflow tasks test example_passing_params_via_test_command run_this <date> -tp '{"foo":"bar"}'` """ if test_mode: print(" 'foo' was passed in via test={} command : kwargs[params][foo] \ = {}".format(test_mode, params["foo"])) # Print out the value of "miff", passed in below via the Python Operator print(" 'miff' was passed in via task params = {}".format(params["miff"])) return 1 my_templated_command = """ echo " 'foo was passed in via Airflow CLI Test command with value {{ params.foo }} " echo " 'miff was passed in via BashOperator with value {{ params.miff }} " """ run_this = PythonOperator( task_id='run_this', python_callable=my_py_command, params={"miff": "agg"}, dag=dag, ) also_run_this = BashOperator( task_id='also_run_this', bash_command=my_templated_command, params={"miff": "agg"}, dag=dag, ) run_this >> also_run_this
apache-2.0
jgoclawski/django
tests/validation/tests.py
301
8536
from __future__ import unicode_literals from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.test import TestCase from django.utils.functional import lazy from . import ValidationTestCase from .models import ( Article, Author, GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest, ModelToValidate, ) class BaseModelValidationTests(ValidationTestCase): def test_missing_required_field_raises_error(self): mtv = ModelToValidate(f_with_custom_validator=42) self.assertFailsValidation(mtv.full_clean, ['name', 'number']) def test_with_correct_value_model_validates(self): mtv = ModelToValidate(number=10, name='Some Name') self.assertIsNone(mtv.full_clean()) def test_custom_validate_method(self): mtv = ModelToValidate(number=11) self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name']) def test_wrong_FK_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', parent_id=3) self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'parent', ['model to validate instance with id %r does not exist.' % mtv.parent_id]) mtv = ModelToValidate(number=10, name='Some Name', ufm_id='Some Name') self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'ufm', ["unique fields model instance with unique_charfield %r does not exist." % mtv.name]) def test_correct_FK_value_validates(self): parent = ModelToValidate.objects.create(number=10, name='Some Name') mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) self.assertIsNone(mtv.full_clean()) def test_limited_FK_raises_error(self): # The limit_choices_to on the parent field says that a parent object's # number attribute must be 10, so this should fail validation. parent = ModelToValidate.objects.create(number=11, name='Other Name') mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) self.assertFailsValidation(mtv.full_clean, ['parent']) def test_wrong_email_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', email='not-an-email') self.assertFailsValidation(mtv.full_clean, ['email']) def test_correct_email_value_passes(self): mtv = ModelToValidate(number=10, name='Some Name', email='valid@email.com') self.assertIsNone(mtv.full_clean()) def test_wrong_url_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', url='not a url') self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', ['Enter a valid URL.']) def test_text_greater_that_charfields_max_length_raises_errors(self): mtv = ModelToValidate(number=10, name='Some Name' * 100) self.assertFailsValidation(mtv.full_clean, ['name']) def test_malformed_slug_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', slug='##invalid##') self.assertFailsValidation(mtv.full_clean, ['slug']) def test_full_clean_does_not_mutate_exclude(self): mtv = ModelToValidate(f_with_custom_validator=42) exclude = ['number'] self.assertFailsValidation(mtv.full_clean, ['name'], exclude=exclude) self.assertEqual(len(exclude), 1) self.assertEqual(exclude[0], 'number') class ArticleForm(forms.ModelForm): class Meta: model = Article exclude = ['author'] class ModelFormsTests(TestCase): def setUp(self): self.author = Author.objects.create(name='Joseph Kocherhans') def test_partial_validation(self): # Make sure the "commit=False and set field values later" idiom still # works with model validation. data = { 'title': 'The state of model validation', 'pub_date': '2010-1-10 14:49:00' } form = ArticleForm(data) self.assertEqual(list(form.errors), []) article = form.save(commit=False) article.author = self.author article.save() def test_validation_with_empty_blank_field(self): # Since a value for pub_date wasn't provided and the field is # blank=True, model-validation should pass. # Also, Article.clean() should be run, so pub_date will be filled after # validation, so the form should save cleanly even though pub_date is # not allowed to be null. data = { 'title': 'The state of model validation', } article = Article(author_id=self.author.id) form = ArticleForm(data, instance=article) self.assertEqual(list(form.errors), []) self.assertNotEqual(form.instance.pub_date, None) article = form.save() def test_validation_with_invalid_blank_field(self): # Even though pub_date is set to blank=True, an invalid value was # provided, so it should fail validation. data = { 'title': 'The state of model validation', 'pub_date': 'never' } article = Article(author_id=self.author.id) form = ArticleForm(data, instance=article) self.assertEqual(list(form.errors), ['pub_date']) class GenericIPAddressFieldTests(ValidationTestCase): def test_correct_generic_ip_passes(self): giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4") self.assertIsNone(giptm.full_clean()) giptm = GenericIPAddressTestModel(generic_ip=" 1.2.3.4 ") self.assertIsNone(giptm.full_clean()) giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4\n") self.assertIsNone(giptm.full_clean()) giptm = GenericIPAddressTestModel(generic_ip="2001::2") self.assertIsNone(giptm.full_clean()) def test_invalid_generic_ip_raises_error(self): giptm = GenericIPAddressTestModel(generic_ip="294.4.2.1") self.assertFailsValidation(giptm.full_clean, ['generic_ip']) giptm = GenericIPAddressTestModel(generic_ip="1:2") self.assertFailsValidation(giptm.full_clean, ['generic_ip']) giptm = GenericIPAddressTestModel(generic_ip=1) self.assertFailsValidation(giptm.full_clean, ['generic_ip']) giptm = GenericIPAddressTestModel(generic_ip=lazy(lambda: 1, int)) self.assertFailsValidation(giptm.full_clean, ['generic_ip']) def test_correct_v4_ip_passes(self): giptm = GenericIPAddressTestModel(v4_ip="1.2.3.4") self.assertIsNone(giptm.full_clean()) def test_invalid_v4_ip_raises_error(self): giptm = GenericIPAddressTestModel(v4_ip="294.4.2.1") self.assertFailsValidation(giptm.full_clean, ['v4_ip']) giptm = GenericIPAddressTestModel(v4_ip="2001::2") self.assertFailsValidation(giptm.full_clean, ['v4_ip']) def test_correct_v6_ip_passes(self): giptm = GenericIPAddressTestModel(v6_ip="2001::2") self.assertIsNone(giptm.full_clean()) def test_invalid_v6_ip_raises_error(self): giptm = GenericIPAddressTestModel(v6_ip="1.2.3.4") self.assertFailsValidation(giptm.full_clean, ['v6_ip']) giptm = GenericIPAddressTestModel(v6_ip="1:2") self.assertFailsValidation(giptm.full_clean, ['v6_ip']) def test_v6_uniqueness_detection(self): # These two addresses are the same with different syntax giptm = GenericIPAddressTestModel(generic_ip="2001::1:0:0:0:0:2") giptm.save() giptm = GenericIPAddressTestModel(generic_ip="2001:0:1:2") self.assertFailsValidation(giptm.full_clean, ['generic_ip']) def test_v4_unpack_uniqueness_detection(self): # These two are different, because we are not doing IPv4 unpacking giptm = GenericIPAddressTestModel(generic_ip="::ffff:10.10.10.10") giptm.save() giptm = GenericIPAddressTestModel(generic_ip="10.10.10.10") self.assertIsNone(giptm.full_clean()) # These two are the same, because we are doing IPv4 unpacking giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="::ffff:18.52.18.52") giptm.save() giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="18.52.18.52") self.assertFailsValidation(giptm.full_clean, ['generic_v4unpack_ip']) def test_empty_generic_ip_passes(self): giptm = GenericIPAddressTestModel(generic_ip="") self.assertIsNone(giptm.full_clean()) giptm = GenericIPAddressTestModel(generic_ip=None) self.assertIsNone(giptm.full_clean())
bsd-3-clause
fabianekc/n7
n7.py
1
2906
#!/usr/bin/python import urllib, inflect, string, json, sys, Algorithmia # tests # python n7.py '{"h2t":"http://slashdot.org", "auth":"API_KEY"}' # python n7.py '{"url":"http://derstandard.at"}' # python n7.py '{"text":"life is a miracle"}' # initialize p = inflect.engine() text = "" offset = 7 start_line = -1 end_line = -1 new_text = [] new_line = [] table = string.maketrans("", "") dict_url = "https://raw.githubusercontent.com/fabianekc/n7/master/nounlist.txt" # parse input; sample URL: 'http://www.gutenberg.org/cache/epub/97/pg97.txt' input = json.loads(str(sys.argv[1])) if 'url' in input: text = urllib.urlopen(input['url']).read() elif 'h2t' in input: if 'auth' in input: client = Algorithmia.client(input['auth']) text = client.algo('util/Html2Text/0.1.3').pipe(input['h2t']) else: print("Error: provide authentication when using the html2text preprocessing from Algorithmia") sys.exit() elif 'text' in input: text = input['text'] else: text = urllib.urlopen(input).read() if 'offset' in input: offset = input['offset'] if 'dict' in input: dict_url = input['dict'] if 'start' in input: start_line = input['start'] if 'end' in input: end_line = input['end'] if text == "": print("Error: no input text provided") sys.exit() if isinstance(text, str): text = text.decode('utf-8') text = text.encode('ascii', 'replace') text_split = text.split('\n') if end_line > -1: text_split = text_split[0:end_line] if start_line > -1: text_split = text_split[start_line:] dict = urllib.urlopen(dict_url).read().split() ld = len(dict) # iterate over text for line in text_split: for word in line.split(): # when replacing words we need to take care for # - punc: punctuation # - sipl: singular / plural # - new vs final: uppercase / capitalize / lowercase punc = word.translate(table, string.punctuation) sipl = p.singular_noun(punc) if sipl: new = sipl else: new = punc if (new.lower() in dict): if punc == word: if sipl: final = p.plural(dict[(dict.index(new.lower())+offset)%ld]) else: final = dict[dict.index(new.lower())+offset] else: if sipl: final = word.replace(punc, p.plural(dict[(dict.index(new.lower())+offset)%ld])) else: final = word.replace(punc, dict[(dict.index(new.lower())+offset)%ld]) if new.lower() != new: if new.upper() == new: final = final.upper() else: final = final.capitalize() else: final = word new_line.append(final) new_text.append(" ".join(new_line)) new_line = [] print "\n".join(new_text)
mit
mathiasertl/django-ca
ca/django_ca/management/commands/init_ca.py
1
10835
# This file is part of django-ca (https://github.com/mathiasertl/django-ca). # # django-ca 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. # # django-ca 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 django-ca. If not, # see <http://www.gnu.org/licenses/>. """Management command to create a certificate authority. .. seealso:: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ """ import os import pathlib import typing from datetime import timedelta from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from django.core.management.base import CommandError from django.core.management.base import CommandParser from django.utils import timezone from ... import ca_settings from ...extensions import IssuerAlternativeName from ...extensions import NameConstraints from ...models import CertificateAuthority from ...subject import Subject from ...tasks import cache_crl from ...tasks import generate_ocsp_key from ...tasks import run_task from ...typehints import ParsableKeyType from ..actions import ExpiresAction from ..actions import MultipleURLAction from ..actions import PasswordAction from ..actions import URLAction from ..base import BaseCommand from ..mixins import CertificateAuthorityDetailMixin class Command(CertificateAuthorityDetailMixin, BaseCommand): """Implement :command:`manage.py init_ca`.""" help = "Create a certificate authority." def add_arguments(self, parser: CommandParser) -> None: self.add_general_args(parser) self.add_algorithm(parser) self.add_key_type(parser) self.add_key_size(parser) self.add_ecc_curve(parser) parser.add_argument( "--expires", metavar="DAYS", action=ExpiresAction, default=timedelta(365 * 10), help="CA certificate expires in DAYS days (default: %(default)s).", ) self.add_ca( parser, "--parent", no_default=True, help_text="Make the CA an intermediate CA of the named CA. By default, this is a new root CA.", ) parser.add_argument("name", help="Human-readable name of the CA") self.add_subject( parser, help_text="""The subject of the CA in the format "/key1=value1/key2=value2/...", valid keys are %s. If "CN" is not set, the name is used.""" % self.valid_subject_keys, ) self.add_password( parser, help_text="Optional password used to encrypt the private key. If no argument is passed, " "you will be prompted.", ) parser.add_argument( "--path", type=pathlib.PurePath, help="Path where to store Certificate Authorities (relative to CA_DIR).", ) parser.add_argument( "--parent-password", nargs="?", action=PasswordAction, metavar="PASSWORD", prompt="Password for parent CA: ", help="Password for the private key of any parent CA.", ) group = parser.add_argument_group( "Default hostname", "The default hostname is used to compute default URLs for services like OCSP. The hostname is " "usually configured in your settings (current setting: %s), but you can override that value " "here. The value must be just the hostname and optionally a port, *without* a protocol, e.g. " '"ca.example.com" or "ca.example.com:8000".' % ca_settings.CA_DEFAULT_HOSTNAME, ) group = group.add_mutually_exclusive_group() group.add_argument( "--default-hostname", metavar="HOSTNAME", help="Override the the default hostname configured in your settings.", ) group.add_argument( "--no-default-hostname", dest="default_hostname", action="store_false", help="Disable any default hostname configured in your settings.", ) self.add_acme_group(parser) group = parser.add_argument_group( "pathlen attribute", """Maximum number of CAs that can appear below this one. A pathlen of zero (the default) means it can only be used to sign end user certificates and not further CAs.""", ) group = group.add_mutually_exclusive_group() group.add_argument( "--pathlen", default=0, type=int, help="Maximum number of sublevel CAs (default: %(default)s)." ) group.add_argument( "--no-pathlen", action="store_const", const=None, dest="pathlen", help="Do not add a pathlen attribute.", ) group = parser.add_argument_group( "X509 v3 certificate extensions for CA", """Extensions added to the certificate authority itself. These options cannot be changed without creating a new authority.""", ) group.add_argument( "--ca-crl-url", action=MultipleURLAction, help="URL to a certificate revokation list. Can be given multiple times.", ) group.add_argument("--ca-ocsp-url", metavar="URL", action=URLAction, help="URL of an OCSP responder.") group.add_argument( "--ca-issuer-url", metavar="URL", action=URLAction, help="URL to the certificate of your CA (in DER format).", ) nc_group = parser.add_argument_group( "Name Constraints", "Add name constraints to the CA, limiting what certificates this CA can sign." ) nc_group.add_argument( "--permit-name", metavar="NAME", action="append", default=[], help="Add the given name to the permitted-subtree.", ) nc_group.add_argument( "--exclude-name", metavar="NAME", action="append", default=[], help="Add the given name to the excluded-subtree.", ) self.add_ca_args(parser) def handle( # type: ignore[override] # pylint: disable=too-many-arguments,too-many-locals self, name: str, subject: Subject, parent: typing.Optional[CertificateAuthority], expires: timedelta, key_size: int, key_type: ParsableKeyType, ecc_curve: typing.Optional[ec.EllipticCurve], algorithm: hashes.HashAlgorithm, pathlen: typing.Optional[int], password: typing.Optional[bytes], parent_password: typing.Optional[bytes], crl_url: typing.List[str], ocsp_url: typing.Optional[str], issuer_url: typing.Optional[str], ca_crl_url: typing.List[str], ca_ocsp_url: typing.Optional[str], ca_issuer_url: typing.Optional[str], permit_name: typing.List[str], exclude_name: typing.List[str], caa: str, website: str, tos: str, **options: typing.Any ) -> None: if not os.path.exists(ca_settings.CA_DIR): # pragma: no cover # TODO: set permissions os.makedirs(ca_settings.CA_DIR) # In case of CAs, we silently set the expiry date to that of the parent CA if the user specified a # number of days that would make the CA expire after the parent CA. # # The reasoning is simple: When issuing the child CA, the default is automatically after that of the # parent if it wasn't issued on the same day. if parent and timezone.now() + expires > parent.expires: expires = parent.expires # type: ignore[assignment] if parent and not parent.allows_intermediate_ca: raise CommandError("Parent CA cannot create intermediate CA due to pathlen restrictions.") if not parent and ca_crl_url: raise CommandError("CRLs cannot be used to revoke root CAs.") if not parent and ca_ocsp_url: raise CommandError("OCSP cannot be used to revoke root CAs.") # See if we can work with the private key if parent: self.test_private_key(parent, parent_password) # Set CommonName to name if not set in subject if "CN" not in subject: subject["CN"] = name name_constraints = NameConstraints({"value": {"permitted": permit_name, "excluded": exclude_name}}) issuer_alternative_name = options[IssuerAlternativeName.key] if issuer_alternative_name is None: issuer_alternative_name = "" kwargs = {} for opt in ["path", "default_hostname"]: if options[opt] is not None: kwargs[opt] = options[opt] if ca_settings.CA_ENABLE_ACME: # pragma: no branch; never False because parser throws error already # These settings are only there if ACME is enabled for opt in ["acme_enabled", "acme_requires_contact"]: if options[opt] is not None: kwargs[opt] = options[opt] try: ca = CertificateAuthority.objects.init( name=name, subject=subject, expires=expires, algorithm=algorithm, parent=parent, pathlen=pathlen, issuer_url=issuer_url, issuer_alt_name=",".join(issuer_alternative_name), crl_url=crl_url, ocsp_url=ocsp_url, ca_issuer_url=ca_issuer_url, ca_crl_url=ca_crl_url, ca_ocsp_url=ca_ocsp_url, name_constraints=name_constraints, password=password, parent_password=parent_password, ecc_curve=ecc_curve, key_type=key_type, key_size=key_size, caa=caa, website=website, terms_of_service=tos, **kwargs ) except Exception as ex: raise CommandError(ex) from ex # Generate OCSP keys and cache CRLs run_task(generate_ocsp_key, serial=ca.serial, password=password) run_task(cache_crl, serial=ca.serial, password=password)
gpl-3.0
hipikat/django-revkom
revkom/utils/mixins.py
1
4147
""" Generic mixins for classes. """ from functools import partial from django.conf import settings from django.core.exceptions import ImproperlyConfigured class GetSettingsMixin(object): """ A generic class mixin which adds a _get_settings() method, which will return a tuple of settings or throw appropriate errors if they aren't defined. TODO: Extend to allow default settings or warn instaed of error. TODO: Create methods at class-creation time; allow renaming. """ def get_setting(self, setting): try: return getattr(settings, setting) except AttributeError: raise ImproperlyConfigured( "The class {} requires the setting {} to be defined.".format( self.__class__.__name__, setting)) def get_settings(self, *get_list, **default_list): setting_list = [] for setting in get_list: setting_list.append(self._get_setting(setting)) for setting, default in default_list.iteritems(): setting_list.append(getattr(settings, setting, default)) return setting_list class InstanceProp(object): def accessors(self): access = [self.getter] if hasattr(self, setter): access.append(self.setter) if hasattr(self, deleter): access.append(self.deleter) def getter(self): raise NotImplementedError class BooleanProp(InstanceProp): def __init__(self, default): self._value = bool(default) if default else None def getter(self): return self._value def setter(self, value): self._value = bool(value) class StringProp(InstanceProp): # TODO: Should this be unicode or something? def __init__(self, default): self._value = str(default) if default else None def getter(self): return self._value def setter(self, value): self._value = str(value) class PropMetaclass(type): _prop_types = { 'boolean': BooleanProp, 'string': StringProp, } def __new__(mcls, name, bases, attrs): #def print_foo(self): # print('foo') #attrs['print_bar'] = print_foo def _add_prop(ptype_class, self, prop_name, *init_args, **init_kwargs): """ Add a property called prop_name to self. The property's getter, setter and deleter are taken from methods (with those names) attached to a new instance of ``ptype_class``, where they exist. The propety is initialised with ``init_args`` and ``init_kwargs``. """ # TODO: Warn if property already exists? #import pdb; pdb.set_trace() prop_instance = ptype_class(*init_args, **init_kwargs) accessors = [prop_instance.getter] if hasattr(prop_instance, 'setter'): accessors.append(prop_instance.setter) if hasattr(prop_instance, 'deleter'): accessors.append(prop_instance.deleter) prop = property(*accessors) setattr(self, prop_name, prop) #attrs['_add_prop'] = _add_prop for ptype_name, ptype_class in mcls._prop_types.iteritems(): prop_adder_name = "add_%s_prop" % ptype_name prop_adder_func = partial(_add_prop, ptype_class) attrs[prop_adder_name] = prop_adder_func #setattr(instance, prop_adder_name, prop_adder_func) return super(PropMetaclass, mcls).__new__(mcls, name, bases, attrs) # def __new__(cls, *args, **kwargs): # """ # Return a new instance of cls, with methods like ``add_boolean_prop(...)`` # attached, ready to be used in the instance's ``__init__(...)`` method. # """ # instance = super(PropMixin, cls).__new__(cls, *args, **kwargs) # for ptype_name, ptype_class in cls._prop_types.iteritems(): # prop_adder_name = "add_%s_prop" % ptype_name # prop_adder_func = partial(instance._add_prop, ptype_class) # setattr(instance, prop_adder_name, prop_adder_func) # return instance
bsd-2-clause
JimCircadian/ansible
lib/ansible/modules/remote_management/ipmi/ipmi_boot.py
23
5576
#!/usr/bin/python # -*- coding: utf-8 -*- # # 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: ipmi_boot short_description: Management of order of boot devices description: - Use this module to manage order of boot devices version_added: "2.2" options: name: description: - Hostname or ip address of the BMC. required: true port: description: - Remote RMCP port. default: 623 user: description: - Username to use to connect to the BMC. required: true password: description: - Password to connect to the BMC. required: true bootdev: description: - Set boot device to use on next reboot required: true choices: - network -- Request network boot - floppy -- Boot from floppy - hd -- Boot from hard drive - safe -- Boot from hard drive, requesting 'safe mode' - optical -- boot from CD/DVD/BD drive - setup -- Boot into setup utility - default -- remove any IPMI directed boot device request state: description: - Whether to ensure that boot devices is desired. default: present choices: - present -- Request system turn on - absent -- Request system turn on persistent: description: - If set, ask that system firmware uses this device beyond next boot. Be aware many systems do not honor this. type: bool default: 'no' uefiboot: description: - If set, request UEFI boot explicitly. Strictly speaking, the spec suggests that if not set, the system should BIOS boot and offers no "don't care" option. In practice, this flag not being set does not preclude UEFI boot on any system I've encountered. type: bool default: 'no' requirements: - "python >= 2.6" - pyghmi author: "Bulat Gaifullin (gaifullinbf@gmail.com)" ''' RETURN = ''' bootdev: description: The boot device name which will be used beyond next boot. returned: success type: string sample: default persistent: description: If True, system firmware will use this device beyond next boot. returned: success type: bool sample: false uefimode: description: If True, system firmware will use UEFI boot explicitly beyond next boot. returned: success type: bool sample: false ''' EXAMPLES = ''' # Ensure bootdevice is HD. - ipmi_boot: name: test.testdomain.com user: admin password: password bootdev: hd # Ensure bootdevice is not Network - ipmi_boot: name: test.testdomain.com user: admin password: password bootdev: network state: absent ''' try: from pyghmi.ipmi import command except ImportError: command = None from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), port=dict(default=623, type='int'), user=dict(required=True, no_log=True), password=dict(required=True, no_log=True), state=dict(default='present', choices=['present', 'absent']), bootdev=dict(required=True, choices=['network', 'hd', 'floppy', 'safe', 'optical', 'setup', 'default']), persistent=dict(default=False, type='bool'), uefiboot=dict(default=False, type='bool') ), supports_check_mode=True, ) if command is None: module.fail_json(msg='the python pyghmi module is required') name = module.params['name'] port = module.params['port'] user = module.params['user'] password = module.params['password'] state = module.params['state'] bootdev = module.params['bootdev'] persistent = module.params['persistent'] uefiboot = module.params['uefiboot'] request = dict() if state == 'absent' and bootdev == 'default': module.fail_json(msg="The bootdev 'default' cannot be used with state 'absent'.") # --- run command --- try: ipmi_cmd = command.Command( bmc=name, userid=user, password=password, port=port ) module.debug('ipmi instantiated - name: "%s"' % name) current = ipmi_cmd.get_bootdev() # uefimode may not supported by BMC, so use desired value as default current.setdefault('uefimode', uefiboot) if state == 'present' and current != dict(bootdev=bootdev, persistent=persistent, uefimode=uefiboot): request = dict(bootdev=bootdev, uefiboot=uefiboot, persist=persistent) elif state == 'absent' and current['bootdev'] == bootdev: request = dict(bootdev='default') else: module.exit_json(changed=False, **current) if module.check_mode: response = dict(bootdev=request['bootdev']) else: response = ipmi_cmd.set_bootdev(**request) if 'error' in response: module.fail_json(msg=response['error']) if 'persist' in request: response['persistent'] = request['persist'] if 'uefiboot' in request: response['uefimode'] = request['uefiboot'] module.exit_json(changed=True, **response) except Exception as e: module.fail_json(msg=str(e)) if __name__ == '__main__': main()
gpl-3.0
mgagne/nova
nova/tests/unit/api/openstack/compute/contrib/test_cloudpipe_update.py
38
3994
# Copyright 2012 IBM Corp. # # 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 webob from nova.api.openstack.compute.contrib import cloudpipe_update as clup_v2 from nova.api.openstack.compute.plugins.v3 import cloudpipe as clup_v21 from nova import db from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit import fake_network fake_networks = [fake_network.fake_network(1), fake_network.fake_network(2)] def fake_project_get_networks(context, project_id, associate=True): return fake_networks def fake_network_update(context, network_id, values): for network in fake_networks: if network['id'] == network_id: for key in values: network[key] = values[key] class CloudpipeUpdateTestV21(test.NoDBTestCase): bad_request = exception.ValidationError def setUp(self): super(CloudpipeUpdateTestV21, self).setUp() self.stubs.Set(db, "project_get_networks", fake_project_get_networks) self.stubs.Set(db, "network_update", fake_network_update) self._setup() self.req = fakes.HTTPRequest.blank('') def _setup(self): self.controller = clup_v21.CloudpipeController() def _check_status(self, expected_status, res, controller_methord): self.assertEqual(expected_status, controller_methord.wsgi_code) def test_cloudpipe_configure_project(self): body = {"configure_project": {"vpn_ip": "1.2.3.4", "vpn_port": 222}} result = self.controller.update(self.req, 'configure-project', body=body) self._check_status(202, result, self.controller.update) self.assertEqual(fake_networks[0]['vpn_public_address'], "1.2.3.4") self.assertEqual(fake_networks[0]['vpn_public_port'], 222) def test_cloudpipe_configure_project_bad_url(self): body = {"configure_project": {"vpn_ip": "1.2.3.4", "vpn_port": 222}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update, self.req, 'configure-projectx', body=body) def test_cloudpipe_configure_project_bad_data(self): body = {"configure_project": {"vpn_ipxx": "1.2.3.4", "vpn_port": 222}} self.assertRaises(self.bad_request, self.controller.update, self.req, 'configure-project', body=body) def test_cloudpipe_configure_project_bad_vpn_port(self): body = {"configure_project": {"vpn_ipxx": "1.2.3.4", "vpn_port": "foo"}} self.assertRaises(self.bad_request, self.controller.update, self.req, 'configure-project', body=body) def test_cloudpipe_configure_project_vpn_port_with_empty_string(self): body = {"configure_project": {"vpn_ipxx": "1.2.3.4", "vpn_port": ""}} self.assertRaises(self.bad_request, self.controller.update, self.req, 'configure-project', body=body) class CloudpipeUpdateTestV2(CloudpipeUpdateTestV21): bad_request = webob.exc.HTTPBadRequest def _setup(self): self.controller = clup_v2.CloudpipeUpdateController() def _check_status(self, expected_status, res, controller_methord): self.assertEqual(expected_status, res.status_int)
apache-2.0
RapidApplicationDevelopment/tensorflow
tensorflow/contrib/stat_summarizer/__init__.py
17
1284
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exposes the Python wrapper for StatSummarizer utility class. The wrapper implementation is in tensorflow/python/util/stat_summarizer.i for technical reasons, but it should be accessed via tf.contrib.stat_summarizer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,wildcard-import, line-too-long from tensorflow.python.pywrap_tensorflow import DeleteStatSummarizer from tensorflow.python.pywrap_tensorflow import NewStatSummarizer from tensorflow.python.pywrap_tensorflow import StatSummarizer
apache-2.0
djw8605/condor
src/condor_contrib/mgmt/qmf/test/jobcontrol.py
9
1434
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009-2011 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from qmf.console import Session from sys import exit, argv, stdin import time cmds = ['SetJobAttribute', 'HoldJob', 'ReleaseJob', 'RemoveJob'] cmdarg = len(argv) > 1 and argv[1] jobid = len(argv) > 2 and argv[2] url = len(argv) > 3 and argv[3] or "amqp://localhost:5672" if cmdarg not in cmds: print "error unknown command: ", cmdarg print "available commands are: ",cmds exit(1) try: session = Session(); broker = session.addBroker(url) schedulers = session.getObjects(_class="scheduler", _package="com.redhat.grid") except Exception, e: print "unable to access broker or scheduler" exit(1) result = schedulers[0]._invoke(cmdarg,[jobid,"test"],[None]) if result.status: print "error invoking: ", cmdarg print result.text session.delBroker(broker) exit(1) session.delBroker(broker)
apache-2.0
anryko/ansible
lib/ansible/modules/net_tools/hetzner_failover_ip.py
30
3706
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2019 Felix Fontein <felix@fontein.de> # 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 = r''' --- module: hetzner_failover_ip version_added: "2.9" short_description: Manage Hetzner's failover IPs author: - Felix Fontein (@felixfontein) description: - Manage Hetzner's failover IPs. seealso: - name: Failover IP documentation description: Hetzner's documentation on failover IPs. link: https://wiki.hetzner.de/index.php/Failover/en - module: hetzner_failover_ip_info description: Retrieve information on failover IPs. extends_documentation_fragment: - hetzner options: failover_ip: description: The failover IP address. type: str required: yes state: description: - Defines whether the IP will be routed or not. - If set to C(routed), I(value) must be specified. type: str choices: - routed - unrouted default: routed value: description: - The new value for the failover IP address. - Required when setting I(state) to C(routed). type: str timeout: description: - Timeout to use when routing or unrouting the failover IP. - Note that the API call returns when the failover IP has been successfully routed to the new address, respectively successfully unrouted. type: int default: 180 ''' EXAMPLES = r''' - name: Set value of failover IP 1.2.3.4 to 5.6.7.8 hetzner_failover_ip: hetzner_user: foo hetzner_password: bar failover_ip: 1.2.3.4 value: 5.6.7.8 - name: Set value of failover IP 1.2.3.4 to unrouted hetzner_failover_ip: hetzner_user: foo hetzner_password: bar failover_ip: 1.2.3.4 state: unrouted ''' RETURN = r''' value: description: - The value of the failover IP. - Will be C(none) if the IP is unrouted. returned: success type: str state: description: - Will be C(routed) or C(unrouted). returned: success type: str ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.hetzner import ( HETZNER_DEFAULT_ARGUMENT_SPEC, get_failover, set_failover, get_failover_state, ) def main(): argument_spec = dict( failover_ip=dict(type='str', required=True), state=dict(type='str', default='routed', choices=['routed', 'unrouted']), value=dict(type='str'), timeout=dict(type='int', default=180), ) argument_spec.update(HETZNER_DEFAULT_ARGUMENT_SPEC) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=( ('state', 'routed', ['value']), ), ) failover_ip = module.params['failover_ip'] value = get_failover(module, failover_ip) changed = False before = get_failover_state(value) if module.params['state'] == 'routed': new_value = module.params['value'] else: new_value = None if value != new_value: if module.check_mode: value = new_value changed = True else: value, changed = set_failover(module, failover_ip, new_value, timeout=module.params['timeout']) after = get_failover_state(value) module.exit_json( changed=changed, diff=dict( before=before, after=after, ), **after ) if __name__ == '__main__': main()
gpl-3.0
StephenWeber/ansible
lib/ansible/modules/network/panos/panos_cert_gen_ssh.py
19
6384
#!/usr/bin/python # -*- coding: utf-8 -*- # # Ansible module to manage PaloAltoNetworks Firewall # (c) 2016, techbizdev <techbizdev@paloaltonetworks.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: panos_cert_gen_ssh short_description: generates a self-signed certificate using SSH protocol with SSH key description: - This module generates a self-signed certificate that can be used by GlobalProtect client, SSL connector, or - otherwise. Root certificate must be preset on the system first. This module depends on paramiko for ssh. author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)" version_added: "2.3" requirements: - paramiko notes: - Checkmode is not supported. options: ip_address: description: - IP address (or hostname) of PAN-OS device being configured. required: true default: null key_filename: description: - Location of the filename that is used for the auth. Either I(key_filename) or I(password) is required. required: true default: null password: description: - Password credentials to use for auth. Either I(key_filename) or I(password) is required. required: true default: null cert_friendly_name: description: - Human friendly certificate name (not CN but just a friendly name). required: true default: null cert_cn: description: - Certificate CN (common name) embeded in the certificate signature. required: true default: null signed_by: description: - Undersigning authority (CA) that MUST already be presents on the device. required: true default: null rsa_nbits: description: - Number of bits used by the RSA algorithm for the certificate generation. required: false default: "2048" ''' EXAMPLES = ''' # Generates a new self-signed certificate using ssh - name: generate self signed certificate panos_cert_gen_ssh: ip_address: "192.168.1.1" password: "paloalto" cert_cn: "1.1.1.1" cert_friendly_name: "test123" signed_by: "root-ca" ''' RETURN=''' # Default return values ''' ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import get_exception import time try: import paramiko HAS_LIB=True except ImportError: HAS_LIB=False _PROMPTBUFF = 4096 def wait_with_timeout(module, shell, prompt, timeout=60): now = time.time() result = "" while True: if shell.recv_ready(): result += shell.recv(_PROMPTBUFF) endresult = result.strip() if len(endresult) != 0 and endresult[-1] == prompt: break if time.time()-now > timeout: module.fail_json(msg="Timeout waiting for prompt") return result def generate_cert(module, ip_address, key_filename, password, cert_cn, cert_friendly_name, signed_by, rsa_nbits ): stdout = "" client = paramiko.SSHClient() # add policy to accept all host keys, I haven't found # a way to retreive the instance SSH key fingerprint from AWS client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if not key_filename: client.connect(ip_address, username="admin", password=password) else: client.connect(ip_address, username="admin", key_filename=key_filename) shell = client.invoke_shell() # wait for the shell to start buff = wait_with_timeout(module, shell, ">") stdout += buff # generate self-signed certificate if isinstance(cert_cn, list): cert_cn = cert_cn[0] cmd = 'request certificate generate signed-by {0} certificate-name {1} name {2} algorithm RSA rsa-nbits {3}\n'.format( signed_by, cert_friendly_name, cert_cn, rsa_nbits) shell.send(cmd) # wait for the shell to complete buff = wait_with_timeout(module, shell, ">") stdout += buff # exit shell.send('exit\n') if 'Success' not in buff: module.fail_json(msg="Error generating self signed certificate: "+stdout) client.close() return stdout def main(): argument_spec = dict( ip_address=dict(required=True), key_filename=dict(), password=dict(no_log=True), cert_cn=dict(required=True), cert_friendly_name=dict(required=True), rsa_nbits=dict(default='2048'), signed_by=dict(required=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['key_filename', 'password']]) if not HAS_LIB: module.fail_json(msg='paramiko is required for this module') ip_address = module.params["ip_address"] key_filename = module.params["key_filename"] password = module.params["password"] cert_cn = module.params["cert_cn"] cert_friendly_name = module.params["cert_friendly_name"] signed_by = module.params["signed_by"] rsa_nbits = module.params["rsa_nbits"] try: stdout = generate_cert(module, ip_address, key_filename, password, cert_cn, cert_friendly_name, signed_by, rsa_nbits) except Exception: exc = get_exception() module.fail_json(msg=exc.message) module.exit_json(changed=True, msg="okey dokey") if __name__ == '__main__': main()
gpl-3.0
sunlianqiang/kbengine
kbe/res/scripts/common/Lib/lib2to3/patcomp.py
93
7075
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Pattern compiler. The grammer is taken from PatternGrammar.txt. The compiler compiles a pattern to a pytree.*Pattern instance. """ __author__ = "Guido van Rossum <guido@python.org>" # Python imports import io import os # Fairly local imports from .pgen2 import driver, literals, token, tokenize, parse, grammar # Really local imports from . import pytree from . import pygram # The pattern grammar file _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "PatternGrammar.txt") class PatternSyntaxError(Exception): pass def tokenize_wrapper(input): """Tokenizes a string suppressing significant whitespace.""" skip = set((token.NEWLINE, token.INDENT, token.DEDENT)) tokens = tokenize.generate_tokens(io.StringIO(input).readline) for quintuple in tokens: type, value, start, end, line_text = quintuple if type not in skip: yield quintuple class PatternCompiler(object): def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE): """Initializer. Takes an optional alternative filename for the pattern grammar. """ self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert) def compile_pattern(self, input, debug=False, with_tree=False): """Compiles a pattern string to a nested pytree.*Pattern object.""" tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: raise PatternSyntaxError(str(e)) if with_tree: return self.compile_node(root), root else: return self.compile_node(root) def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ # XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize() def compile_basic(self, nodes, repeat=None): # Compile STRING | NAME [Details] | (...) | [...] assert len(nodes) >= 1 node = nodes[0] if node.type == token.STRING: value = str(literals.evalString(node.value)) return pytree.LeafPattern(_type_of_literal(value), value) elif node.type == token.NAME: value = node.value if value.isupper(): if value not in TOKEN_MAP: raise PatternSyntaxError("Invalid token: %r" % value) if nodes[1:]: raise PatternSyntaxError("Can't have details for token") return pytree.LeafPattern(TOKEN_MAP[value]) else: if value == "any": type = None elif not value.startswith("_"): type = getattr(self.pysyms, value, None) if type is None: raise PatternSyntaxError("Invalid symbol: %r" % value) if nodes[1:]: # Details present content = [self.compile_node(nodes[1].children[1])] else: content = None return pytree.NodePattern(type, content) elif node.value == "(": return self.compile_node(nodes[1]) elif node.value == "[": assert repeat is None subpattern = self.compile_node(nodes[1]) return pytree.WildcardPattern([[subpattern]], min=0, max=1) assert False, node def get_int(self, node): assert node.type == token.NUMBER return int(node.value) # Map named tokens to the type value for a LeafPattern TOKEN_MAP = {"NAME": token.NAME, "STRING": token.STRING, "NUMBER": token.NUMBER, "TOKEN": None} def _type_of_literal(value): if value[0].isalpha(): return token.NAME elif value in grammar.opmap: return grammar.opmap[value] else: return None def pattern_convert(grammar, raw_node_info): """Converts raw node information to a Node or Leaf instance.""" type, value, context, children = raw_node_info if children or type in grammar.number2symbol: return pytree.Node(type, children, context=context) else: return pytree.Leaf(type, value, context=context) def compile_pattern(pattern): return PatternCompiler().compile_pattern(pattern)
lgpl-3.0
csuttles/utils
python/todo-api/flask/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/connection.py
679
3293
import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True if not poll: if not select: # Platform-specific: AppEngine return False try: return select([sock], [], [], 0.0)[0] except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True # This function is copied from socket.py in the Python 2.7 standard # library test suite. Added to its signature is only `socket_options`. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=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 socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. # This is the only addition urllib3 makes to this function. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as _: err = _ if sock is not None: sock.close() sock = None if err is not None: raise err else: raise socket.error("getaddrinfo returns an empty list") def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt)
apache-2.0
puzan/ansible
lib/ansible/modules/cloud/openstack/os_keypair.py
3
5344
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # Copyright (c) 2013, Benno Joy <benno@ansible.com> # Copyright (c) 2013, John Dewey <john@dewey.ws> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software 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 software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_keypair short_description: Add/Delete a keypair from OpenStack author: "Benno Joy (@bennojoy)" extends_documentation_fragment: openstack version_added: "2.0" description: - Add or Remove key pair from OpenStack options: name: description: - Name that has to be given to the key pair required: true default: None public_key: description: - The public key that would be uploaded to nova and injected into VMs upon creation. required: false default: None public_key_file: description: - Path to local file containing ssh public key. Mutually exclusive with public_key. required: false default: None state: description: - Should the resource be present or absent. choices: [present, absent] default: present availability_zone: description: - Ignored. Present for backwards compatability required: false requirements: [] ''' EXAMPLES = ''' # Creates a key pair with the running users public key - os_keypair: cloud: mordred state: present name: ansible_key public_key_file: /home/me/.ssh/id_rsa.pub # Creates a new key pair and the private key returned after the run. - os_keypair: cloud: rax-dfw state: present name: ansible_key ''' RETURN = ''' id: description: Unique UUID. returned: success type: string name: description: Name given to the keypair. returned: success type: string public_key: description: The public key value for the keypair. returned: success type: string private_key: description: The private key value for the keypair. returned: Only when a keypair is generated for the user (e.g., when creating one and a public key is not specified). type: string ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False def _system_state_change(module, keypair): state = module.params['state'] if state == 'present' and not keypair: return True if state == 'absent' and keypair: return True return False def main(): argument_spec = openstack_full_argument_spec( name = dict(required=True), public_key = dict(default=None), public_key_file = dict(default=None), state = dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs( mutually_exclusive=[['public_key', 'public_key_file']]) module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] name = module.params['name'] public_key = module.params['public_key'] if module.params['public_key_file']: public_key = open(module.params['public_key_file']).read() public_key = public_key.rstrip() try: cloud = shade.openstack_cloud(**module.params) keypair = cloud.get_keypair(name) if module.check_mode: module.exit_json(changed=_system_state_change(module, keypair)) if state == 'present': if keypair and keypair['name'] == name: if public_key and (public_key != keypair['public_key']): module.fail_json( msg="Key name %s present but key hash not the same" " as offered. Delete key first." % name ) else: changed = False else: keypair = cloud.create_keypair(name, public_key) changed = True module.exit_json(changed=changed, key=keypair, id=keypair['id']) elif state == 'absent': if keypair: cloud.delete_keypair(name) module.exit_json(changed=True) module.exit_json(changed=False) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0
mskrzypkows/servo
tests/wpt/web-platform-tests/tools/html5lib/html5lib/treewalkers/pulldom.py
1729
2302
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
mpl-2.0
dannybrowne86/django-timepiece
timepiece/tests/test_utils.py
3
2189
import datetime from django.test import TestCase from timepiece.utils import get_active_entry, ActiveEntryError from timepiece import utils from . import factories class UtilityFunctionsTest(TestCase): def setUp(self): # Setup last billable days self.last_billable = [ utils.add_timezone(datetime.datetime(2012, 3, 25)), utils.add_timezone(datetime.datetime(2012, 4, 29)), utils.add_timezone(datetime.datetime(2012, 5, 27)), utils.add_timezone(datetime.datetime(2012, 6, 24)), utils.add_timezone(datetime.datetime(2012, 7, 29)), utils.add_timezone(datetime.datetime(2012, 8, 26)), ] self.dates = [ utils.add_timezone(datetime.datetime(2012, 3, 12)), utils.add_timezone(datetime.datetime(2012, 4, 3)), utils.add_timezone(datetime.datetime(2012, 5, 18)), utils.add_timezone(datetime.datetime(2012, 6, 20)), utils.add_timezone(datetime.datetime(2012, 7, 1)), utils.add_timezone(datetime.datetime(2012, 8, 25)), ] def test_get_last_billable_day(self): for idx, date in enumerate(self.dates): self.assertEquals(self.last_billable[idx], utils.get_last_billable_day(date)) class GetActiveEntryTest(TestCase): def setUp(self): self.user = factories.User() def test_get_active_entry_none(self): self.assertIsNone(get_active_entry(self.user)) def test_get_active_entry_single(self): now = datetime.datetime.now() entry = factories.Entry(user=self.user, start_time=now) # not active factories.Entry(user=self.user, start_time=now, end_time=now) # different user factories.Entry(start_time=now) self.assertEqual(entry, get_active_entry(self.user)) def test_get_active_entry_multiple(self): now = datetime.datetime.now() # two active entries for same user factories.Entry(user=self.user, start_time=now) factories.Entry(user=self.user, start_time=now) self.assertRaises(ActiveEntryError, get_active_entry, self.user)
mit
alaw1290/CS591B1
analysis/test_data_weighted_sums.py
1
2907
import pickle import numpy as np import cf_recommender as cf import similarity_functions as sf import movie_reviews_compiler as mrc path = '../data/' def run_test_weighted_sums(cosine=True): '''compute the predictions for masked values in the testing set (user review vectors) using the training set (critic review matrix) model for predictions: weighted sum of critics using cosine similiarity''' #get testing data audience_names = pickle.load(open(path + 'audience_names.pkl','rb')) audience_review_test_set = pickle.load(open(path + 'audience_test_data.pkl','rb')) #get training data movie_critic, critic_movie, matrix, movie_keys, critic_keys = mrc.import_pickle() #compute average ratings for weighted sum avg_ratings = {} for i in range(len(matrix)): avg_ratings[critic_keys[i]] = sum(matrix[i])/len([0 for j in matrix[i] if j != 0]) #store results for pickle weighted_sums_results = {} for aud_review_index in range(len(audience_review_test_set)): name = audience_names[aud_review_index].split("'s")[0] print('\nTest Vector: ' + name) test_vector = audience_review_test_set[aud_review_index] #find indicies of masks for testing reviewed_indicies = [i for i in range(len(test_vector)) if test_vector[i] != 0] #if there are more than 1 reviews for the user: if(len(reviewed_indicies) > 1): actual_vals = [] prediced_vals = [] av = [] pv = [] for mask in reviewed_indicies: #mask selected index vector = [i for i in test_vector] vector[mask] = 0 #compute predicted value if(cosine): critics_sim = sf.run_cosine(vector,matrix,movie_critic,movie_keys,critic_keys) else: critics_sim = sf.run_pearson(vector,matrix,movie_critic,movie_keys,critic_keys) result_vector = cf.weighted_sums(vector,critics_sim,movie_keys,critic_keys,movie_critic, avg_ratings) print('\tPredicted for index ' + str(mask) + ': ' + str(result_vector[mask])) print('\tActual for index ' + str(mask) + ': ' + str(test_vector[mask])) prediced_vals.append(result_vector[mask]) actual_vals.append(test_vector[mask]) av.append((mask,test_vector[mask])) pv.append((mask,result_vector[mask])) #calculate accuracy using the root mean square error value RMSE = float(((sum([(actual_vals[i]-prediced_vals[i])**2 for i in range(len(reviewed_indicies))]))/len(reviewed_indicies))**0.5) print('\n\tRMSE for Test Vector: ' + str(RMSE)) weighted_sums_results[name] = {'actual':av,'predicted':pv,'RMSE':RMSE} else: print('\n\tOnly 1 review not predictable') weighted_sums_results[name] = 'Error' #export weighted sums results if(cosine): pickle.dump(weighted_sums_results, open(path + "weighted_sums_results_cosine.pkl", "wb" ) ) else: pickle.dump(weighted_sums_results, open(path + "weighted_sums_results_pearson.pkl", "wb" ) ) return weighted_sums_results
mit
ddayguerrero/blogme
flask/lib/python3.4/site-packages/sqlalchemy/dialects/sqlite/pysqlcipher.py
80
4129
# sqlite/pysqlcipher.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: sqlite+pysqlcipher :name: pysqlcipher :dbapi: pysqlcipher :connectstring: sqlite+pysqlcipher://:passphrase/file_path[?kdf_iter=<iter>] :url: https://pypi.python.org/pypi/pysqlcipher ``pysqlcipher`` is a fork of the standard ``pysqlite`` driver to make use of the `SQLCipher <https://www.zetetic.net/sqlcipher>`_ backend. .. versionadded:: 0.9.9 Driver ------ The driver here is the `pysqlcipher <https://pypi.python.org/pypi/pysqlcipher>`_ driver, which makes use of the SQLCipher engine. This system essentially introduces new PRAGMA commands to SQLite which allows the setting of a passphrase and other encryption parameters, allowing the database file to be encrypted. Connect Strings --------------- The format of the connect string is in every way the same as that of the :mod:`~sqlalchemy.dialects.sqlite.pysqlite` driver, except that the "password" field is now accepted, which should contain a passphrase:: e = create_engine('sqlite+pysqlcipher://:testing@/foo.db') For an absolute file path, two leading slashes should be used for the database name:: e = create_engine('sqlite+pysqlcipher://:testing@//path/to/foo.db') A selection of additional encryption-related pragmas supported by SQLCipher as documented at https://www.zetetic.net/sqlcipher/sqlcipher-api/ can be passed in the query string, and will result in that PRAGMA being called for each new connection. Currently, ``cipher``, ``kdf_iter`` ``cipher_page_size`` and ``cipher_use_hmac`` are supported:: e = create_engine('sqlite+pysqlcipher://:testing@/foo.db?cipher=aes-256-cfb&kdf_iter=64000') Pooling Behavior ---------------- The driver makes a change to the default pool behavior of pysqlite as described in :ref:`pysqlite_threading_pooling`. The pysqlcipher driver has been observed to be significantly slower on connection than the pysqlite driver, most likely due to the encryption overhead, so the dialect here defaults to using the :class:`.SingletonThreadPool` implementation, instead of the :class:`.NullPool` pool used by pysqlite. As always, the pool implementation is entirely configurable using the :paramref:`.create_engine.poolclass` parameter; the :class:`.StaticPool` may be more feasible for single-threaded use, or :class:`.NullPool` may be used to prevent unencrypted connections from being held open for long periods of time, at the expense of slower startup time for new connections. """ from __future__ import absolute_import from .pysqlite import SQLiteDialect_pysqlite from ...engine import url as _url from ... import pool class SQLiteDialect_pysqlcipher(SQLiteDialect_pysqlite): driver = 'pysqlcipher' pragmas = ('kdf_iter', 'cipher', 'cipher_page_size', 'cipher_use_hmac') @classmethod def dbapi(cls): from pysqlcipher import dbapi2 as sqlcipher return sqlcipher @classmethod def get_pool_class(cls, url): return pool.SingletonThreadPool def connect(self, *cargs, **cparams): passphrase = cparams.pop('passphrase', '') pragmas = dict( (key, cparams.pop(key, None)) for key in self.pragmas ) conn = super(SQLiteDialect_pysqlcipher, self).\ connect(*cargs, **cparams) conn.execute('pragma key="%s"' % passphrase) for prag, value in pragmas.items(): if value is not None: conn.execute('pragma %s=%s' % (prag, value)) return conn def create_connect_args(self, url): super_url = _url.URL( url.drivername, username=url.username, host=url.host, database=url.database, query=url.query) c_args, opts = super(SQLiteDialect_pysqlcipher, self).\ create_connect_args(super_url) opts['passphrase'] = url.password return c_args, opts dialect = SQLiteDialect_pysqlcipher
mit
anthgur/servo
tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/assertion/__init__.py
15
5166
""" support for presenting detailed information in failing assertions. """ from __future__ import absolute_import, division, print_function import sys import six from _pytest.assertion import util from _pytest.assertion import rewrite from _pytest.assertion import truncate def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", choices=("rewrite", "plain",), default="rewrite", metavar="MODE", help="""Control assertion debugging tools. 'plain' performs no assertion debugging. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert expression information.""") def register_assert_rewrite(*names): """Register one or more module names to be rewritten on import. This function will make sure that this module or all modules inside the package will get their assert statements rewritten. Thus you should make sure to call this before the module is actually imported, usually in your __init__.py if you are a plugin using a package. :raise TypeError: if the given module names are not strings. """ for name in names: if not isinstance(name, str): msg = 'expected module names as *args, got {0} instead' raise TypeError(msg.format(repr(names))) for hook in sys.meta_path: if isinstance(hook, rewrite.AssertionRewritingHook): importhook = hook break else: importhook = DummyRewriteHook() importhook.mark_rewrite(*names) class DummyRewriteHook(object): """A no-op import hook for when rewriting is disabled.""" def mark_rewrite(self, *names): pass class AssertionState: """State for the assertion plugin.""" def __init__(self, config, mode): self.mode = mode self.trace = config.trace.root.get("assertion") self.hook = None def install_importhook(config): """Try to install the rewrite hook, raise SystemError if it fails.""" # Jython has an AST bug that make the assertion rewriting hook malfunction. if (sys.platform.startswith('java')): raise SystemError('rewrite not supported') config._assertstate = AssertionState(config, 'rewrite') config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config) sys.meta_path.insert(0, hook) config._assertstate.trace('installed rewrite import hook') def undo(): hook = config._assertstate.hook if hook is not None and hook in sys.meta_path: sys.meta_path.remove(hook) config.add_cleanup(undo) return hook def pytest_collection(session): # this hook is only called when test modules are collected # so for example not in the master process of pytest-xdist # (which does not collect test modules) assertstate = getattr(session.config, '_assertstate', None) if assertstate: if assertstate.hook is not None: assertstate.hook.set_session(session) def pytest_runtest_setup(item): """Setup the pytest_assertrepr_compare hook The newinterpret and rewrite modules will use util._reprcompare if it exists to use custom reporting via the pytest_assertrepr_compare hook. This sets up this custom comparison for the test. """ def callbinrepr(op, left, right): """Call the pytest_assertrepr_compare hook and prepare the result This uses the first result from the hook and then ensures the following: * Overly verbose explanations are truncated unless configured otherwise (eg. if running in verbose mode). * Embedded newlines are escaped to help util.format_explanation() later. * If the rewrite mode is used embedded %-characters are replaced to protect later % formatting. The result can be formatted by util.format_explanation() for pretty printing. """ hook_result = item.ihook.pytest_assertrepr_compare( config=item.config, op=op, left=left, right=right) for new_expl in hook_result: if new_expl: new_expl = truncate.truncate_if_required(new_expl, item) new_expl = [line.replace("\n", "\\n") for line in new_expl] res = six.text_type("\n~").join(new_expl) if item.config.getvalue("assertmode") == "rewrite": res = res.replace("%", "%%") return res util._reprcompare = callbinrepr def pytest_runtest_teardown(item): util._reprcompare = None def pytest_sessionfinish(session): assertstate = getattr(session.config, '_assertstate', None) if assertstate: if assertstate.hook is not None: assertstate.hook.set_session(None) # Expose this plugin's implementation for the pytest_assertrepr_compare hook pytest_assertrepr_compare = util.assertrepr_compare
mpl-2.0
clk8908/pymc3
pymc3/tests/test_ndarray_backend.py
13
2679
import unittest import numpy as np import numpy.testing as npt from pymc3.tests import backend_fixtures as bf from pymc3.backends import base, ndarray class TestNDArray0dSampling(bf.SamplingTestCase): backend = ndarray.NDArray name = None shape = () class TestNDArray1dSampling(bf.SamplingTestCase): backend = ndarray.NDArray name = None shape = 2 class TestNDArray2dSampling(bf.SamplingTestCase): backend = ndarray.NDArray name = None shape = (2, 3) class TestNDArray0dSelection(bf.SelectionTestCase): backend = ndarray.NDArray name = None shape = () class TestNDArray1dSelection(bf.SelectionTestCase): backend = ndarray.NDArray name = None shape = 2 class TestNDArray2dSelection(bf.SelectionTestCase): backend = ndarray.NDArray name = None shape = (2, 3) class TestMultiTrace(bf.ModelBackendSetupTestCase): name = None backend = ndarray.NDArray shape = () def setUp(self): super(TestMultiTrace, self).setUp() self.strace0 = self.strace super(TestMultiTrace, self).setUp() self.strace1 = self.strace def test_multitrace_nonunique(self): self.assertRaises(ValueError, base.MultiTrace, [self.strace0, self.strace1]) def test_merge_traces_nonunique(self): mtrace0 = base.MultiTrace([self.strace0]) mtrace1 = base.MultiTrace([self.strace1]) self.assertRaises(ValueError, base.merge_traces, [mtrace0, mtrace1]) class TestSqueezeCat(unittest.TestCase): def setUp(self): self.x = np.arange(10) self.y = np.arange(10, 20) def test_combine_false_squeeze_false(self): expected = [self.x, self.y] result = base._squeeze_cat([self.x, self.y], False, False) npt.assert_equal(result, expected) def test_combine_true_squeeze_false(self): expected = [np.concatenate([self.x, self.y])] result = base._squeeze_cat([self.x, self.y], True, False) npt.assert_equal(result, expected) def test_combine_false_squeeze_true_more_than_one_item(self): expected = [self.x, self.y] result = base._squeeze_cat([self.x, self.y], False, True) npt.assert_equal(result, expected) def test_combine_false_squeeze_true_one_item(self): expected = self.x result = base._squeeze_cat([self.x], False, True) npt.assert_equal(result, expected) def test_combine_true_squeeze_true(self): expected = np.concatenate([self.x, self.y]) result = base._squeeze_cat([self.x, self.y], True, True) npt.assert_equal(result, expected)
apache-2.0
youfoh/webkit-efl
Tools/Scripts/webkitpy/layout_tests/models/test_results_unittest.py
5
2293
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from webkitpy.layout_tests.models.test_results import TestResult class TestResultsTest(unittest.TestCase): def test_defaults(self): result = TestResult("foo") self.assertEqual(result.test_name, 'foo') self.assertEqual(result.failures, []) self.assertEqual(result.test_run_time, 0) def test_loads(self): result = TestResult(test_name='foo', failures=[], test_run_time=1.1) s = result.dumps() new_result = TestResult.loads(s) self.assertTrue(isinstance(new_result, TestResult)) self.assertEqual(new_result, result) # Also check that != is implemented. self.assertFalse(new_result != result)
lgpl-2.1
csirtgadgets/bearded-avenger
test/zsqlite/test_store_sqlite_tokens.py
1
5082
import logging import os import tempfile from argparse import Namespace import pytest from cif.store import Store from cifsdk.utils import setup_logging import arrow from datetime import datetime from pprint import pprint from cifsdk.exceptions import AuthError args = Namespace(debug=True, verbose=None) setup_logging(args) logger = logging.getLogger(__name__) @pytest.fixture def store(): dbfile = tempfile.mktemp() with Store(store_type='sqlite', dbfile=dbfile) as s: s._load_plugin(dbfile=dbfile) s.token_create_admin() yield s s = None if os.path.isfile(dbfile): os.unlink(dbfile) @pytest.fixture def indicator(): return { 'indicator': 'example.com', 'tags': 'botnet', 'provider': 'csirtgadgets.org', 'group': 'everyone', 'lasttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'), 'itype': 'fqdn', } def test_store_sqlite_tokens(store): t = store.store.tokens.admin_exists() assert t t = list(store.store.tokens.search({'token': t})) assert len(t) > 0 t = t[0]['token'] assert store.store.tokens.update_last_activity_at(t, datetime.now()) assert store.store.tokens.check(t, 'read') assert store.store.tokens.read(t) assert store.store.tokens.write(t) assert store.store.tokens.admin(t) assert store.store.tokens.last_activity_at(t) is not None assert store.store.tokens.update_last_activity_at(t, datetime.now()) def test_store_sqlite_tokens_groups(store): t = store.store.tokens.admin_exists() assert t assert store.store.tokens.edit({'token': t, 'write': False}) assert store.store.tokens.delete({'token': t}) # groups t = store.store.tokens.create({ 'username': 'test', 'groups': ['staff', 'everyone'], 'read': True, 'write': True }) assert t assert t['groups'] == ['staff', 'everyone'] assert t['write'] assert t['read'] assert not t['admin'] i = None try: i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff2', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn' }) except AuthError as e: pass assert i == 0 i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn' }) assert i x = store.store.indicators.search(t, {'indicator': 'example.com'}) assert len(list(x)) > 0 x = store.store.indicators.search(t, {'itype': 'fqdn'}) assert len(list(x)) > 0 def test_store_sqlite_tokens_groups2(store, indicator): t = store.store.tokens.create({ 'username': 'test', 'groups': ['staff'], 'read': True, 'write': True }) i = None try: i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff2', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn', 'lasttime': arrow.utcnow().datetime, 'reporttime': arrow.utcnow().datetime }) except AuthError as e: pass assert (i is None or i == 0) def test_store_sqlite_tokens_groups3(store, indicator): t = store.store.tokens.create({ 'username': 'test', 'groups': ['staff'], 'write': True }) t2 = store.store.tokens.create({ 'username': 'test', 'groups': ['staff2'], 'read': True, }) i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn', 'lasttime': arrow.utcnow().datetime, 'reporttime': arrow.utcnow().datetime }) assert i i = store.store.indicators.search(t2, {'itype': 'fqdn'}) assert len(list(i)) == 0 i = store.store.indicators.search(t2, {'indicator': 'example.com'}) assert len(list(i)) == 0 def test_store_sqlite_tokens_groups4(store, indicator): t = store.store.tokens.create({ 'username': 'test', 'groups': ['staff', 'staff2'], 'write': True, 'read': True }) i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn', 'lasttime': arrow.utcnow().datetime, 'reporttime': arrow.utcnow().datetime }) assert i i = store.store.indicators.create(t, { 'indicator': 'example.com', 'group': 'staff2', 'provider': 'example.com', 'tags': ['test'], 'itype': 'fqdn', 'lasttime': arrow.utcnow().datetime, 'reporttime': arrow.utcnow().datetime }) assert i i = store.store.indicators.search(t['token'], {'itype': 'fqdn', 'groups': 'staff'}) assert len(list(i)) == 1
mpl-2.0
MarcBS/Motion_Video_Segmentation
SIFT/vlfeat-0.9.16/docsrc/mdoc.py
11
16193
#!/usr/bin/python # file: mdoc.py # author: Brian Fulkerson and Andrea Vedaldi # description: MDoc main # Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. # All rights reserved. # # This file is part of the VLFeat library and is made available under # the terms of the BSD license (see the COPYING file). import sys, os, re, shutil import subprocess, signal from wikidoc import wikidoc from formatter import Formatter from optparse import OptionParser excludeRegexList = [] format = 'html' verb = 0 sitexml = "" usage = """usage: %prog [options] <basedir> <docdir> Takes all .m files in basedir and its subdirectories and converts them to html documentation, placing the results in docdir.""" parser = OptionParser(usage=usage) parser.add_option( "-f", "--format", dest = "format", default = "html", action = "store", help = "specify the output format (html, wiki, web)", metavar = "STRING") parser.add_option( "-x", "--exclude", dest = "excludeList", action = "append", type = "string", help = "exclude files matching the specified regexp") parser.add_option( "-v", "--verbose", dest = "verb", default = False, action = "store_true", help = "print debug information") parser.add_option( "-t", "--helptoc", dest = "helptoc", default = False, action = "store_true", help = "create helptoc.xml") parser.add_option( "", "--helptoc-toolbox-name", dest = "helptoc_toolbox_name", default = "Example", action = "store", type = "string", help = "helptoc.xml: Toolbox Name") # -------------------------------------------------------------------- def runcmd(cmd): # -------------------------------------------------------------------- """ runcmd(CMD) runs the command CMD. The function waits for the command to complete and correctly react to Ctrl-C by stopping the process and raising an exception. """ try: p = subprocess.Popen(cmd, shell=True) sts = os.waitpid(p.pid, 0) except (KeyboardInterrupt, SystemExit): os.kill(p.pid, signal.SIGKILL) raise # -------------------------------------------------------------------- class MFile: # -------------------------------------------------------------------- """ MFile('sub/file.m') represents a MATLAB M-File. """ def __init__(self, basedir, dirname, name): funcname = os.path.splitext(name)[0] self.funcname = funcname #.upper() self.path = os.path.join(basedir, dirname, name) self.mdocname = funcname.replace(os.path.sep, '_') self.webname = funcname.replace(os.path.sep, '.') self.htmlname = self.mdocname + '.html' self.wikiname = 'MDoc_' + (os.path.join(dirname, funcname) .upper().replace(os.path.sep, '_')) self.prev = None self.next = None self.node = None def getId (self, format='html'): if format == 'html': return self.htmlname elif format == 'web': return self.webname elif format == 'wiki': return self.wikiname def getRef (self, format='html'): if format == 'html': return self.htmlname elif format == 'web': return '%pathto:' + self.webname + ';' elif format == 'wiki': return self.wikiname def __cmp__(self, other): return cmp(self.webname, other.webname) def __str__(self): str = "MFile: %s\n" % (self.funcname) str += " path : %s\n" % (self.path) str += " mdocname: %s\n" % (self.mdocname) str += " htmlname: %s\n" % (self.htmlname) str += " wikiname: %s\n" % (self.wikiname) return str # -------------------------------------------------------------------- class Node: # -------------------------------------------------------------------- """ A Node N represents a node in the toolbox hierechy. A node is a directory in the toolbox hierarchy and contains both M-files and other sub-directories. """ def __init__(self, dirname): self.dirname = dirname self.children = [] self.mfiles = [] def addChildNode(self, node): "Add a child node (toolbox subdirectory) to this node" self.children.append(node) def addMFile(self, mfile): "Add a MATLAB M-File to this node" self.mfiles.append(mfile) mfile.node = self def toIndexPage(self, format='html', depth=1): "Converts the node hierarchy rooted here into an index." page = "" if format == 'html' or format == 'web': if len(self.mfiles) > 0: page += "<b>%s</b>" % (self.dirname.upper()) page += "<ul>\n" for m in self.mfiles: page += "<li>" page += "<b><a href='%s'>%s</a></b>" % (m.getRef(format), m.funcname) page += " %s" % (m.brief) page += "</li>" page += "</ul>\n" elif format == 'wiki': if len(self.mfiles) > 0: if depth > 1: page += "=== %s ===\n" % (self.dirname.upper()) for m in self.mfiles: page += "* [[%s|%s]]" % (m.getRef(format), m.funcname) page += " %s\n" % (m.brief) elif format == 'helptoc': for m in self.mfiles: page += "<tocitem target='%s'>%s</tocitem>\n" % (m.getRef('html'), m.funcname) else: assert False for n in self.children: page += n.toIndexPage(format, depth+1) return page def toIndexXML(self): xml = "" for m in self.mfiles: dirname = m.node.dirname.upper() if len(dirname) > 0: xml += \ "<page id='%s' name='%s' title='%s - %s' hide='yes'>" \ "<div class='mdoc'>" \ "<include src='%s'/></div></page>\n" % (m.getId('web'), m.funcname, dirname, m.funcname, m.htmlname) else: xml += \ "<page id='%s' name='%s' title='%s' hide='yes'>" \ "<div class='mdoc'>" \ "<include src='%s'/></div></page>\n" % (m.getId('web'), m.funcname, m.funcname, m.htmlname) for n in self.children: xml += n.toIndexXML() ; return xml def __str__(self): s = "Node: %s\n" % self.dirname for m in self.mfiles: s += m.__str__() for n in self.children: s += n.__str__() return s # -------------------------------------------------------------------- def depth_first(node): # -------------------------------------------------------------------- """ depth_first(NODE) is a generator that implements a depth first visit of the node hierarchy rooted at NODE. """ yield node for n in node.children: for m in depth_first(n): yield m return # -------------------------------------------------------------------- def extract(path): # -------------------------------------------------------------------- """ (BODY, FUNC, BRIEF) = extract(PATH) extracts the comment BODY, the function name FUNC and the brief description BRIEF from the MATLAB M-file located at PATH. """ body = [] func = "" brief = "" seenfunction = False seenpercent = False for l in open(path): # Remove whitespace and newline line = l.strip().lstrip() if line.startswith('%'): seenpercent = True if line.startswith('function'): seenfunction = True continue if not line.startswith('%'): if (seenfunction and seenpercent) or not seenfunction: break else: continue # remove leading `%' character line = line[1:] # body.append('%s\n' % line) # Extract header from body if len(body) > 0: head = body[0] body = body[1:] match = re.match(r"^\s*(\w+)\s*(\S.*)\n$", head) func = match.group(1) brief = match.group(2) return (body, func, brief) # -------------------------------------------------------------------- def xscan(baseDir, subDir=''): # -------------------------------------------------------------------- """ NODE = xscan(BASEDIR) recusrively scans the directory BASEDIR and construct the toolbox hierarchy rooted at NODE. """ node = Node(subDir) dir = os.listdir(os.path.join(baseDir, subDir)) fileNames = [f for f in dir if os.path.isfile( os.path.join(baseDir, subDir, f))] subSubDirs = [s for s in dir if os.path.isdir ( os.path.join(baseDir, subDir, s))] fileNames.sort() # Scan M-FileNames for fileName in fileNames: # only m-files if not os.path.splitext(fileName)[1] == '.m': continue # skip if in the exclude list exclude = False for rx in excludeRegexList: fileRelPath = os.path.join(subDir, fileName) mo = rx.match(fileRelPath) if mo and (mo.end() - mo.start() == len(fileRelPath)): if verb: print "mdoc: excluding ''%s''." % fileRelPath exclude = True if exclude: continue node.addMFile(MFile(baseDir, subDir, fileName)) # Scan sub-directories for s in subSubDirs: node.addChildNode(xscan(basedir, os.path.join(subDir, s))) return node # -------------------------------------------------------------------- def breadCrumb(m): # -------------------------------------------------------------------- breadcrumb = "<ul class='breadcrumb'>" if format == 'web': breadcrumb += "<li><a href='%pathto:mdoc;'>Index</a></li>" else: breadcrumb += "<li><a href='index.html'>Index</a></li>" if m.prev: breadcrumb += "<li><a href='%s'>Prev</a></li>" % m.prev.getRef(format) if m.next: breadcrumb += "<li><a href='%s'>Next</a></li>" % m.next.getRef(format) breadcrumb += "</ul>" #breadcrumb += "<span class='path'>%s</span>" % m.node.dirname.upper() return breadcrumb # -------------------------------------------------------------------- if __name__ == '__main__': # -------------------------------------------------------------------- # # Parse comand line options # (options, args) = parser.parse_args() if options.verb: verb = 1 format = options.format helptoc = options.helptoc print options.excludeList for ex in options.excludeList: rx = re.compile(ex) excludeRegexList.append(rx) if len(args) != 2: parser.print_help() sys.exit(2) basedir = args[0] docdir = args[1] if not basedir.endswith('/'): basedir = basedir + "/" if not basedir.endswith('/'): docdir = docdir + "/" if verb: print "mdoc: search path: %s" % basedir print "mdoc: output path: %s" % docdir print "mdoc: output format: %s" % format # # Search for mfiles # toolbox = xscan(basedir) # # Extract dictionaries of links and M-Files # linkdict = {} mfiles = {} prev = None next = None for n in depth_first(toolbox): for m in n.mfiles: if prev: prev.next = m m.prev = prev prev = m func = m.funcname.upper() mfiles[func] = m linkdict[func] = m.getRef(format) if verb: print "mdoc: num mfiles: %d" % (len(mfiles)) # Create output directory if not os.access(docdir, os.F_OK): os.makedirs(docdir) # ---------------------------------------------------------------- # Extract comment block and run formatter # ---------------------------------------------------------------- for (func, m) in mfiles.items(): if format == 'wiki': outname = m.wikiname elif format == 'html': outname = m.htmlname elif format == 'web': outname = m.htmlname if verb: print "mdoc: generating %s from %s" % (outname, m.path) # extract comment block from file (lines, func, brief) = extract(m.path) m.brief = brief # Run formatter content = "" if len(lines) > 0: if format == 'wiki' : formatter = Formatter(lines, linkdict, 'wiki') else: formatter = Formatter(lines, linkdict, 'a') content = formatter.toDOM().toxml("UTF-8") content = content[content.find('?>')+2:] # add decorations if not format == 'wiki': content = breadCrumb(m) + content if format == 'web': content = "<group>\n" + content + "</group>\n" # save the result to an html file if format == 'wiki': f = open(os.path.join(docdir, m.wikiname), 'w') else: f = open(os.path.join(docdir, m.htmlname), 'w') f.write(content) f.close() # ---------------------------------------------------------------- # Make index page # ---------------------------------------------------------------- page = "" if format == 'html': pagename = 'index.html' page += toolbox.toIndexPage('html') elif format == 'web': pagename = 'mdoc.html' page += '<group>\n' + toolbox.toIndexPage('web') + '</group>\n' elif format =='wiki' : pagename = 'MDoc' page = "== Documentation ==\n" page += toolbox.toIndexPage('wiki') f = open(os.path.join(docdir, pagename), 'w') f.write(page) f.close() if format == 'web': f = open(os.path.join(docdir, "mdoc.xml"), 'w') f.write("<group>"+toolbox.toIndexXML()+"</group>\n") f.close() # ---------------------------------------------------------------- # Make helptoc.xml # ---------------------------------------------------------------- if helptoc: page = """<?xml version='1.0' encoding="utf-8"?> <toc version="2.0"> <tocitem target="../index.html">%s <tocitem target="%s" image="HelpIcon.FUNCTION">Functions """ % (options.helptoc_toolbox_name, pagename) page += toolbox.toIndexPage('helptoc') page += """ </tocitem> </tocitem> </toc> """ f = open(os.path.join(docdir, "helptoc.xml"), 'w') f.write(page) f.close() # ---------------------------------------------------------------- # Checkin files to wiki # ---------------------------------------------------------------- def towiki(docdir, pagename): pagenamewiki = pagename + '.wiki' runcmd("cd %s ; mvs update %s" % (docdir, pagenamewiki)) if verb: print "mdoc: converting", pagename, "to", pagenamewiki wikidoc(os.path.join(docdir, pagenamewiki), os.path.join(docdir, pagename)) runcmd("cd %s ; mvs commit -M -m 'Documentation update' %s" % (docdir, pagenamewiki)) if format == 'wiki' : try: towiki(docdir, pagename) except (KeyboardInterrupt, SystemExit): sys.exit(1) for (func, m) in mfiles.items(): try: towiki(docdir, m.wikiname) except (KeyboardInterrupt, SystemExit): sys.exit(1)
gpl-2.0
tbenthompson/taskloaf
taskloaf/promise.py
1
5194
import asyncio import taskloaf from .refcounting import Ref from .object_ref import put, is_ref, ObjectRef import logging logger = logging.getLogger(__name__) def await_handler(args): req_addr = args[0] pr = args[1] async def await_wrapper(): result_ref = await pr._get_future() taskloaf.ctx().messenger.send( req_addr, taskloaf.ctx().protocol.SETRESULT, [pr, result_ref] ) taskloaf.ctx().executor.run_work(await_wrapper) class Promise: def __init__(self, running_on): def on_delete(_id): del taskloaf.ctx().promises[_id] self.ref = Ref(on_delete) self.running_on = running_on self.ensure_future_exists() def encode_capnp(self, msg): self.ref.encode_capnp(msg.ref) msg.runningOn = self.running_on @classmethod def decode_capnp(cls, msg): out = Promise.__new__(Promise) out.ref = Ref.decode_capnp(msg.ref) out.running_on = msg.runningOn return out def ensure_future_exists(self): taskloaf.ctx().promises[self.ref._id] = asyncio.Future( loop=taskloaf.ctx().executor.ioloop ) def _get_future(self): return taskloaf.ctx().promises[self.ref._id] def __await__(self): if taskloaf.ctx().name != self.ref.owner: self.ensure_future_exists() taskloaf.ctx().messenger.send( self.ref.owner, taskloaf.ctx().protocol.AWAIT, [self] ) result_ref = yield from self._get_future().__await__() out = yield from result_ref.get().__await__() if isinstance(out, TaskExceptionCapture): raise out.e return out def set_result(self, result): self._get_future().set_result(result) def then(self, f, to=None): return task(f, self, to=to) def next(self, f, to=None): return self.then(lambda x: f(), to) class TaskExceptionCapture: def __init__(self, e): self.e = e def task_runner(pr, in_f, *in_args): async def task_wrapper(): f = await ensure_obj(in_f) args = [] for a in in_args: args.append(await ensure_obj(a)) try: result = await taskloaf.ctx().executor.wait_for_work(f, *args) # catches all exceptions except system-exiting exceptions that inherit # from BaseException except Exception as e: logger.exception("exception during task") result = TaskExceptionCapture(e) _unwrap_promise(pr, result) taskloaf.ctx().executor.run_work(task_wrapper) def _unwrap_promise(pr, result): if isinstance(result, Promise): def unwrap_then(x): _unwrap_promise(pr, x) result.then(unwrap_then) else: result_ref = put(result) if pr.ref.owner == taskloaf.ctx().name: pr.set_result(result_ref) else: taskloaf.ctx().messenger.send( pr.ref.owner, taskloaf.ctx().protocol.SETRESULT, [pr, result_ref], ) def task_handler(args): task_runner(args[1], args[2], *args[3:]) def set_result_handler(args): args[1].set_result(args[2]) # f and args can be provided in two forms: # -- a python object (f should be callable or awaitable) # -- a dref to a serialized object in the memory manager # if f is a function and the task is being run locally, f is never serialized, # but when the task is being run remotely, f is entered into the def task(f, *args, to=None): ctx = taskloaf.ctx() if to is None: to = ctx.name out_pr = Promise(to) if to == ctx.name: task_runner(out_pr, f, *args) else: msg_objs = [out_pr, ensure_ref(f)] + [ensure_ref(a) for a in args] ctx.messenger.send(to, ctx.protocol.TASK, msg_objs) return out_pr async def _ensure_obj_helper(x): if type(x) == Promise: return await x else: return x async def ensure_obj(maybe_ref): if is_ref(maybe_ref): return await _ensure_obj_helper(await maybe_ref.get()) if type(maybe_ref) == Promise: return await maybe_ref else: return maybe_ref def ensure_ref(v): if is_ref(v): return v return put(v) class TaskMsg: @staticmethod def serialize(args): pr = args[0] objrefs = args[1:] m = taskloaf.message_capnp.Message.new_message() m.init("task") pr.encode_capnp(m.task.promise) m.task.init("objrefs", len(objrefs)) for i, ref in enumerate(objrefs): ref.encode_capnp(m.task.objrefs[i]) return m @staticmethod def deserialize(msg): out = [msg.sourceName, Promise.decode_capnp(msg.task.promise)] for i in range(len(msg.task.objrefs)): out.append(ObjectRef.decode_capnp(msg.task.objrefs[i])) return out def when_all(ps, to=None): if to is None: to = ps[0].running_on async def wait_for_all(): results = [] for i, p in enumerate(ps): results.append(await p) return results return task(wait_for_all, to=to)
mit
valkjsaaa/sl4a
python/src/Tools/framer/framer/slots.py
50
2245
"""Descriptions of all the slots in Python's type objects.""" class Slot(object): def __init__(self, name, cast=None, special=None, default="0"): self.name = name self.cast = cast self.special = special self.default = default Slots = (Slot("ob_size"), Slot("tp_name"), Slot("tp_basicsize"), Slot("tp_itemsize"), Slot("tp_dealloc", "destructor"), Slot("tp_print", "printfunc"), Slot("tp_getattr", "getattrfunc"), Slot("tp_setattr", "setattrfunc"), Slot("tp_compare", "cmpfunc", "__cmp__"), Slot("tp_repr", "reprfunc", "__repr__"), Slot("tp_as_number"), Slot("tp_as_sequence"), Slot("tp_as_mapping"), Slot("tp_hash", "hashfunc", "__hash__"), Slot("tp_call", "ternaryfunc", "__call__"), Slot("tp_str", "reprfunc", "__str__"), Slot("tp_getattro", "getattrofunc", "__getattr__", # XXX "PyObject_GenericGetAttr"), Slot("tp_setattro", "setattrofunc", "__setattr__"), Slot("tp_as_buffer"), Slot("tp_flags", default="Py_TPFLAGS_DEFAULT"), Slot("tp_doc"), Slot("tp_traverse", "traverseprox"), Slot("tp_clear", "inquiry"), Slot("tp_richcompare", "richcmpfunc"), Slot("tp_weaklistoffset"), Slot("tp_iter", "getiterfunc", "__iter__"), Slot("tp_iternext", "iternextfunc", "__next__"), # XXX Slot("tp_methods"), Slot("tp_members"), Slot("tp_getset"), Slot("tp_base"), Slot("tp_dict"), Slot("tp_descr_get", "descrgetfunc"), Slot("tp_descr_set", "descrsetfunc"), Slot("tp_dictoffset"), Slot("tp_init", "initproc", "__init__"), Slot("tp_alloc", "allocfunc"), Slot("tp_new", "newfunc"), Slot("tp_free", "freefunc"), Slot("tp_is_gc", "inquiry"), Slot("tp_bases"), Slot("tp_mro"), Slot("tp_cache"), Slot("tp_subclasses"), Slot("tp_weaklist"), ) # give some slots symbolic names TP_NAME = Slots[1] TP_BASICSIZE = Slots[2] TP_DEALLOC = Slots[4] TP_DOC = Slots[20] TP_METHODS = Slots[27] TP_MEMBERS = Slots[28]
apache-2.0
sagangwee/sagangwee.github.io
build/pygments/pygments/lexers/testing.py
72
8704
# -*- coding: utf-8 -*- """ pygments.lexers.testing ~~~~~~~~~~~~~~~~~~~~~~~ Lexers for testing languages. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, include, bygroups from pygments.token import Comment, Keyword, Name, String __all__ = ['GherkinLexer'] class GherkinLexer(RegexLexer): """ For `Gherkin <http://github.com/aslakhellesoy/gherkin/>` syntax. .. versionadded:: 1.2 """ name = 'Gherkin' aliases = ['cucumber', 'gherkin'] filenames = ['*.feature'] mimetypes = ['text/x-gherkin'] feature_keywords = u'^(기능|機能|功能|フィーチャ|خاصية|תכונה|Функціонал|Функционалност|Функционал|Фича|Особина|Могућност|Özellik|Właściwość|Tính năng|Trajto|Savybė|Požiadavka|Požadavek|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Fīča|Funzionalità|Funktionalität|Funkcionalnost|Funkcionalitāte|Funcționalitate|Functionaliteit|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Feature|Egenskap|Egenskab|Crikey|Característica|Arwedd)(:)(.*)$' feature_element_keywords = u'^(\\s*)(시나리오 개요|시나리오|배경|背景|場景大綱|場景|场景大纲|场景|劇本大綱|劇本|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|シナリオ|سيناريو مخطط|سيناريو|الخلفية|תרחיש|תבנית תרחיש|רקע|Тарих|Сценарій|Сценарио|Сценарий структураси|Сценарий|Структура сценарію|Структура сценарија|Структура сценария|Скица|Рамка на сценарий|Пример|Предыстория|Предистория|Позадина|Передумова|Основа|Концепт|Контекст|Założenia|Wharrimean is|Tình huống|The thing of it is|Tausta|Taust|Tapausaihio|Tapaus|Szenariogrundriss|Szenario|Szablon scenariusza|Stsenaarium|Struktura scenarija|Skica|Skenario konsep|Skenario|Situācija|Senaryo taslağı|Senaryo|Scénář|Scénario|Schema dello scenario|Scenārijs pēc parauga|Scenārijs|Scenár|Scenaro|Scenariusz|Scenariul de şablon|Scenariul de sablon|Scenariu|Scenario Outline|Scenario Amlinellol|Scenario|Scenarijus|Scenarijaus šablonas|Scenarij|Scenarie|Rerefons|Raamstsenaarium|Primer|Pozadí|Pozadina|Pozadie|Plan du scénario|Plan du Scénario|Osnova scénáře|Osnova|Náčrt Scénáře|Náčrt Scenáru|Mate|MISHUN SRSLY|MISHUN|Kịch bản|Konturo de la scenaro|Kontext|Konteksts|Kontekstas|Kontekst|Koncept|Khung tình huống|Khung kịch bản|Háttér|Grundlage|Geçmiş|Forgatókönyv vázlat|Forgatókönyv|Fono|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l\'escenari|Escenario|Escenari|Dis is what went down|Dasar|Contexto|Contexte|Contesto|Condiţii|Conditii|Cenário|Cenario|Cefndir|Bối cảnh|Blokes|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|All y\'all|Achtergrond|Abstrakt Scenario|Abstract Scenario)(:)(.*)$' examples_keywords = u'^(\\s*)(예|例子|例|サンプル|امثلة|דוגמאות|Сценарији|Примери|Приклади|Мисоллар|Значения|Örnekler|Voorbeelden|Variantai|Tapaukset|Scenarios|Scenariji|Scenarijai|Příklady|Példák|Príklady|Przykłady|Primjeri|Primeri|Piemēri|Pavyzdžiai|Paraugs|Juhtumid|Exemplos|Exemples|Exemplele|Exempel|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|EXAMPLZ|Dữ liệu|Contoh|Cobber|Beispiele)(:)(.*)$' step_keywords = u'^(\\s*)(하지만|조건|먼저|만일|만약|단|그리고|그러면|那麼|那么|而且|當|当|前提|假設|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|و |متى |لكن |عندما |ثم |بفرض |اذاً |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Унда |То |Припустимо, що |Припустимо |Онда |Но |Нехай |Лекин |Когато |Када |Кад |К тому же |И |Задато |Задати |Задате |Если |Допустим |Дадено |Ва |Бирок |Аммо |Али |Але |Агар |А |І |Și |És |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Youse know when youse got |Youse know like when |Yna |Ya know how |Ya gotta |Y |Wun |Wtedy |When y\'all |When |Wenn |WEN |Và |Ve |Und |Un |Thì |Then y\'all |Then |Tapi |Tak |Tada |Tad |Så |Stel |Soit |Siis |Si |Sed |Se |Quando |Quand |Quan |Pryd |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Når |När |Niin |Nhưng |N |Mutta |Men |Mas |Maka |Majd |Mais |Maar |Ma |Lorsque |Lorsqu\'|Kun |Kuid |Kui |Khi |Keď |Ketika |Když |Kaj |Kai |Kada |Kad |Jeżeli |Ja |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y\'all |Given |Gitt |Gegeven |Gegeben sei |Fakat |Eğer ki |Etant donné |Et |Então |Entonces |Entao |En |Eeldades |E |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Dengan |Den youse gotta |De |Dato |Dar |Dann |Dan |Dado |Dacă |Daca |DEN |Când |Cuando |Cho |Cept |Cand |Cal |But y\'all |But |Buh |Biết |Bet |BUT |Atès |Atunci |Atesa |Anrhegedig a |Angenommen |And y\'all |And |An |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Aber |AN |A také |A |\* )' tokens = { 'comments': [ (r'^\s*#.*$', Comment), ], 'feature_elements': [ (step_keywords, Keyword, "step_content_stack"), include('comments'), (r"(\s|.)", Name.Function), ], 'feature_elements_on_stack': [ (step_keywords, Keyword, "#pop:2"), include('comments'), (r"(\s|.)", Name.Function), ], 'examples_table': [ (r"\s+\|", Keyword, 'examples_table_header'), include('comments'), (r"(\s|.)", Name.Function), ], 'examples_table_header': [ (r"\s+\|\s*$", Keyword, "#pop:2"), include('comments'), (r"\\\|", Name.Variable), (r"\s*\|", Keyword), (r"[^|]", Name.Variable), ], 'scenario_sections_on_stack': [ (feature_element_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), "feature_elements_on_stack"), ], 'narrative': [ include('scenario_sections_on_stack'), include('comments'), (r"(\s|.)", Name.Function), ], 'table_vars': [ (r'(<[^>]+>)', Name.Variable), ], 'numbers': [ (r'(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', String), ], 'string': [ include('table_vars'), (r'(\s|.)', String), ], 'py_string': [ (r'"""', Keyword, "#pop"), include('string'), ], 'step_content_root': [ (r"$", Keyword, "#pop"), include('step_content'), ], 'step_content_stack': [ (r"$", Keyword, "#pop:2"), include('step_content'), ], 'step_content': [ (r'"', Name.Function, "double_string"), include('table_vars'), include('numbers'), include('comments'), (r'(\s|.)', Name.Function), ], 'table_content': [ (r"\s+\|\s*$", Keyword, "#pop"), include('comments'), (r"\\\|", String), (r"\s*\|", Keyword), include('string'), ], 'double_string': [ (r'"', Name.Function, "#pop"), include('string'), ], 'root': [ (r'\n', Name.Function), include('comments'), (r'"""', Keyword, "py_string"), (r'\s+\|', Keyword, 'table_content'), (r'"', Name.Function, "double_string"), include('table_vars'), include('numbers'), (r'(\s*)(@[^@\r\n\t ]+)', bygroups(Name.Function, Name.Tag)), (step_keywords, bygroups(Name.Function, Keyword), 'step_content_root'), (feature_keywords, bygroups(Keyword, Keyword, Name.Function), 'narrative'), (feature_element_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), 'feature_elements'), (examples_keywords, bygroups(Name.Function, Keyword, Keyword, Name.Function), 'examples_table'), (r'(\s|.)', Name.Function), ] }
mit
ferabra/edx-platform
common/test/acceptance/fixtures/edxnotes.py
14
1841
""" Tools for creating edxnotes content fixture data. """ import json import factory import requests from . import EDXNOTES_STUB_URL class Range(factory.Factory): class Meta(object): # pylint: disable=missing-docstring model = dict start = "/div[1]/p[1]" end = "/div[1]/p[1]" startOffset = 0 endOffset = 8 class Note(factory.Factory): class Meta(object): # pylint: disable=missing-docstring model = dict user = "dummy-user" usage_id = "dummy-usage-id" course_id = "dummy-course-id" text = "dummy note text" quote = "dummy note quote" ranges = [Range()] class EdxNotesFixtureError(Exception): """ Error occurred while installing a edxnote fixture. """ pass class EdxNotesFixture(object): notes = [] def create_notes(self, notes_list): self.notes = notes_list return self def install(self): """ Push the data to the stub EdxNotes service. """ response = requests.post( '{}/create_notes'.format(EDXNOTES_STUB_URL), data=json.dumps(self.notes) ) if not response.ok: raise EdxNotesFixtureError( "Could not create notes {0}. Status was {1}".format( json.dumps(self.notes), response.status_code ) ) return self def cleanup(self): """ Cleanup the stub EdxNotes service. """ self.notes = [] response = requests.put('{}/cleanup'.format(EDXNOTES_STUB_URL)) if not response.ok: raise EdxNotesFixtureError( "Could not cleanup EdxNotes service {0}. Status was {1}".format( json.dumps(self.notes), response.status_code ) ) return self
agpl-3.0
gimite/personfinder
app/vendors/oauth2client/_helpers.py
39
10852
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions for commonly used utilities.""" import base64 import functools import inspect import json import logging import os import warnings import six from six.moves import urllib logger = logging.getLogger(__name__) POSITIONAL_WARNING = 'WARNING' POSITIONAL_EXCEPTION = 'EXCEPTION' POSITIONAL_IGNORE = 'IGNORE' POSITIONAL_SET = frozenset([POSITIONAL_WARNING, POSITIONAL_EXCEPTION, POSITIONAL_IGNORE]) positional_parameters_enforcement = POSITIONAL_WARNING _SYM_LINK_MESSAGE = 'File: {0}: Is a symbolic link.' _IS_DIR_MESSAGE = '{0}: Is a directory' _MISSING_FILE_MESSAGE = 'Cannot access {0}: No such file or directory' def positional(max_positional_args): """A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after ``*`` must be a keyword:: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example ^^^^^^^ To define a function like above, do:: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument:: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter:: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for ``self`` and ``cls``:: class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... The positional decorator behavior is controlled by ``_helpers.positional_parameters_enforcement``, which may be set to ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do nothing, respectively, if a declaration is violated. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError: if a key-word only argument is provided as a positional parameter, but only if _helpers.positional_parameters_enforcement is set to POSITIONAL_EXCEPTION. """ def positional_decorator(wrapped): @functools.wraps(wrapped) def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' message = ('{function}() takes at most {args_max} positional ' 'argument{plural} ({args_given} given)'.format( function=wrapped.__name__, args_max=max_positional_args, args_given=len(args), plural=plural_s)) if positional_parameters_enforcement == POSITIONAL_EXCEPTION: raise TypeError(message) elif positional_parameters_enforcement == POSITIONAL_WARNING: logger.warning(message) return wrapped(*args, **kwargs) return positional_wrapper if isinstance(max_positional_args, six.integer_types): return positional_decorator else: args, _, _, defaults = inspect.getargspec(max_positional_args) return positional(len(args) - len(defaults))(max_positional_args) def scopes_to_string(scopes): """Converts scope value to a string. If scopes is a string then it is simply passed through. If scopes is an iterable then a string is returned that is all the individual scopes concatenated with spaces. Args: scopes: string or iterable of strings, the scopes. Returns: The scopes formatted as a single string. """ if isinstance(scopes, six.string_types): return scopes else: return ' '.join(scopes) def string_to_scopes(scopes): """Converts stringifed scope value to a list. If scopes is a list then it is simply passed through. If scopes is an string then a list of each individual scope is returned. Args: scopes: a string or iterable of strings, the scopes. Returns: The scopes in a list. """ if not scopes: return [] elif isinstance(scopes, six.string_types): return scopes.split(' ') else: return scopes def parse_unique_urlencoded(content): """Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated. """ urlencoded_params = urllib.parse.parse_qs(content) params = {} for key, value in six.iteritems(urlencoded_params): if len(value) != 1: msg = ('URL-encoded content contains a repeated value:' '%s -> %s' % (key, ', '.join(value))) raise ValueError(msg) params[key] = value[0] return params def update_query_params(uri, params): """Updates a URI with new query parameters. If a given key from ``params`` is repeated in the ``uri``, then the URI will be considered invalid and an error will occur. If the URI is valid, then each value from ``params`` will replace the corresponding value in the query parameters (if it exists). Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added. """ parts = urllib.parse.urlparse(uri) query_params = parse_unique_urlencoded(parts.query) query_params.update(params) new_query = urllib.parse.urlencode(query_params) new_parts = parts._replace(query=new_query) return urllib.parse.urlunparse(new_parts) def _add_query_parameter(url, name, value): """Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: return update_query_params(url, {name: value}) def validate_file(filename): if os.path.islink(filename): raise IOError(_SYM_LINK_MESSAGE.format(filename)) elif os.path.isdir(filename): raise IOError(_IS_DIR_MESSAGE.format(filename)) elif not os.path.isfile(filename): warnings.warn(_MISSING_FILE_MESSAGE.format(filename)) def _parse_pem_key(raw_key_input): """Identify and extract PEM keys. Determines whether the given key is in the format of PEM key, and extracts the relevant part of the key if it is. Args: raw_key_input: The contents of a private key file (either PEM or PKCS12). Returns: string, The actual key if the contents are from a PEM file, or else None. """ offset = raw_key_input.find(b'-----BEGIN ') if offset != -1: return raw_key_input[offset:] def _json_encode(data): return json.dumps(data, separators=(',', ':')) def _to_bytes(value, encoding='ascii'): """Converts a string value to bytes, if necessary. Unfortunately, ``six.b`` is insufficient for this task since in Python2 it does not modify ``unicode`` objects. Args: value: The string/bytes value to be converted. encoding: The encoding to use to convert unicode to bytes. Defaults to "ascii", which will not allow any characters from ordinals larger than 127. Other useful values are "latin-1", which which will only allows byte ordinals (up to 255) and "utf-8", which will encode any unicode that needs to be. Returns: The original value converted to bytes (if unicode) or as passed in if it started out as bytes. Raises: ValueError if the value could not be converted to bytes. """ result = (value.encode(encoding) if isinstance(value, six.text_type) else value) if isinstance(result, six.binary_type): return result else: raise ValueError('{0!r} could not be converted to bytes'.format(value)) def _from_bytes(value): """Converts bytes to a string value, if necessary. Args: value: The string/bytes value to be converted. Returns: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError if the value could not be converted to unicode. """ result = (value.decode('utf-8') if isinstance(value, six.binary_type) else value) if isinstance(result, six.text_type): return result else: raise ValueError( '{0!r} could not be converted to unicode'.format(value)) def _urlsafe_b64encode(raw_bytes): raw_bytes = _to_bytes(raw_bytes, encoding='utf-8') return base64.urlsafe_b64encode(raw_bytes).rstrip(b'=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = _to_bytes(b64string) padded = b64string + b'=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
apache-2.0
MridulS/sympy
sympy/physics/quantum/shor.py
17
5901
"""Shor's algorithm and helper functions. Todo: * Get the CMod gate working again using the new Gate API. * Fix everything. * Update docstrings and reformat. * Remove print statements. We may want to think about a better API for this. """ from __future__ import print_function, division import math import random from sympy import Mul, S from sympy import log, sqrt from sympy.core.numbers import igcd from sympy.ntheory import continued_fraction_periodic as continued_fraction from sympy.utilities.iterables import variations from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qft import QFT from sympy.physics.quantum.qexpr import QuantumError class OrderFindingException(QuantumError): pass class CMod(Gate): """A controlled mod gate. This is black box controlled Mod function for use by shor's algorithm. TODO implement a decompose property that returns how to do this in terms of elementary gates """ @classmethod def _eval_args(cls, args): # t = args[0] # a = args[1] # N = args[2] raise NotImplementedError('The CMod gate has not been completed.') @property def t(self): """Size of 1/2 input register. First 1/2 holds output.""" return self.label[0] @property def a(self): """Base of the controlled mod function.""" return self.label[1] @property def N(self): """N is the type of modular arithmetic we are doing.""" return self.label[2] def _apply_operator_Qubit(self, qubits, **options): """ This directly calculates the controlled mod of the second half of the register and puts it in the second This will look pretty when we get Tensor Symbolically working """ n = 1 k = 0 # Determine the value stored in high memory. for i in range(self.t): k = k + n*qubits[self.t + i] n = n*2 # The value to go in low memory will be out. out = int(self.a**k % self.N) # Create array for new qbit-ket which will have high memory unaffected outarray = list(qubits.args[0][:self.t]) # Place out in low memory for i in reversed(range(self.t)): outarray.append((out >> i) & 1) return Qubit(*outarray) def shor(N): """This function implements Shor's factoring algorithm on the Integer N The algorithm starts by picking a random number (a) and seeing if it is coprime with N. If it isn't, then the gcd of the two numbers is a factor and we are done. Otherwise, it begins the period_finding subroutine which finds the period of a in modulo N arithmetic. This period, if even, can be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1. These values are returned. """ a = random.randrange(N - 2) + 2 if igcd(N, a) != 1: print("got lucky with rand") return igcd(N, a) print("a= ", a) print("N= ", N) r = period_find(a, N) print("r= ", r) if r % 2 == 1: print("r is not even, begin again") shor(N) answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N)) return answer def getr(x, y, N): fraction = continued_fraction(x, y) # Now convert into r total = ratioize(fraction, N) return total def ratioize(list, N): if list[0] > N: return S.Zero if len(list) == 1: return list[0] return list[0] + ratioize(list[1:], N) def period_find(a, N): """Finds the period of a in modulo N arithmetic This is quantum part of Shor's algorithm.It takes two registers, puts first in superposition of states with Hadamards so: ``|k>|0>`` with k being all possible choices. It then does a controlled mod and a QFT to determine the order of a. """ epsilon = .5 #picks out t's such that maintains accuracy within epsilon t = int(2*math.ceil(log(N, 2))) # make the first half of register be 0's |000...000> start = [0 for x in range(t)] #Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0> factor = 1/sqrt(2**t) qubits = 0 for arr in variations(range(2), t, repetition=True): qbitArray = arr + start qubits = qubits + Qubit(*qbitArray) circuit = (factor*qubits).expand() #Controlled second half of register so that we have: # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n> circuit = CMod(t, a, N)*circuit #will measure first half of register giving one of the a**k%N's circuit = qapply(circuit) print("controlled Mod'd") for i in range(t): circuit = measure_partial_oneshot(circuit, i) # circuit = measure(i)*circuit # circuit = qapply(circuit) print("measured 1") #Now apply Inverse Quantum Fourier Transform on the second half of the register circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True) print("QFT'd") for i in range(t): circuit = measure_partial_oneshot(circuit, i + t) # circuit = measure(i+t)*circuit # circuit = qapply(circuit) print(circuit) if isinstance(circuit, Qubit): register = circuit elif isinstance(circuit, Mul): register = circuit.args[-1] else: register = circuit.args[-1].args[-1] print(register) n = 1 answer = 0 for i in range(len(register)/2): answer += n*register[i + t] n = n << 1 if answer == 0: raise OrderFindingException( "Order finder returned 0. Happens with chance %f" % epsilon) #turn answer into r using continued fractions g = getr(answer, 2**t, N) print(g) return g
bsd-3-clause
xodus7/tensorflow
tensorflow/contrib/slim/python/slim/nets/vgg_test.py
25
17465
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.vgg.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.framework.python.ops import variables as variables_lib from tensorflow.contrib.slim.python.slim.nets import vgg from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test class VGGATest(test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_a/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_a/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 for is_training in [True, False]: with ops.Graph().as_default(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_a(inputs, num_classes, is_training=is_training) expected_names = [ 'vgg_a/conv1/conv1_1', 'vgg_a/pool1', 'vgg_a/conv2/conv2_1', 'vgg_a/pool2', 'vgg_a/conv3/conv3_1', 'vgg_a/conv3/conv3_2', 'vgg_a/pool3', 'vgg_a/conv4/conv4_1', 'vgg_a/conv4/conv4_2', 'vgg_a/pool4', 'vgg_a/conv5/conv5_1', 'vgg_a/conv5/conv5_2', 'vgg_a/pool5', 'vgg_a/fc6', 'vgg_a/fc7', 'vgg_a/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) vgg.vgg_a(inputs, num_classes) expected_names = [ 'vgg_a/conv1/conv1_1/weights', 'vgg_a/conv1/conv1_1/biases', 'vgg_a/conv2/conv2_1/weights', 'vgg_a/conv2/conv2_1/biases', 'vgg_a/conv3/conv3_1/weights', 'vgg_a/conv3/conv3_1/biases', 'vgg_a/conv3/conv3_2/weights', 'vgg_a/conv3/conv3_2/biases', 'vgg_a/conv4/conv4_1/weights', 'vgg_a/conv4/conv4_1/biases', 'vgg_a/conv4/conv4_2/weights', 'vgg_a/conv4/conv4_2/biases', 'vgg_a/conv5/conv5_1/weights', 'vgg_a/conv5/conv5_1/biases', 'vgg_a/conv5/conv5_2/weights', 'vgg_a/conv5/conv5_2/biases', 'vgg_a/fc6/weights', 'vgg_a/fc6/biases', 'vgg_a/fc7/weights', 'vgg_a/fc7/biases', 'vgg_a/fc8/weights', 'vgg_a/fc8/biases', ] model_variables = [v.op.name for v in variables_lib.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.cached_session(): eval_inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = math_ops.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.cached_session(): train_inputs = random_ops.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_a(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) variable_scope.get_variable_scope().reuse_variables() eval_inputs = random_ops.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_a( eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = math_ops.reduce_mean(logits, [1, 2]) predictions = math_ops.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.cached_session() as sess: inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs) sess.run(variables.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) class VGG16Test(test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_16/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_16/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 for is_training in [True, False]: with ops.Graph().as_default(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_16(inputs, num_classes, is_training=is_training) expected_names = [ 'vgg_16/conv1/conv1_1', 'vgg_16/conv1/conv1_2', 'vgg_16/pool1', 'vgg_16/conv2/conv2_1', 'vgg_16/conv2/conv2_2', 'vgg_16/pool2', 'vgg_16/conv3/conv3_1', 'vgg_16/conv3/conv3_2', 'vgg_16/conv3/conv3_3', 'vgg_16/pool3', 'vgg_16/conv4/conv4_1', 'vgg_16/conv4/conv4_2', 'vgg_16/conv4/conv4_3', 'vgg_16/pool4', 'vgg_16/conv5/conv5_1', 'vgg_16/conv5/conv5_2', 'vgg_16/conv5/conv5_3', 'vgg_16/pool5', 'vgg_16/fc6', 'vgg_16/fc7', 'vgg_16/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) vgg.vgg_16(inputs, num_classes) expected_names = [ 'vgg_16/conv1/conv1_1/weights', 'vgg_16/conv1/conv1_1/biases', 'vgg_16/conv1/conv1_2/weights', 'vgg_16/conv1/conv1_2/biases', 'vgg_16/conv2/conv2_1/weights', 'vgg_16/conv2/conv2_1/biases', 'vgg_16/conv2/conv2_2/weights', 'vgg_16/conv2/conv2_2/biases', 'vgg_16/conv3/conv3_1/weights', 'vgg_16/conv3/conv3_1/biases', 'vgg_16/conv3/conv3_2/weights', 'vgg_16/conv3/conv3_2/biases', 'vgg_16/conv3/conv3_3/weights', 'vgg_16/conv3/conv3_3/biases', 'vgg_16/conv4/conv4_1/weights', 'vgg_16/conv4/conv4_1/biases', 'vgg_16/conv4/conv4_2/weights', 'vgg_16/conv4/conv4_2/biases', 'vgg_16/conv4/conv4_3/weights', 'vgg_16/conv4/conv4_3/biases', 'vgg_16/conv5/conv5_1/weights', 'vgg_16/conv5/conv5_1/biases', 'vgg_16/conv5/conv5_2/weights', 'vgg_16/conv5/conv5_2/biases', 'vgg_16/conv5/conv5_3/weights', 'vgg_16/conv5/conv5_3/biases', 'vgg_16/fc6/weights', 'vgg_16/fc6/biases', 'vgg_16/fc7/weights', 'vgg_16/fc7/biases', 'vgg_16/fc8/weights', 'vgg_16/fc8/biases', ] model_variables = [v.op.name for v in variables_lib.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.cached_session(): eval_inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = math_ops.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.cached_session(): train_inputs = random_ops.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_16(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) variable_scope.get_variable_scope().reuse_variables() eval_inputs = random_ops.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_16( eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = math_ops.reduce_mean(logits, [1, 2]) predictions = math_ops.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.cached_session() as sess: inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs) sess.run(variables.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) class VGG19Test(test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_19/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_19/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 for is_training in [True, False]: with ops.Graph().as_default(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_19(inputs, num_classes, is_training=is_training) expected_names = [ 'vgg_19/conv1/conv1_1', 'vgg_19/conv1/conv1_2', 'vgg_19/pool1', 'vgg_19/conv2/conv2_1', 'vgg_19/conv2/conv2_2', 'vgg_19/pool2', 'vgg_19/conv3/conv3_1', 'vgg_19/conv3/conv3_2', 'vgg_19/conv3/conv3_3', 'vgg_19/conv3/conv3_4', 'vgg_19/pool3', 'vgg_19/conv4/conv4_1', 'vgg_19/conv4/conv4_2', 'vgg_19/conv4/conv4_3', 'vgg_19/conv4/conv4_4', 'vgg_19/pool4', 'vgg_19/conv5/conv5_1', 'vgg_19/conv5/conv5_2', 'vgg_19/conv5/conv5_3', 'vgg_19/conv5/conv5_4', 'vgg_19/pool5', 'vgg_19/fc6', 'vgg_19/fc7', 'vgg_19/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.cached_session(): inputs = random_ops.random_uniform((batch_size, height, width, 3)) vgg.vgg_19(inputs, num_classes) expected_names = [ 'vgg_19/conv1/conv1_1/weights', 'vgg_19/conv1/conv1_1/biases', 'vgg_19/conv1/conv1_2/weights', 'vgg_19/conv1/conv1_2/biases', 'vgg_19/conv2/conv2_1/weights', 'vgg_19/conv2/conv2_1/biases', 'vgg_19/conv2/conv2_2/weights', 'vgg_19/conv2/conv2_2/biases', 'vgg_19/conv3/conv3_1/weights', 'vgg_19/conv3/conv3_1/biases', 'vgg_19/conv3/conv3_2/weights', 'vgg_19/conv3/conv3_2/biases', 'vgg_19/conv3/conv3_3/weights', 'vgg_19/conv3/conv3_3/biases', 'vgg_19/conv3/conv3_4/weights', 'vgg_19/conv3/conv3_4/biases', 'vgg_19/conv4/conv4_1/weights', 'vgg_19/conv4/conv4_1/biases', 'vgg_19/conv4/conv4_2/weights', 'vgg_19/conv4/conv4_2/biases', 'vgg_19/conv4/conv4_3/weights', 'vgg_19/conv4/conv4_3/biases', 'vgg_19/conv4/conv4_4/weights', 'vgg_19/conv4/conv4_4/biases', 'vgg_19/conv5/conv5_1/weights', 'vgg_19/conv5/conv5_1/biases', 'vgg_19/conv5/conv5_2/weights', 'vgg_19/conv5/conv5_2/biases', 'vgg_19/conv5/conv5_3/weights', 'vgg_19/conv5/conv5_3/biases', 'vgg_19/conv5/conv5_4/weights', 'vgg_19/conv5/conv5_4/biases', 'vgg_19/fc6/weights', 'vgg_19/fc6/biases', 'vgg_19/fc7/weights', 'vgg_19/fc7/biases', 'vgg_19/fc8/weights', 'vgg_19/fc8/biases', ] model_variables = [v.op.name for v in variables_lib.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.cached_session(): eval_inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = math_ops.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.cached_session(): train_inputs = random_ops.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_19(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) variable_scope.get_variable_scope().reuse_variables() eval_inputs = random_ops.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_19( eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = math_ops.reduce_mean(logits, [1, 2]) predictions = math_ops.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.cached_session() as sess: inputs = random_ops.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs) sess.run(variables.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) if __name__ == '__main__': test.main()
apache-2.0
zzcclp/spark
python/pyspark/pandas/tests/test_groupby.py
14
118068
# # 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. # import unittest import inspect from distutils.version import LooseVersion from itertools import product import numpy as np import pandas as pd from pyspark import pandas as ps from pyspark.pandas.config import option_context from pyspark.pandas.exceptions import PandasNotImplementedError, DataError from pyspark.pandas.missing.groupby import ( MissingPandasLikeDataFrameGroupBy, MissingPandasLikeSeriesGroupBy, ) from pyspark.pandas.groupby import is_multi_agg_with_relabel from pyspark.testing.pandasutils import PandasOnSparkTestCase, TestUtils class GroupByTest(PandasOnSparkTestCase, TestUtils): def test_groupby_simple(self): pdf = pd.DataFrame( { "a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2], "c": [4, 2, 7, 3, None, 1, 1, 1, 2], "d": list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("a").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("a", as_index=as_index).sum()), sort(pdf.groupby("a", as_index=as_index).sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index).b.sum()), sort(pdf.groupby("a", as_index=as_index).b.sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)["b"].sum()), sort(pdf.groupby("a", as_index=as_index)["b"].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)[["b", "c"]].sum()), sort(pdf.groupby("a", as_index=as_index)[["b", "c"]].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)[[]].sum()), sort(pdf.groupby("a", as_index=as_index)[[]].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)["c"].sum()), sort(pdf.groupby("a", as_index=as_index)["c"].sum()), ) self.assert_eq( psdf.groupby("a").a.sum().sort_index(), pdf.groupby("a").a.sum().sort_index() ) self.assert_eq( psdf.groupby("a")["a"].sum().sort_index(), pdf.groupby("a")["a"].sum().sort_index() ) self.assert_eq( psdf.groupby("a")[["a"]].sum().sort_index(), pdf.groupby("a")[["a"]].sum().sort_index() ) self.assert_eq( psdf.groupby("a")[["a", "c"]].sum().sort_index(), pdf.groupby("a")[["a", "c"]].sum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b).sum().sort_index(), pdf.a.groupby(pdf.b).sum().sort_index() ) for axis in [0, "index"]: self.assert_eq( psdf.groupby("a", axis=axis).a.sum().sort_index(), pdf.groupby("a", axis=axis).a.sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)["a"].sum().sort_index(), pdf.groupby("a", axis=axis)["a"].sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)[["a"]].sum().sort_index(), pdf.groupby("a", axis=axis)[["a"]].sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)[["a", "c"]].sum().sort_index(), pdf.groupby("a", axis=axis)[["a", "c"]].sum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b, axis=axis).sum().sort_index(), pdf.a.groupby(pdf.b, axis=axis).sum().sort_index(), ) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False).a) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)["a"]) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)[["a"]]) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)[["a", "c"]]) self.assertRaises(KeyError, lambda: psdf.groupby("z", as_index=False)[["a", "c"]]) self.assertRaises(KeyError, lambda: psdf.groupby(["z"], as_index=False)[["a", "c"]]) self.assertRaises(TypeError, lambda: psdf.a.groupby(psdf.b, as_index=False)) self.assertRaises(NotImplementedError, lambda: psdf.groupby("a", axis=1)) self.assertRaises(NotImplementedError, lambda: psdf.groupby("a", axis="columns")) self.assertRaises(ValueError, lambda: psdf.groupby("a", "b")) self.assertRaises(TypeError, lambda: psdf.a.groupby(psdf.a, psdf.b)) # we can't use column name/names as a parameter `by` for `SeriesGroupBy`. self.assertRaises(KeyError, lambda: psdf.a.groupby(by="a")) self.assertRaises(KeyError, lambda: psdf.a.groupby(by=["a", "b"])) self.assertRaises(KeyError, lambda: psdf.a.groupby(by=("a", "b"))) # we can't use DataFrame as a parameter `by` for `DataFrameGroupBy`/`SeriesGroupBy`. self.assertRaises(ValueError, lambda: psdf.groupby(psdf)) self.assertRaises(ValueError, lambda: psdf.a.groupby(psdf)) self.assertRaises(ValueError, lambda: psdf.a.groupby((psdf,))) # non-string names pdf = pd.DataFrame( { 10: [1, 2, 6, 4, 4, 6, 4, 3, 7], 20: [4, 2, 7, 3, 3, 1, 1, 1, 2], 30: [4, 2, 7, 3, None, 1, 1, 1, 2], 40: list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(10).reset_index(drop=True) self.assert_eq( sort(psdf.groupby(10, as_index=as_index).sum()), sort(pdf.groupby(10, as_index=as_index).sum()), ) self.assert_eq( sort(psdf.groupby(10, as_index=as_index)[20].sum()), sort(pdf.groupby(10, as_index=as_index)[20].sum()), ) self.assert_eq( sort(psdf.groupby(10, as_index=as_index)[[20, 30]].sum()), sort(pdf.groupby(10, as_index=as_index)[[20, 30]].sum()), ) def test_groupby_multiindex_columns(self): pdf = pd.DataFrame( { (10, "a"): [1, 2, 6, 4, 4, 6, 4, 3, 7], (10, "b"): [4, 2, 7, 3, 3, 1, 1, 1, 2], (20, "c"): [4, 2, 7, 3, None, 1, 1, 1, 2], (30, "d"): list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby((10, "a")).sum().sort_index(), pdf.groupby((10, "a")).sum().sort_index() ) self.assert_eq( psdf.groupby((10, "a"), as_index=False) .sum() .sort_values((10, "a")) .reset_index(drop=True), pdf.groupby((10, "a"), as_index=False) .sum() .sort_values((10, "a")) .reset_index(drop=True), ) self.assert_eq( psdf.groupby((10, "a"))[[(20, "c")]].sum().sort_index(), pdf.groupby((10, "a"))[[(20, "c")]].sum().sort_index(), ) # TODO: a pandas bug? # expected = pdf.groupby((10, "a"))[(20, "c")].sum().sort_index() expected = pd.Series( [4.0, 2.0, 1.0, 4.0, 8.0, 2.0], name=(20, "c"), index=pd.Index([1, 2, 3, 4, 6, 7], name=(10, "a")), ) self.assert_eq(psdf.groupby((10, "a"))[(20, "c")].sum().sort_index(), expected) if ( LooseVersion(pd.__version__) >= LooseVersion("1.0.4") and LooseVersion(pd.__version__) != LooseVersion("1.1.3") and LooseVersion(pd.__version__) != LooseVersion("1.1.4") ): self.assert_eq( psdf[(20, "c")].groupby(psdf[(10, "a")]).sum().sort_index(), pdf[(20, "c")].groupby(pdf[(10, "a")]).sum().sort_index(), ) else: # Due to pandas bugs resolved in 1.0.4, re-introduced in 1.1.3 and resolved in 1.1.5 self.assert_eq(psdf[(20, "c")].groupby(psdf[(10, "a")]).sum().sort_index(), expected) def test_split_apply_combine_on_series(self): pdf = pd.DataFrame( { "a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2], "c": [4, 2, 7, 3, None, 1, 1, 1, 2], "d": list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) funcs = [ ((True, False), ["sum", "min", "max", "count", "first", "last"]), ((True, True), ["mean"]), ((False, False), ["var", "std"]), ] funcs = [(check_exact, almost, f) for (check_exact, almost), fs in funcs for f in fs] for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(list(df.columns)).reset_index(drop=True) for check_exact, almost, func in funcs: for kkey, pkey in [("b", "b"), (psdf.b, pdf.b)]: with self.subTest(as_index=as_index, func=func, key=pkey): if as_index is True or func != "std": self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) else: # seems like a pandas' bug for as_index=False and func == "std"? self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(pdf.groupby(pkey, as_index=True).a.std().reset_index()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(pdf.groupby(pkey, as_index=True).std().reset_index()), check_exact=check_exact, almost=almost, ) for kkey, pkey in [(psdf.b + 1, pdf.b + 1), (psdf.copy().b, pdf.copy().b)]: with self.subTest(as_index=as_index, func=func, key=pkey): self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) for check_exact, almost, func in funcs: for i in [0, 4, 7]: with self.subTest(as_index=as_index, func=func, i=i): self.assert_eq( sort(getattr(psdf.groupby(psdf.b > i, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pdf.b > i, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(psdf.b > i, as_index=as_index), func)()), sort(getattr(pdf.groupby(pdf.b > i, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) for check_exact, almost, func in funcs: for kkey, pkey in [ (psdf.b, pdf.b), (psdf.b + 1, pdf.b + 1), (psdf.copy().b, pdf.copy().b), (psdf.b.rename(), pdf.b.rename()), ]: with self.subTest(func=func, key=pkey): self.assert_eq( getattr(psdf.a.groupby(kkey), func)().sort_index(), getattr(pdf.a.groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr((psdf.a + 1).groupby(kkey), func)().sort_index(), getattr((pdf.a + 1).groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr((psdf.b + 1).groupby(kkey), func)().sort_index(), getattr((pdf.b + 1).groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr(psdf.a.rename().groupby(kkey), func)().sort_index(), getattr(pdf.a.rename().groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) def test_aggregate(self): pdf = pd.DataFrame( {"A": [1, 1, 2, 2], "B": [1, 2, 3, 4], "C": [0.362, 0.227, 1.267, -0.562]} ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(list(df.columns)).reset_index(drop=True) for kkey, pkey in [("A", "A"), (psdf.A, pdf.A)]: with self.subTest(as_index=as_index, key=pkey): self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg("sum")), sort(pdf.groupby(pkey, as_index=as_index).agg("sum")), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg({"B": "min", "C": "sum"})), sort(pdf.groupby(pkey, as_index=as_index).agg({"B": "min", "C": "sum"})), ) self.assert_eq( sort( psdf.groupby(kkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), sort( pdf.groupby(pkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), ) if as_index: self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=as_index).agg(["sum"])), ) else: # seems like a pandas' bug for as_index=False and func_or_funcs is list? self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=True).agg(["sum"]).reset_index()), ) for kkey, pkey in [(psdf.A + 1, pdf.A + 1), (psdf.copy().A, pdf.copy().A)]: with self.subTest(as_index=as_index, key=pkey): self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg("sum")), sort(pdf.groupby(pkey, as_index=as_index).agg("sum")), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg({"B": "min", "C": "sum"})), sort(pdf.groupby(pkey, as_index=as_index).agg({"B": "min", "C": "sum"})), ) self.assert_eq( sort( psdf.groupby(kkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), sort( pdf.groupby(pkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=as_index).agg(["sum"])), ) expected_error_message = ( r"aggs must be a dict mapping from column name to aggregate functions " r"\(string or list of strings\)." ) with self.assertRaisesRegex(ValueError, expected_error_message): psdf.groupby("A", as_index=as_index).agg(0) # multi-index columns columns = pd.MultiIndex.from_tuples([(10, "A"), (10, "B"), (20, "C")]) pdf.columns = columns psdf.columns = columns for as_index in [True, False]: stats_psdf = psdf.groupby((10, "A"), as_index=as_index).agg( {(10, "B"): "min", (20, "C"): "sum"} ) stats_pdf = pdf.groupby((10, "A"), as_index=as_index).agg( {(10, "B"): "min", (20, "C"): "sum"} ) self.assert_eq( stats_psdf.sort_values(by=[(10, "B"), (20, "C")]).reset_index(drop=True), stats_pdf.sort_values(by=[(10, "B"), (20, "C")]).reset_index(drop=True), ) stats_psdf = psdf.groupby((10, "A")).agg({(10, "B"): ["min", "max"], (20, "C"): "sum"}) stats_pdf = pdf.groupby((10, "A")).agg({(10, "B"): ["min", "max"], (20, "C"): "sum"}) self.assert_eq( stats_psdf.sort_values( by=[(10, "B", "min"), (10, "B", "max"), (20, "C", "sum")] ).reset_index(drop=True), stats_pdf.sort_values( by=[(10, "B", "min"), (10, "B", "max"), (20, "C", "sum")] ).reset_index(drop=True), ) # non-string names pdf.columns = [10, 20, 30] psdf.columns = [10, 20, 30] for as_index in [True, False]: stats_psdf = psdf.groupby(10, as_index=as_index).agg({20: "min", 30: "sum"}) stats_pdf = pdf.groupby(10, as_index=as_index).agg({20: "min", 30: "sum"}) self.assert_eq( stats_psdf.sort_values(by=[20, 30]).reset_index(drop=True), stats_pdf.sort_values(by=[20, 30]).reset_index(drop=True), ) stats_psdf = psdf.groupby(10).agg({20: ["min", "max"], 30: "sum"}) stats_pdf = pdf.groupby(10).agg({20: ["min", "max"], 30: "sum"}) self.assert_eq( stats_psdf.sort_values(by=[(20, "min"), (20, "max"), (30, "sum")]).reset_index( drop=True ), stats_pdf.sort_values(by=[(20, "min"), (20, "max"), (30, "sum")]).reset_index( drop=True ), ) def test_aggregate_func_str_list(self): # this is test for cases where only string or list is assigned pdf = pd.DataFrame( { "kind": ["cat", "dog", "cat", "dog"], "height": [9.1, 6.0, 9.5, 34.0], "weight": [7.9, 7.5, 9.9, 198.0], } ) psdf = ps.from_pandas(pdf) agg_funcs = ["max", "min", ["min", "max"]] for aggfunc in agg_funcs: # Since in Koalas groupby, the order of rows might be different # so sort on index to ensure they have same output sorted_agg_psdf = psdf.groupby("kind").agg(aggfunc).sort_index() sorted_agg_pdf = pdf.groupby("kind").agg(aggfunc).sort_index() self.assert_eq(sorted_agg_psdf, sorted_agg_pdf) # test on multi index column case pdf = pd.DataFrame( {"A": [1, 1, 2, 2], "B": [1, 2, 3, 4], "C": [0.362, 0.227, 1.267, -0.562]} ) psdf = ps.from_pandas(pdf) columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")]) pdf.columns = columns psdf.columns = columns for aggfunc in agg_funcs: sorted_agg_psdf = psdf.groupby(("X", "A")).agg(aggfunc).sort_index() sorted_agg_pdf = pdf.groupby(("X", "A")).agg(aggfunc).sort_index() self.assert_eq(sorted_agg_psdf, sorted_agg_pdf) @unittest.skipIf(pd.__version__ < "0.25.0", "not supported before pandas 0.25.0") def test_aggregate_relabel(self): # this is to test named aggregation in groupby pdf = pd.DataFrame({"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]}) psdf = ps.from_pandas(pdf) # different agg column, same function agg_pdf = pdf.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")).sort_index() agg_psdf = psdf.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # same agg column, different functions agg_pdf = pdf.groupby("group").agg(b_max=("B", "max"), b_min=("B", "min")).sort_index() agg_psdf = psdf.groupby("group").agg(b_max=("B", "max"), b_min=("B", "min")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # test on NamedAgg agg_pdf = ( pdf.groupby("group").agg(b_max=pd.NamedAgg(column="B", aggfunc="max")).sort_index() ) agg_psdf = ( psdf.groupby("group").agg(b_max=ps.NamedAgg(column="B", aggfunc="max")).sort_index() ) self.assert_eq(agg_psdf, agg_pdf) # test on NamedAgg multi columns aggregation agg_pdf = ( pdf.groupby("group") .agg( b_max=pd.NamedAgg(column="B", aggfunc="max"), b_min=pd.NamedAgg(column="B", aggfunc="min"), ) .sort_index() ) agg_psdf = ( psdf.groupby("group") .agg( b_max=ps.NamedAgg(column="B", aggfunc="max"), b_min=ps.NamedAgg(column="B", aggfunc="min"), ) .sort_index() ) self.assert_eq(agg_psdf, agg_pdf) def test_dropna(self): pdf = pd.DataFrame( {"A": [None, 1, None, 1, 2], "B": [1, 2, 3, None, None], "C": [4, 5, 6, 7, None]} ) psdf = ps.from_pandas(pdf) # pd.DataFrame.groupby with dropna parameter is implemented since pandas 1.1.0 if LooseVersion(pd.__version__) >= LooseVersion("1.1.0"): for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna).std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna).std()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna).B.std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna).B.std()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna)["B"].std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna)["B"].std()), ) self.assert_eq( sort( psdf.groupby("A", as_index=as_index, dropna=dropna).agg( {"B": "min", "C": "std"} ) ), sort( pdf.groupby("A", as_index=as_index, dropna=dropna).agg( {"B": "min", "C": "std"} ) ), ) for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(["A", "B"]).reset_index(drop=True) self.assert_eq( sort( psdf.groupby(["A", "B"], as_index=as_index, dropna=dropna).agg( {"C": ["min", "std"]} ) ), sort( pdf.groupby(["A", "B"], as_index=as_index, dropna=dropna).agg( {"C": ["min", "std"]} ) ), almost=True, ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")]) pdf.columns = columns psdf.columns = columns for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(("X", "A")).reset_index(drop=True) sorted_stats_psdf = sort( psdf.groupby(("X", "A"), as_index=as_index, dropna=dropna).agg( {("X", "B"): "min", ("Y", "C"): "std"} ) ) sorted_stats_pdf = sort( pdf.groupby(("X", "A"), as_index=as_index, dropna=dropna).agg( {("X", "B"): "min", ("Y", "C"): "std"} ) ) self.assert_eq(sorted_stats_psdf, sorted_stats_pdf) else: # Testing dropna=True (pandas default behavior) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=True)["B"].min()), sort(pdf.groupby("A", as_index=as_index)["B"].min()), ) if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(["A", "B"]).reset_index(drop=True) self.assert_eq( sort( psdf.groupby(["A", "B"], as_index=as_index, dropna=True).agg( {"C": ["min", "std"]} ) ), sort(pdf.groupby(["A", "B"], as_index=as_index).agg({"C": ["min", "std"]})), almost=True, ) # Testing dropna=False index = pd.Index([1.0, 2.0, np.nan], name="A") expected = pd.Series([2.0, np.nan, 1.0], index=index, name="B") result = psdf.groupby("A", as_index=True, dropna=False)["B"].min().sort_index() self.assert_eq(expected, result) expected = pd.DataFrame({"A": [1.0, 2.0, np.nan], "B": [2.0, np.nan, 1.0]}) result = ( psdf.groupby("A", as_index=False, dropna=False)["B"] .min() .sort_values("A") .reset_index(drop=True) ) self.assert_eq(expected, result) index = pd.MultiIndex.from_tuples( [(1.0, 2.0), (1.0, None), (2.0, None), (None, 1.0), (None, 3.0)], names=["A", "B"] ) expected = pd.DataFrame( { ("C", "min"): [5.0, 7.0, np.nan, 4.0, 6.0], ("C", "std"): [np.nan, np.nan, np.nan, np.nan, np.nan], }, index=index, ) result = ( psdf.groupby(["A", "B"], as_index=True, dropna=False) .agg({"C": ["min", "std"]}) .sort_index() ) self.assert_eq(expected, result) expected = pd.DataFrame( { ("A", ""): [1.0, 1.0, 2.0, np.nan, np.nan], ("B", ""): [2.0, np.nan, np.nan, 1.0, 3.0], ("C", "min"): [5.0, 7.0, np.nan, 4.0, 6.0], ("C", "std"): [np.nan, np.nan, np.nan, np.nan, np.nan], } ) result = ( psdf.groupby(["A", "B"], as_index=False, dropna=False) .agg({"C": ["min", "std"]}) .sort_values(["A", "B"]) .reset_index(drop=True) ) self.assert_eq(expected, result) def test_describe(self): # support for numeric type, not support for string type yet datas = [] datas.append({"a": [1, 1, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) datas.append({"a": [-1, -1, -3], "b": [-4, -5, -6], "c": [-7, -8, -9]}) datas.append({"a": [0, 0, 0], "b": [0, 0, 0], "c": [0, 8, 0]}) # it is okay if string type column as a group key datas.append({"a": ["a", "a", "c"], "b": [4, 5, 6], "c": [7, 8, 9]}) percentiles = [0.25, 0.5, 0.75] formatted_percentiles = ["25%", "50%", "75%"] non_percentile_stats = ["count", "mean", "std", "min", "max"] for data in datas: pdf = pd.DataFrame(data) psdf = ps.from_pandas(pdf) describe_pdf = pdf.groupby("a").describe().sort_index() describe_psdf = psdf.groupby("a").describe().sort_index() # since the result of percentile columns are slightly difference from pandas, # we should check them separately: non-percentile columns & percentile columns # 1. Check that non-percentile columns are equal. agg_cols = [col.name for col in psdf.groupby("a")._agg_columns] self.assert_eq( describe_psdf.drop(list(product(agg_cols, formatted_percentiles))), describe_pdf.drop(columns=formatted_percentiles, level=1), check_exact=False, ) # 2. Check that percentile columns are equal. # The interpolation argument is yet to be implemented in Koalas. quantile_pdf = pdf.groupby("a").quantile(percentiles, interpolation="nearest") quantile_pdf = quantile_pdf.unstack(level=1).astype(float) self.assert_eq( describe_psdf.drop(list(product(agg_cols, non_percentile_stats))), quantile_pdf.rename(columns="{:.0%}".format, level=1), ) # not support for string type yet datas = [] datas.append({"a": ["a", "a", "c"], "b": ["d", "e", "f"], "c": ["g", "h", "i"]}) datas.append({"a": ["a", "a", "c"], "b": [4, 0, 1], "c": ["g", "h", "i"]}) for data in datas: pdf = pd.DataFrame(data) psdf = ps.from_pandas(pdf) self.assertRaises( NotImplementedError, lambda: psdf.groupby("a").describe().sort_index() ) # multi-index columns pdf = pd.DataFrame({("x", "a"): [1, 1, 3], ("x", "b"): [4, 5, 6], ("y", "c"): [7, 8, 9]}) psdf = ps.from_pandas(pdf) describe_pdf = pdf.groupby(("x", "a")).describe().sort_index() describe_psdf = psdf.groupby(("x", "a")).describe().sort_index() # 1. Check that non-percentile columns are equal. agg_column_labels = [col._column_label for col in psdf.groupby(("x", "a"))._agg_columns] self.assert_eq( describe_psdf.drop( [ tuple(list(label) + [s]) for label, s in product(agg_column_labels, formatted_percentiles) ] ), describe_pdf.drop(columns=formatted_percentiles, level=2), check_exact=False, ) # 2. Check that percentile columns are equal. # The interpolation argument is yet to be implemented in Koalas. quantile_pdf = pdf.groupby(("x", "a")).quantile(percentiles, interpolation="nearest") quantile_pdf = quantile_pdf.unstack(level=1).astype(float) self.assert_eq( describe_psdf.drop( [ tuple(list(label) + [s]) for label, s in product(agg_column_labels, non_percentile_stats) ] ), quantile_pdf.rename(columns="{:.0%}".format, level=2), ) def test_aggregate_relabel_multiindex(self): pdf = pd.DataFrame({"A": [0, 1, 2, 3], "B": [5, 6, 7, 8], "group": ["a", "a", "b", "b"]}) pdf.columns = pd.MultiIndex.from_tuples([("y", "A"), ("y", "B"), ("x", "group")]) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [1, 3]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = pdf.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")).sort_index() agg_psdf = psdf.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # same column, different methods if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [1, 3], "a_min": [0, 2]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = ( pdf.groupby(("x", "group")) .agg(a_max=(("y", "A"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) agg_psdf = ( psdf.groupby(("x", "group")) .agg(a_max=(("y", "A"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) self.assert_eq(agg_pdf, agg_psdf) # different column, different methods if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [6, 8], "a_min": [0, 2]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = ( pdf.groupby(("x", "group")) .agg(a_max=(("y", "B"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) agg_psdf = ( psdf.groupby(("x", "group")) .agg(a_max=(("y", "B"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) self.assert_eq(agg_pdf, agg_psdf) def test_all_any(self): pdf = pd.DataFrame( { "A": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5], "B": [True, True, True, False, False, False, None, True, None, False], } ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).all()), sort(pdf.groupby("A", as_index=as_index).all()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).any()), sort(pdf.groupby("A", as_index=as_index).any()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).all()).B, sort(pdf.groupby("A", as_index=as_index).all()).B, ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).any()).B, sort(pdf.groupby("A", as_index=as_index).any()).B, ) self.assert_eq( psdf.B.groupby(psdf.A).all().sort_index(), pdf.B.groupby(pdf.A).all().sort_index() ) self.assert_eq( psdf.B.groupby(psdf.A).any().sort_index(), pdf.B.groupby(pdf.A).any().sort_index() ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("Y", "B")]) pdf.columns = columns psdf.columns = columns for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(("X", "A")).reset_index(drop=True) self.assert_eq( sort(psdf.groupby(("X", "A"), as_index=as_index).all()), sort(pdf.groupby(("X", "A"), as_index=as_index).all()), ) self.assert_eq( sort(psdf.groupby(("X", "A"), as_index=as_index).any()), sort(pdf.groupby(("X", "A"), as_index=as_index).any()), ) def test_raises(self): psdf = ps.DataFrame( {"a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2]}, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) # test raises with incorrect key self.assertRaises(ValueError, lambda: psdf.groupby([])) self.assertRaises(KeyError, lambda: psdf.groupby("x")) self.assertRaises(KeyError, lambda: psdf.groupby(["a", "x"])) self.assertRaises(KeyError, lambda: psdf.groupby("a")["x"]) self.assertRaises(KeyError, lambda: psdf.groupby("a")["b", "x"]) self.assertRaises(KeyError, lambda: psdf.groupby("a")[["b", "x"]]) def test_nunique(self): pdf = pd.DataFrame( {"a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": [2, 2, 2, 3, 3, 4, 4, 5, 5, 5]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("a").agg({"b": "nunique"}).sort_index(), pdf.groupby("a").agg({"b": "nunique"}).sort_index(), ) if LooseVersion(pd.__version__) < LooseVersion("1.1.0"): expected = ps.DataFrame({"b": [2, 2]}, index=pd.Index([0, 1], name="a")) self.assert_eq(psdf.groupby("a").nunique().sort_index(), expected) self.assert_eq( psdf.groupby("a").nunique(dropna=False).sort_index(), expected, ) else: self.assert_eq( psdf.groupby("a").nunique().sort_index(), pdf.groupby("a").nunique().sort_index() ) self.assert_eq( psdf.groupby("a").nunique(dropna=False).sort_index(), pdf.groupby("a").nunique(dropna=False).sort_index(), ) self.assert_eq( psdf.groupby("a")["b"].nunique().sort_index(), pdf.groupby("a")["b"].nunique().sort_index(), ) self.assert_eq( psdf.groupby("a")["b"].nunique(dropna=False).sort_index(), pdf.groupby("a")["b"].nunique(dropna=False).sort_index(), ) nunique_psdf = psdf.groupby("a", as_index=False).agg({"b": "nunique"}) nunique_pdf = pdf.groupby("a", as_index=False).agg({"b": "nunique"}) self.assert_eq( nunique_psdf.sort_values(["a", "b"]).reset_index(drop=True), nunique_pdf.sort_values(["a", "b"]).reset_index(drop=True), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) < LooseVersion("1.1.0"): expected = ps.DataFrame({("y", "b"): [2, 2]}, index=pd.Index([0, 1], name=("x", "a"))) self.assert_eq( psdf.groupby(("x", "a")).nunique().sort_index(), expected, ) self.assert_eq( psdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), expected, ) else: self.assert_eq( psdf.groupby(("x", "a")).nunique().sort_index(), pdf.groupby(("x", "a")).nunique().sort_index(), ) self.assert_eq( psdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), pdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), ) def test_unique(self): for pdf in [ pd.DataFrame( {"a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": [2, 2, 2, 3, 3, 4, 4, 5, 5, 5]} ), pd.DataFrame( { "a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": ["w", "w", "w", "x", "x", "y", "y", "z", "z", "z"], } ), ]: with self.subTest(pdf=pdf): psdf = ps.from_pandas(pdf) actual = psdf.groupby("a")["b"].unique().sort_index().to_pandas() expect = pdf.groupby("a")["b"].unique().sort_index() self.assert_eq(len(actual), len(expect)) for act, exp in zip(actual, expect): self.assertTrue(sorted(act) == sorted(exp)) def test_value_counts(self): pdf = pd.DataFrame({"A": [1, 2, 2, 3, 3, 3], "B": [1, 1, 2, 3, 3, 3]}, columns=["A", "B"]) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("A")["B"].value_counts().sort_index(), pdf.groupby("A")["B"].value_counts().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].value_counts(sort=True, ascending=False).sort_index(), pdf.groupby("A")["B"].value_counts(sort=True, ascending=False).sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].value_counts(sort=True, ascending=True).sort_index(), pdf.groupby("A")["B"].value_counts(sort=True, ascending=True).sort_index(), ) self.assert_eq( psdf.B.rename().groupby(psdf.A).value_counts().sort_index(), pdf.B.rename().groupby(pdf.A).value_counts().sort_index(), ) self.assert_eq( psdf.B.groupby(psdf.A.rename()).value_counts().sort_index(), pdf.B.groupby(pdf.A.rename()).value_counts().sort_index(), ) self.assert_eq( psdf.B.rename().groupby(psdf.A.rename()).value_counts().sort_index(), pdf.B.rename().groupby(pdf.A.rename()).value_counts().sort_index(), ) def test_size(self): pdf = pd.DataFrame({"A": [1, 2, 2, 3, 3, 3], "B": [1, 1, 2, 3, 3, 3]}) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("A").size().sort_index(), pdf.groupby("A").size().sort_index()) self.assert_eq( psdf.groupby("A")["B"].size().sort_index(), pdf.groupby("A")["B"].size().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].size().sort_index(), pdf.groupby("A")[["B"]].size().sort_index(), ) self.assert_eq( psdf.groupby(["A", "B"]).size().sort_index(), pdf.groupby(["A", "B"]).size().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("Y", "B")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("X", "A")).size().sort_index(), pdf.groupby(("X", "A")).size().sort_index(), ) self.assert_eq( psdf.groupby([("X", "A"), ("Y", "B")]).size().sort_index(), pdf.groupby([("X", "A"), ("Y", "B")]).size().sort_index(), ) def test_diff(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, } ) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("b").diff().sort_index(), pdf.groupby("b").diff().sort_index()) self.assert_eq( psdf.groupby(["a", "b"]).diff().sort_index(), pdf.groupby(["a", "b"]).diff().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].diff().sort_index(), pdf.groupby(["b"])["a"].diff().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "b"]].diff().sort_index(), pdf.groupby(["b"])[["a", "b"]].diff().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).diff().sort_index(), pdf.groupby(pdf.b // 5).diff().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].diff().sort_index(), pdf.groupby(pdf.b // 5)["a"].diff().sort_index(), ) self.assert_eq(psdf.groupby("b").diff().sum(), pdf.groupby("b").diff().sum().astype(int)) self.assert_eq(psdf.groupby(["b"])["a"].diff().sum(), pdf.groupby(["b"])["a"].diff().sum()) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).diff().sort_index(), pdf.groupby(("x", "b")).diff().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).diff().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).diff().sort_index(), ) def test_rank(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("b").rank().sort_index(), pdf.groupby("b").rank().sort_index()) self.assert_eq( psdf.groupby(["a", "b"]).rank().sort_index(), pdf.groupby(["a", "b"]).rank().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].rank().sort_index(), pdf.groupby(["b"])["a"].rank().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].rank().sort_index(), pdf.groupby(["b"])[["a", "c"]].rank().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).rank().sort_index(), pdf.groupby(pdf.b // 5).rank().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].rank().sort_index(), pdf.groupby(pdf.b // 5)["a"].rank().sort_index(), ) self.assert_eq(psdf.groupby("b").rank().sum(), pdf.groupby("b").rank().sum()) self.assert_eq(psdf.groupby(["b"])["a"].rank().sum(), pdf.groupby(["b"])["a"].rank().sum()) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).rank().sort_index(), pdf.groupby(("x", "b")).rank().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).rank().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).rank().sort_index(), ) def test_cumcount(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) for ascending in [True, False]: self.assert_eq( psdf.groupby("b").cumcount(ascending=ascending).sort_index(), pdf.groupby("b").cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).cumcount(ascending=ascending).sort_index(), pdf.groupby(["a", "b"]).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cumcount(ascending=ascending).sort_index(), pdf.groupby(["b"])["a"].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumcount(ascending=ascending).sort_index(), pdf.groupby(["b"])[["a", "c"]].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cumcount(ascending=ascending).sort_index(), pdf.groupby(pdf.b // 5).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cumcount(ascending=ascending).sort_index(), pdf.groupby(pdf.b // 5)["a"].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby("b").cumcount(ascending=ascending).sum(), pdf.groupby("b").cumcount(ascending=ascending).sum(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumcount(ascending=ascending).sort_index(), pdf.a.rename().groupby(pdf.b).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumcount(ascending=ascending).sort_index(), pdf.a.groupby(pdf.b.rename()).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumcount(ascending=ascending).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumcount(ascending=ascending).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns for ascending in [True, False]: self.assert_eq( psdf.groupby(("x", "b")).cumcount(ascending=ascending).sort_index(), pdf.groupby(("x", "b")).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumcount(ascending=ascending).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumcount(ascending=ascending).sort_index(), ) def test_cummin(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cummin().sort_index(), pdf.groupby("b").cummin().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cummin().sort_index(), pdf.groupby(["a", "b"]).cummin().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cummin().sort_index(), pdf.groupby(["b"])["a"].cummin().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cummin().sort_index(), pdf.groupby(["b"])[["a", "c"]].cummin().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cummin().sort_index(), pdf.groupby(pdf.b // 5).cummin().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cummin().sort_index(), pdf.groupby(pdf.b // 5)["a"].cummin().sort_index(), ) self.assert_eq( psdf.groupby("b").cummin().sum().sort_index(), pdf.groupby("b").cummin().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cummin().sort_index(), pdf.a.rename().groupby(pdf.b).cummin().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cummin().sort_index(), pdf.a.groupby(pdf.b.rename()).cummin().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cummin().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cummin().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cummin().sort_index(), pdf.groupby(("x", "b")).cummin().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cummin().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cummin().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cummin()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cummin()) def test_cummax(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cummax().sort_index(), pdf.groupby("b").cummax().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cummax().sort_index(), pdf.groupby(["a", "b"]).cummax().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cummax().sort_index(), pdf.groupby(["b"])["a"].cummax().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cummax().sort_index(), pdf.groupby(["b"])[["a", "c"]].cummax().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cummax().sort_index(), pdf.groupby(pdf.b // 5).cummax().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cummax().sort_index(), pdf.groupby(pdf.b // 5)["a"].cummax().sort_index(), ) self.assert_eq( psdf.groupby("b").cummax().sum().sort_index(), pdf.groupby("b").cummax().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cummax().sort_index(), pdf.a.rename().groupby(pdf.b).cummax().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cummax().sort_index(), pdf.a.groupby(pdf.b.rename()).cummax().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cummax().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cummax().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cummax().sort_index(), pdf.groupby(("x", "b")).cummax().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cummax().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cummax().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cummax()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cummax()) def test_cumsum(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cumsum().sort_index(), pdf.groupby("b").cumsum().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cumsum().sort_index(), pdf.groupby(["a", "b"]).cumsum().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cumsum().sort_index(), pdf.groupby(["b"])["a"].cumsum().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumsum().sort_index(), pdf.groupby(["b"])[["a", "c"]].cumsum().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cumsum().sort_index(), pdf.groupby(pdf.b // 5).cumsum().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cumsum().sort_index(), pdf.groupby(pdf.b // 5)["a"].cumsum().sort_index(), ) self.assert_eq( psdf.groupby("b").cumsum().sum().sort_index(), pdf.groupby("b").cumsum().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumsum().sort_index(), pdf.a.rename().groupby(pdf.b).cumsum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumsum().sort_index(), pdf.a.groupby(pdf.b.rename()).cumsum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumsum().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumsum().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cumsum().sort_index(), pdf.groupby(("x", "b")).cumsum().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumsum().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumsum().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cumsum()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cumsum()) def test_cumprod(self): pdf = pd.DataFrame( { "a": [1, 2, -3, 4, -5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 0, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cumprod().sort_index(), pdf.groupby("b").cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["a", "b"]).cumprod().sort_index(), pdf.groupby(["a", "b"]).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["b"])["a"].cumprod().sort_index(), pdf.groupby(["b"])["a"].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumprod().sort_index(), pdf.groupby(["b"])[["a", "c"]].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(psdf.b // 3).cumprod().sort_index(), pdf.groupby(pdf.b // 3).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(psdf.b // 3)["a"].cumprod().sort_index(), pdf.groupby(pdf.b // 3)["a"].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby("b").cumprod().sum().sort_index(), pdf.groupby("b").cumprod().sum().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumprod().sort_index(), pdf.a.rename().groupby(pdf.b).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumprod().sort_index(), pdf.a.groupby(pdf.b.rename()).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumprod().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumprod().sort_index(), check_exact=False, ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cumprod().sort_index(), pdf.groupby(("x", "b")).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumprod().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumprod().sort_index(), check_exact=False, ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cumprod()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cumprod()) def test_nsmallest(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "c": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "d": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, }, index=np.random.rand(9 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(["a"])["b"].nsmallest(1).sort_values(), pdf.groupby(["a"])["b"].nsmallest(1).sort_values(), ) self.assert_eq( psdf.groupby(["a"])["b"].nsmallest(2).sort_index(), pdf.groupby(["a"])["b"].nsmallest(2).sort_index(), ) self.assert_eq( (psdf.b * 10).groupby(psdf.a).nsmallest(2).sort_index(), (pdf.b * 10).groupby(pdf.a).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a).nsmallest(2).sort_index(), pdf.b.rename().groupby(pdf.a).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.groupby(psdf.a.rename()).nsmallest(2).sort_index(), pdf.b.groupby(pdf.a.rename()).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a.rename()).nsmallest(2).sort_index(), pdf.b.rename().groupby(pdf.a.rename()).nsmallest(2).sort_index(), ) with self.assertRaisesRegex(ValueError, "nsmallest do not support multi-index now"): psdf.set_index(["a", "b"]).groupby(["c"])["d"].nsmallest(1) def test_nlargest(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "c": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "d": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, }, index=np.random.rand(9 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(["a"])["b"].nlargest(1).sort_values(), pdf.groupby(["a"])["b"].nlargest(1).sort_values(), ) self.assert_eq( psdf.groupby(["a"])["b"].nlargest(2).sort_index(), pdf.groupby(["a"])["b"].nlargest(2).sort_index(), ) self.assert_eq( (psdf.b * 10).groupby(psdf.a).nlargest(2).sort_index(), (pdf.b * 10).groupby(pdf.a).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a).nlargest(2).sort_index(), pdf.b.rename().groupby(pdf.a).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.groupby(psdf.a.rename()).nlargest(2).sort_index(), pdf.b.groupby(pdf.a.rename()).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a.rename()).nlargest(2).sort_index(), pdf.b.rename().groupby(pdf.a.rename()).nlargest(2).sort_index(), ) with self.assertRaisesRegex(ValueError, "nlargest do not support multi-index now"): psdf.set_index(["a", "b"]).groupby(["c"])["d"].nlargest(1) def test_fillna(self): pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, } ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("A").fillna(0).sort_index(), pdf.groupby("A").fillna(0).sort_index() ) self.assert_eq( psdf.groupby("A")["C"].fillna(0).sort_index(), pdf.groupby("A")["C"].fillna(0).sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(0).sort_index(), pdf.groupby("A")[["C"]].fillna(0).sort_index(), ) self.assert_eq( psdf.groupby("A").fillna(method="bfill").sort_index(), pdf.groupby("A").fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A")["C"].fillna(method="bfill").sort_index(), pdf.groupby("A")["C"].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(method="bfill").sort_index(), pdf.groupby("A")[["C"]].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A").fillna(method="ffill").sort_index(), pdf.groupby("A").fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby("A")["C"].fillna(method="ffill").sort_index(), pdf.groupby("A")["C"].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(method="ffill").sort_index(), pdf.groupby("A")[["C"]].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5).fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5).fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)["C"].fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5)["C"].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)[["C"]].fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5)[["C"]].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5).fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5).fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)["C"].fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5)["C"].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)[["C"]].fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5)[["C"]].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.C.rename().groupby(psdf.A).fillna(0).sort_index(), pdf.C.rename().groupby(pdf.A).fillna(0).sort_index(), ) self.assert_eq( psdf.C.groupby(psdf.A.rename()).fillna(0).sort_index(), pdf.C.groupby(pdf.A.rename()).fillna(0).sort_index(), ) self.assert_eq( psdf.C.rename().groupby(psdf.A.rename()).fillna(0).sort_index(), pdf.C.rename().groupby(pdf.A.rename()).fillna(0).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("X", "A")).fillna(0).sort_index(), pdf.groupby(("X", "A")).fillna(0).sort_index(), ) self.assert_eq( psdf.groupby(("X", "A")).fillna(method="bfill").sort_index(), pdf.groupby(("X", "A")).fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(("X", "A")).fillna(method="ffill").sort_index(), pdf.groupby(("X", "A")).fillna(method="ffill").sort_index(), ) def test_ffill(self): idx = np.random.rand(4 * 3) pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, }, index=idx, ) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby("A").ffill().sort_index(), pdf.groupby("A").ffill().sort_index().drop("A", 1), ) self.assert_eq( psdf.groupby("A")[["B"]].ffill().sort_index(), pdf.groupby("A")[["B"]].ffill().sort_index().drop("A", 1), ) else: self.assert_eq( psdf.groupby("A").ffill().sort_index(), pdf.groupby("A").ffill().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].ffill().sort_index(), pdf.groupby("A")[["B"]].ffill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].ffill().sort_index(), pdf.groupby("A")["B"].ffill().sort_index() ) self.assert_eq( psdf.groupby("A")["B"].ffill()[idx[6]], pdf.groupby("A")["B"].ffill()[idx[6]] ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby(("X", "A")).ffill().sort_index(), pdf.groupby(("X", "A")).ffill().sort_index().drop(("X", "A"), 1), ) else: self.assert_eq( psdf.groupby(("X", "A")).ffill().sort_index(), pdf.groupby(("X", "A")).ffill().sort_index(), ) def test_bfill(self): idx = np.random.rand(4 * 3) pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, }, index=idx, ) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby("A").bfill().sort_index(), pdf.groupby("A").bfill().sort_index().drop("A", 1), ) self.assert_eq( psdf.groupby("A")[["B"]].bfill().sort_index(), pdf.groupby("A")[["B"]].bfill().sort_index().drop("A", 1), ) else: self.assert_eq( psdf.groupby("A").bfill().sort_index(), pdf.groupby("A").bfill().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].bfill().sort_index(), pdf.groupby("A")[["B"]].bfill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].bfill().sort_index(), pdf.groupby("A")["B"].bfill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].bfill()[idx[6]], pdf.groupby("A")["B"].bfill()[idx[6]] ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby(("X", "A")).bfill().sort_index(), pdf.groupby(("X", "A")).bfill().sort_index().drop(("X", "A"), 1), ) else: self.assert_eq( psdf.groupby(("X", "A")).bfill().sort_index(), pdf.groupby(("X", "A")).bfill().sort_index(), ) @unittest.skipIf(pd.__version__ < "0.24.0", "not supported before pandas 0.24.0") def test_shift(self): pdf = pd.DataFrame( { "a": [1, 1, 2, 2, 3, 3] * 3, "b": [1, 1, 2, 2, 3, 4] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("a").shift().sort_index(), pdf.groupby("a").shift().sort_index() ) # TODO: seems like a pandas' bug when fill_value is not None? # self.assert_eq(psdf.groupby(['a', 'b']).shift(periods=-1, fill_value=0).sort_index(), # pdf.groupby(['a', 'b']).shift(periods=-1, fill_value=0).sort_index()) self.assert_eq( psdf.groupby(["b"])["a"].shift().sort_index(), pdf.groupby(["b"])["a"].shift().sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"])["c"].shift().sort_index(), pdf.groupby(["a", "b"])["c"].shift().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).shift().sort_index(), pdf.groupby(pdf.b // 5).shift().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].shift().sort_index(), pdf.groupby(pdf.b // 5)["a"].shift().sort_index(), ) # TODO: known pandas' bug when fill_value is not None pandas>=1.0.0 # https://github.com/pandas-dev/pandas/issues/31971#issue-565171762 if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): self.assert_eq( psdf.groupby(["b"])[["a", "c"]].shift(periods=-1, fill_value=0).sort_index(), pdf.groupby(["b"])[["a", "c"]].shift(periods=-1, fill_value=0).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).shift().sort_index(), pdf.a.rename().groupby(pdf.b).shift().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).shift().sort_index(), pdf.a.groupby(pdf.b.rename()).shift().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).shift().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).shift().sort_index(), ) self.assert_eq(psdf.groupby("a").shift().sum(), pdf.groupby("a").shift().sum().astype(int)) self.assert_eq( psdf.a.rename().groupby(psdf.b).shift().sum(), pdf.a.rename().groupby(pdf.b).shift().sum(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "a")).shift().sort_index(), pdf.groupby(("x", "a")).shift().sort_index(), ) # TODO: seems like a pandas' bug when fill_value is not None? # self.assert_eq(psdf.groupby([('x', 'a'), ('x', 'b')]).shift(periods=-1, # fill_value=0).sort_index(), # pdf.groupby([('x', 'a'), ('x', 'b')]).shift(periods=-1, # fill_value=0).sort_index()) def test_apply(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").apply(lambda x: x + x.min()).sort_index(), pdf.groupby("b").apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b").apply(len).sort_index(), pdf.groupby("b").apply(len).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"] .apply(lambda x, y, z: x + x.min() + y * z, 10, z=20) .sort_index(), pdf.groupby("b")["a"].apply(lambda x, y, z: x + x.min() + y * z, 10, z=20).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].apply(lambda x: x + x.min()).sort_index(), pdf.groupby("b")[["a"]].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]) .apply(lambda x, y, z: x + x.min() + y + z, 1, z=2) .sort_index(), pdf.groupby(["a", "b"]).apply(lambda x, y, z: x + x.min() + y + z, 1, z=2).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].apply(lambda x: 1).sort_index(), pdf.groupby(["b"])["c"].apply(lambda x: 1).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].apply(len).sort_index(), pdf.groupby(["b"])["c"].apply(len).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)["a"].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].apply(len).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].apply(len).sort_index(), almost=True, ) self.assert_eq( psdf.a.rename().groupby(psdf.b).apply(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), pdf.a.groupby(pdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), ) with self.assertRaisesRegex(TypeError, "int object is not callable"): psdf.groupby("b").apply(1) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).apply(lambda x: 1).sort_index(), pdf.groupby(("x", "b")).apply(lambda x: 1).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).apply(lambda x: x + x.min()).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(("x", "b")).apply(len).sort_index(), pdf.groupby(("x", "b")).apply(len).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).apply(len).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).apply(len).sort_index(), ) def test_apply_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_apply() def test_apply_negative(self): def func(_) -> ps.Series[int]: return pd.Series([1]) with self.assertRaisesRegex(TypeError, "Series as a return type hint at frame groupby"): ps.range(10).groupby("id").apply(func) def test_apply_with_new_dataframe(self): pdf = pd.DataFrame( {"timestamp": [0.0, 0.5, 1.0, 0.0, 0.5], "car_id": ["A", "A", "A", "B", "B"]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), pdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), ) self.assert_eq( psdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), pdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), ) # dataframe with 1000+ records pdf = pd.DataFrame( { "timestamp": [0.0, 0.5, 1.0, 0.0, 0.5] * 300, "car_id": ["A", "A", "A", "B", "B"] * 300, } ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), pdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), ) self.assert_eq( psdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), pdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), ) def test_apply_with_new_dataframe_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_apply_with_new_dataframe() def test_apply_key_handling(self): pdf = pd.DataFrame( {"d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], "v": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("d").apply(sum).sort_index(), pdf.groupby("d").apply(sum).sort_index() ) with ps.option_context("compute.shortcut_limit", 1): self.assert_eq( psdf.groupby("d").apply(sum).sort_index(), pdf.groupby("d").apply(sum).sort_index() ) def test_apply_with_side_effect(self): pdf = pd.DataFrame( {"d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], "v": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]} ) psdf = ps.from_pandas(pdf) acc = ps.utils.default_session().sparkContext.accumulator(0) def sum_with_acc_frame(x) -> ps.DataFrame[np.float64, np.float64]: nonlocal acc acc += 1 return np.sum(x) actual = psdf.groupby("d").apply(sum_with_acc_frame).sort_index() actual.columns = ["d", "v"] self.assert_eq(actual, pdf.groupby("d").apply(sum).sort_index().reset_index(drop=True)) self.assert_eq(acc.value, 2) def sum_with_acc_series(x) -> np.float64: nonlocal acc acc += 1 return np.sum(x) self.assert_eq( psdf.groupby("d")["v"].apply(sum_with_acc_series).sort_index(), pdf.groupby("d")["v"].apply(sum).sort_index().reset_index(drop=True), ) self.assert_eq(acc.value, 4) def test_transform(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b").transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b")["a"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b")[["a"]].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(["a", "b"]).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(["b"])["c"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)["a"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).transform(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), pdf.a.groupby(pdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(("x", "b")).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).transform(lambda x: x + x.min()).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).transform(lambda x: x + x.min()).sort_index(), ) def test_transform_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_transform() def test_filter(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby("b").filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"].filter(lambda x: any(x == 2)).sort_index(), pdf.groupby("b")["a"].filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby("b")[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(["a", "b"]).filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5).filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(pdf["b"] // 5).filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5)["a"].filter(lambda x: any(x == 2)).sort_index(), pdf.groupby(pdf["b"] // 5)["a"].filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5)[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(pdf["b"] // 5)[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).filter(lambda x: any(x == 2)).sort_index(), pdf.a.rename().groupby(pdf.b).filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), pdf.a.groupby(pdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), ) with self.assertRaisesRegex(TypeError, "int object is not callable"): psdf.groupby("b").filter(1) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).filter(lambda x: any(x[("x", "a")] == 2)).sort_index(), pdf.groupby(("x", "b")).filter(lambda x: any(x[("x", "a")] == 2)).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]) .filter(lambda x: any(x[("x", "a")] == 2)) .sort_index(), pdf.groupby([("x", "a"), ("x", "b")]) .filter(lambda x: any(x[("x", "a")] == 2)) .sort_index(), ) def test_idxmax(self): pdf = pd.DataFrame( {"a": [1, 1, 2, 2, 3] * 3, "b": [1, 2, 3, 4, 5] * 3, "c": [5, 4, 3, 2, 1] * 3} ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby(["a"]).idxmax().sort_index(), psdf.groupby(["a"]).idxmax().sort_index() ) self.assert_eq( pdf.groupby(["a"]).idxmax(skipna=False).sort_index(), psdf.groupby(["a"]).idxmax(skipna=False).sort_index(), ) self.assert_eq( pdf.groupby(["a"])["b"].idxmax().sort_index(), psdf.groupby(["a"])["b"].idxmax().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).idxmax().sort_index(), psdf.b.rename().groupby(psdf.a).idxmax().sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).idxmax().sort_index(), psdf.b.groupby(psdf.a.rename()).idxmax().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).idxmax().sort_index(), psdf.b.rename().groupby(psdf.a.rename()).idxmax().sort_index(), ) with self.assertRaisesRegex(ValueError, "idxmax only support one-level index now"): psdf.set_index(["a", "b"]).groupby(["c"]).idxmax() # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).idxmax().sort_index(), psdf.groupby(("x", "a")).idxmax().sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).idxmax(skipna=False).sort_index(), psdf.groupby(("x", "a")).idxmax(skipna=False).sort_index(), ) def test_idxmin(self): pdf = pd.DataFrame( {"a": [1, 1, 2, 2, 3] * 3, "b": [1, 2, 3, 4, 5] * 3, "c": [5, 4, 3, 2, 1] * 3} ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby(["a"]).idxmin().sort_index(), psdf.groupby(["a"]).idxmin().sort_index() ) self.assert_eq( pdf.groupby(["a"]).idxmin(skipna=False).sort_index(), psdf.groupby(["a"]).idxmin(skipna=False).sort_index(), ) self.assert_eq( pdf.groupby(["a"])["b"].idxmin().sort_index(), psdf.groupby(["a"])["b"].idxmin().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).idxmin().sort_index(), psdf.b.rename().groupby(psdf.a).idxmin().sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).idxmin().sort_index(), psdf.b.groupby(psdf.a.rename()).idxmin().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).idxmin().sort_index(), psdf.b.rename().groupby(psdf.a.rename()).idxmin().sort_index(), ) with self.assertRaisesRegex(ValueError, "idxmin only support one-level index now"): psdf.set_index(["a", "b"]).groupby(["c"]).idxmin() # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).idxmin().sort_index(), psdf.groupby(("x", "a")).idxmin().sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).idxmin(skipna=False).sort_index(), psdf.groupby(("x", "a")).idxmin(skipna=False).sort_index(), ) def test_head(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").head(2).sort_index(), psdf.groupby("a").head(2).sort_index() ) self.assert_eq( pdf.groupby("a").head(-2).sort_index(), psdf.groupby("a").head(-2).sort_index() ) self.assert_eq( pdf.groupby("a").head(100000).sort_index(), psdf.groupby("a").head(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(2).sort_index(), psdf.groupby("a")["b"].head(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(-2).sort_index(), psdf.groupby("a")["b"].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].head(100000).sort_index(), psdf.groupby("a")["b"].head(100000).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(2).sort_index(), psdf.groupby("a")[["b"]].head(2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(-2).sort_index(), psdf.groupby("a")[["b"]].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(100000).sort_index(), psdf.groupby("a")[["b"]].head(100000).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2).head(2).sort_index(), psdf.groupby(psdf.a // 2).head(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)["b"].head(2).sort_index(), psdf.groupby(psdf.a // 2)["b"].head(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)[["b"]].head(2).sort_index(), psdf.groupby(psdf.a // 2)[["b"]].head(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).head(2).sort_index(), psdf.b.rename().groupby(psdf.a).head(2).sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).head(2).sort_index(), psdf.b.groupby(psdf.a.rename()).head(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).head(2).sort_index(), psdf.b.rename().groupby(psdf.a.rename()).head(2).sort_index(), ) # multi-index midx = pd.MultiIndex( [["x", "y"], ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]], [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], ) pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5], "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6], }, columns=["a", "b", "c"], index=midx, ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").head(2).sort_index(), psdf.groupby("a").head(2).sort_index() ) self.assert_eq( pdf.groupby("a").head(-2).sort_index(), psdf.groupby("a").head(-2).sort_index() ) self.assert_eq( pdf.groupby("a").head(100000).sort_index(), psdf.groupby("a").head(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(2).sort_index(), psdf.groupby("a")["b"].head(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(-2).sort_index(), psdf.groupby("a")["b"].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].head(100000).sort_index(), psdf.groupby("a")["b"].head(100000).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).head(2).sort_index(), psdf.groupby(("x", "a")).head(2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).head(-2).sort_index(), psdf.groupby(("x", "a")).head(-2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).head(100000).sort_index(), psdf.groupby(("x", "a")).head(100000).sort_index(), ) def test_missing(self): psdf = ps.DataFrame({"a": [1, 2, 3, 4, 5, 6, 7, 8, 9]}) # DataFrameGroupBy functions missing_functions = inspect.getmembers( MissingPandasLikeDataFrameGroupBy, inspect.isfunction ) unsupported_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "unsupported_function" ] for name in unsupported_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.groupby("a"), name)() deprecated_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "deprecated_function" ] for name in deprecated_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.groupby("a"), name)() # SeriesGroupBy functions missing_functions = inspect.getmembers(MissingPandasLikeSeriesGroupBy, inspect.isfunction) unsupported_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "unsupported_function" ] for name in unsupported_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.a.groupby(psdf.a), name)() deprecated_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "deprecated_function" ] for name in deprecated_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.a.groupby(psdf.a), name)() # DataFrameGroupBy properties missing_properties = inspect.getmembers( MissingPandasLikeDataFrameGroupBy, lambda o: isinstance(o, property) ) unsupported_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "unsupported_property" ] for name in unsupported_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.groupby("a"), name) deprecated_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "deprecated_property" ] for name in deprecated_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.groupby("a"), name) # SeriesGroupBy properties missing_properties = inspect.getmembers( MissingPandasLikeSeriesGroupBy, lambda o: isinstance(o, property) ) unsupported_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "unsupported_property" ] for name in unsupported_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.a.groupby(psdf.a), name) deprecated_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "deprecated_property" ] for name in deprecated_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.a.groupby(psdf.a), name) @staticmethod def test_is_multi_agg_with_relabel(): assert is_multi_agg_with_relabel(a="max") is False assert is_multi_agg_with_relabel(a_min=("a", "max"), a_max=("a", "min")) is True def test_get_group(self): pdf = pd.DataFrame( [ ("falcon", "bird", 389.0), ("parrot", "bird", 24.0), ("lion", "mammal", 80.5), ("monkey", "mammal", np.nan), ], columns=["name", "class", "max_speed"], index=[0, 2, 3, 1], ) pdf.columns.name = "Koalas" psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("class").get_group("bird"), pdf.groupby("class").get_group("bird"), ) self.assert_eq( psdf.groupby("class")["name"].get_group("mammal"), pdf.groupby("class")["name"].get_group("mammal"), ) self.assert_eq( psdf.groupby("class")[["name"]].get_group("mammal"), pdf.groupby("class")[["name"]].get_group("mammal"), ) self.assert_eq( psdf.groupby(["class", "name"]).get_group(("mammal", "lion")), pdf.groupby(["class", "name"]).get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby(["class", "name"])["max_speed"].get_group(("mammal", "lion")), pdf.groupby(["class", "name"])["max_speed"].get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby(["class", "name"])[["max_speed"]].get_group(("mammal", "lion")), pdf.groupby(["class", "name"])[["max_speed"]].get_group(("mammal", "lion")), ) self.assert_eq( (psdf.max_speed + 1).groupby(psdf["class"]).get_group("mammal"), (pdf.max_speed + 1).groupby(pdf["class"]).get_group("mammal"), ) self.assert_eq( psdf.groupby("max_speed").get_group(80.5), pdf.groupby("max_speed").get_group(80.5), ) self.assertRaises(KeyError, lambda: psdf.groupby("class").get_group("fish")) self.assertRaises(TypeError, lambda: psdf.groupby("class").get_group(["bird", "mammal"])) self.assertRaises(KeyError, lambda: psdf.groupby("class")["name"].get_group("fish")) self.assertRaises( TypeError, lambda: psdf.groupby("class")["name"].get_group(["bird", "mammal"]) ) self.assertRaises( KeyError, lambda: psdf.groupby(["class", "name"]).get_group(("lion", "mammal")) ) self.assertRaises(ValueError, lambda: psdf.groupby(["class", "name"]).get_group(("lion",))) self.assertRaises( ValueError, lambda: psdf.groupby(["class", "name"]).get_group(("mammal",)) ) self.assertRaises(ValueError, lambda: psdf.groupby(["class", "name"]).get_group("mammal")) # MultiIndex columns pdf.columns = pd.MultiIndex.from_tuples([("A", "name"), ("B", "class"), ("C", "max_speed")]) pdf.columns.names = ["Hello", "Koalas"] psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(("B", "class")).get_group("bird"), pdf.groupby(("B", "class")).get_group("bird"), ) self.assert_eq( psdf.groupby(("B", "class"))[[("A", "name")]].get_group("mammal"), pdf.groupby(("B", "class"))[[("A", "name")]].get_group("mammal"), ) self.assert_eq( psdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal", "lion")), pdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby([("B", "class"), ("A", "name")])[[("C", "max_speed")]].get_group( ("mammal", "lion") ), pdf.groupby([("B", "class"), ("A", "name")])[[("C", "max_speed")]].get_group( ("mammal", "lion") ), ) self.assert_eq( (psdf[("C", "max_speed")] + 1).groupby(psdf[("B", "class")]).get_group("mammal"), (pdf[("C", "max_speed")] + 1).groupby(pdf[("B", "class")]).get_group("mammal"), ) self.assert_eq( psdf.groupby(("C", "max_speed")).get_group(80.5), pdf.groupby(("C", "max_speed")).get_group(80.5), ) self.assertRaises(KeyError, lambda: psdf.groupby(("B", "class")).get_group("fish")) self.assertRaises( TypeError, lambda: psdf.groupby(("B", "class")).get_group(["bird", "mammal"]) ) self.assertRaises( KeyError, lambda: psdf.groupby(("B", "class"))[("A", "name")].get_group("fish") ) self.assertRaises( KeyError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("lion", "mammal")), ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("lion",)), ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal",)) ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group("mammal") ) def test_median(self): psdf = ps.DataFrame( { "a": [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0], "b": [2.0, 3.0, 1.0, 4.0, 6.0, 9.0, 8.0, 10.0, 7.0, 5.0], "c": [3.0, 5.0, 2.0, 5.0, 1.0, 2.0, 6.0, 4.0, 3.0, 6.0], }, columns=["a", "b", "c"], index=[7, 2, 4, 1, 3, 4, 9, 10, 5, 6], ) # DataFrame expected_result = ps.DataFrame( {"b": [2.0, 8.0, 7.0], "c": [3.0, 2.0, 4.0]}, index=pd.Index([1.0, 2.0, 3.0], name="a") ) self.assert_eq(expected_result, psdf.groupby("a").median().sort_index()) # Series expected_result = ps.Series( [2.0, 8.0, 7.0], name="b", index=pd.Index([1.0, 2.0, 3.0], name="a") ) self.assert_eq(expected_result, psdf.groupby("a")["b"].median().sort_index()) with self.assertRaisesRegex(TypeError, "accuracy must be an integer; however"): psdf.groupby("a").median(accuracy="a") def test_tail(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").tail(2).sort_index(), psdf.groupby("a").tail(2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(-2).sort_index(), psdf.groupby("a").tail(-2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(100000).sort_index(), psdf.groupby("a").tail(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(2).sort_index(), psdf.groupby("a")["b"].tail(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(-2).sort_index(), psdf.groupby("a")["b"].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].tail(100000).sort_index(), psdf.groupby("a")["b"].tail(100000).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(2).sort_index(), psdf.groupby("a")[["b"]].tail(2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(-2).sort_index(), psdf.groupby("a")[["b"]].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(100000).sort_index(), psdf.groupby("a")[["b"]].tail(100000).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2).tail(2).sort_index(), psdf.groupby(psdf.a // 2).tail(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)["b"].tail(2).sort_index(), psdf.groupby(psdf.a // 2)["b"].tail(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)[["b"]].tail(2).sort_index(), psdf.groupby(psdf.a // 2)[["b"]].tail(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).tail(2).sort_index(), psdf.b.rename().groupby(psdf.a).tail(2).sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).tail(2).sort_index(), psdf.b.groupby(psdf.a.rename()).tail(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).tail(2).sort_index(), psdf.b.rename().groupby(psdf.a.rename()).tail(2).sort_index(), ) # multi-index midx = pd.MultiIndex( [["x", "y"], ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]], [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], ) pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5], "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6], }, columns=["a", "b", "c"], index=midx, ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").tail(2).sort_index(), psdf.groupby("a").tail(2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(-2).sort_index(), psdf.groupby("a").tail(-2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(100000).sort_index(), psdf.groupby("a").tail(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(2).sort_index(), psdf.groupby("a")["b"].tail(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(-2).sort_index(), psdf.groupby("a")["b"].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].tail(100000).sort_index(), psdf.groupby("a")["b"].tail(100000).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).tail(2).sort_index(), psdf.groupby(("x", "a")).tail(2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).tail(-2).sort_index(), psdf.groupby(("x", "a")).tail(-2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).tail(100000).sort_index(), psdf.groupby(("x", "a")).tail(100000).sort_index(), ) def test_ddof(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) for ddof in (0, 1): # std self.assert_eq( pdf.groupby("a").std(ddof=ddof).sort_index(), psdf.groupby("a").std(ddof=ddof).sort_index(), check_exact=False, ) self.assert_eq( pdf.groupby("a")["b"].std(ddof=ddof).sort_index(), psdf.groupby("a")["b"].std(ddof=ddof).sort_index(), check_exact=False, ) # var self.assert_eq( pdf.groupby("a").var(ddof=ddof).sort_index(), psdf.groupby("a").var(ddof=ddof).sort_index(), check_exact=False, ) self.assert_eq( pdf.groupby("a")["b"].var(ddof=ddof).sort_index(), psdf.groupby("a")["b"].var(ddof=ddof).sort_index(), check_exact=False, ) if __name__ == "__main__": from pyspark.pandas.tests.test_groupby import * # noqa: F401 try: import xmlrunner # type: ignore[import] testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2) except ImportError: testRunner = None unittest.main(testRunner=testRunner, verbosity=2)
apache-2.0