repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991 values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15 values |
|---|---|---|---|---|---|
subutai/nupic.research | projects/transformers/experiments/wide_bert.py | 2 | 8260 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from copy import deepcopy
from .bertitos import tiny_bert_100k
from .sparse_bertitos import tiny_bert_sparse_100k
from .trifecta import (
KDLRRangeTestTrainer,
small_bert_trifecta_100k,
tiny_bert_trifecta_100k,
)
"""
These experiments to widen the BERT model and see the effect on eval/loss after
pre-training. Widening is simply done by setting adjusting the `hidden_size` and
`intermediate` size by some factor. As well, the sparsity is adjusted as best as
possible to keep the same number of on-params between the models.
"""
# Results:
# |--------------------------------------------------------|
# | Model | width | sparsity | on-params | eval loss |
# |:----------:|:------ |:-------- |:---------:|:---------:|
# | Tiny BERT | 1.0x | 80% | 850,510 | 3.578 |
# | Tiny BERT | 1.25x | 84.3% | 842,474 | 3.514 |
# | Tiny BERT | 1.50x | 88% | 865,227 | 3.461 |
# | Tiny BERT | 2.0x | 90.8% | 876,872 | 3.43 |
# | Tiny BERT | 2.0x | 90.83% | 843,781 | 3.469 |
# | Tiny BERT | 4.875x | 97% | 918,441 | 3.409 |
# | Tiny BERT | 4.875x | 97.2% | 834,243 | 3.438 |
# | Small BERT | 1.0 x | 96.95% | 924,208 | 3.317 |
# |--------------------------------------------------------|
#
lr_range_test_args = dict(
max_steps=100,
trainer_class=KDLRRangeTestTrainer,
trainer_mixin_args=dict(
# LR Range Test
min_lr=0.0001,
max_lr=0.05,
test_mode="linear",
# KD
teacher_model_names_or_paths=[
"/mnt/efs/results/pretrained-models/transformers-local/bert_1mi",
],
),
overwrite_output_dir=True,
do_eval=True,
)
# ---------
# Tiny BERT
# ---------
# Bert with layers of 25 percent wider
tiny_bert_125_percent_wide_args = dict(
hidden_size=160,
intermediate_size=640,
sparsity=0.843,
sparsify_all_embeddings=False,
)
# Bert with layers of 12.5 percent wider
tiny_bert_150_percent_wide_args = dict(
hidden_size=192,
intermediate_size=768,
sparsity=0.872,
sparsify_all_embeddings=False,
)
# Bert with layers of 12.5 percent wider
tiny_bert_200_percent_wide_args = dict(
hidden_size=256,
intermediate_size=1024,
sparsity=0.9083,
sparsify_all_embeddings=False,
)
# Bert with layers of 12.5 percent wider
tiny_bert_487_percent_wide_args = dict(
hidden_size=624,
intermediate_size=2496,
sparsify_all_embeddings=False,
)
# Dense Tiny BERT with hidden and intermediate sizes 1.25x bigger.
tiny_bert_125_perc_wide_100k = deepcopy(tiny_bert_100k)
tiny_bert_125_perc_wide_100k["config_kwargs"].update(
**tiny_bert_125_percent_wide_args,
)
# Sparse Tiny BERT with hidden and intermediate sizes 1.25x bigger.
tiny_bert_sparse_125_perc_wide_100k = deepcopy(tiny_bert_sparse_100k)
tiny_bert_sparse_125_perc_wide_100k["config_kwargs"].update(
**tiny_bert_125_percent_wide_args,
)
# Sparse Tiny BERT with hidden and intermediate sizes 1.25x bigger.
# Trained with RigL + KD + OneCycle LR (Trifecta)
tiny_bert_trifecta_125_perc_wide_100k = deepcopy(tiny_bert_trifecta_100k)
tiny_bert_trifecta_125_perc_wide_100k["config_kwargs"].update(
**tiny_bert_125_percent_wide_args,
)
# Sparse Tiny BERT with hidden and intermediate sizes 1.5x bigger.
# Trained with RigL + KD + OneCycle LR (Trifecta)
tiny_bert_trifecta_150_perc_wide_100k = deepcopy(tiny_bert_trifecta_100k)
tiny_bert_trifecta_150_perc_wide_100k["config_kwargs"].update(
**tiny_bert_150_percent_wide_args,
)
# Sparse Tiny BERT with hidden and intermediate sizes 2.0x bigger.
# Trained with RigL + KD + OneCycle LR (Trifecta)
tiny_bert_trifecta_200_perc_wide_100k = deepcopy(tiny_bert_trifecta_100k)
tiny_bert_trifecta_200_perc_wide_100k["config_kwargs"].update(
**tiny_bert_200_percent_wide_args,
)
# Sparse Tiny BERT with hidden and intermediate sizes 4.87x bigger.
# This is the same size in terms of parameters as Small BERT.
# Trained with RigL + KD + OneCycle LR (Trifecta)
tiny_bert_trifecta_487_perc_wide_100k = deepcopy(tiny_bert_trifecta_100k)
tiny_bert_trifecta_487_perc_wide_100k["config_kwargs"].update(
**tiny_bert_487_percent_wide_args,
sparsity=0.97, # this sparsity mimics dense Tiny BERT 1.0x Wide
)
tiny_bert_trifecta_487_perc_wide_100k.update(
# Using batch_size of 16 instead of 128 since we're training on 8 GPUs.
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
)
# This experiment is like the one of the same name above, but it's meant to be
# compared to Small BERT. Thus, it uses the same number of attention heads and
# a comparable number of on-params. As well, the lr is tuned given the slightly
# greater number of params.
# tiny_bert_trifecta_487_perc_wide_100k = deepcopy(tiny_bert_trifecta_100k)
# tiny_bert_trifecta_487_perc_wide_100k["config_kwargs"].update(
# **tiny_bert_487_percent_wide_args,
# # This better mimics Small BERT's architecture. Tiny BERT usually just has 2.
# attention_heads=8,
# # This mimics Small BERT 1.0x Wide at 96.95% sparse
# sparsity=0.972,
# )
# tiny_bert_trifecta_487_perc_wide_100k["trainer_mixin_args"].update(
# # This max_lr is determined by the test below:
# # `tiny_bert_trifecta_487_perc_wide_lr_range_test`
# max_lr=0.011,
# pct_start=0.1,
# )
# tiny_bert_trifecta_487_perc_wide_100k.update(
# # Using batch_size of 16 instead of 128 since we're training on 8 GPUs.
# per_device_train_batch_size=16,
# per_device_eval_batch_size=16,
# )
# This helps decide the max_lr for `tiny_bert_trifecta_487_perc_wide_100k` above.
tiny_bert_trifecta_487_perc_wide_lr_range_test = deepcopy(tiny_bert_trifecta_487_perc_wide_100k) # noqa E501
tiny_bert_trifecta_487_perc_wide_lr_range_test.update(
**lr_range_test_args,
)
# This is a control for Tiny BERT 4.87x Wide
# This Small BERT has the same number of on-params and total params.
small_bert_97_percent_trifecta_100k = deepcopy(small_bert_trifecta_100k)
small_bert_97_percent_trifecta_100k["config_kwargs"].update(
sparsity=0.9695,
sparsify_all_embeddings=False,
)
small_bert_97_percent_trifecta_100k["trainer_mixin_args"].update(
max_lr=0.012,
)
# This helps decide the max_lr for `small_bert_97_percent_trifecta_100k` above.
small_bert_97_percent_trifecta_lr_range_test = deepcopy(small_bert_97_percent_trifecta_100k) # noqa E501
small_bert_97_percent_trifecta_lr_range_test.update(
**lr_range_test_args,
)
CONFIGS = dict(
# Tiny BERT
tiny_bert_125_perc_wide_100k=tiny_bert_125_perc_wide_100k,
tiny_bert_sparse_125_perc_wide_100k=tiny_bert_sparse_125_perc_wide_100k,
tiny_bert_trifecta_125_perc_wide_100k=tiny_bert_trifecta_125_perc_wide_100k,
tiny_bert_trifecta_150_perc_wide_100k=tiny_bert_trifecta_150_perc_wide_100k,
tiny_bert_trifecta_200_perc_wide_100k=tiny_bert_trifecta_200_perc_wide_100k,
tiny_bert_trifecta_487_perc_wide_100k=tiny_bert_trifecta_487_perc_wide_100k,
tiny_bert_trifecta_487_perc_wide_lr_range_test=tiny_bert_trifecta_487_perc_wide_lr_range_test, # noqa E501
# Controls for Tiny BERT
small_bert_97_percent_trifecta_100k=small_bert_97_percent_trifecta_100k,
small_bert_97_percent_trifecta_lr_range_test=small_bert_97_percent_trifecta_lr_range_test, # noqa E501
)
| agpl-3.0 |
ktosiek/spacewalk | backend/server/basePackageUpload.py | 2 | 4302 | #
# Copyright (c) 2008--2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from rhn.UserDictCase import UserDictCase
from spacewalk.common import apache
from spacewalk.common.rhnLog import log_debug
from spacewalk.common.rhnException import rhnFault
class BasePackageUpload:
def __init__(self, req):
self.header_prefix = "X-RHN-Upload"
self.error_header_prefix = 'X-RHN-Upload-Error'
self.prefix = 'rhn/repository'
self.is_source = 0
self.rel_package_path = None
self.package_path = None
self.required_fields = [
"Package-Name",
"Package-Version",
"Package-Release",
"Package-Arch",
"File-Checksum",
"File-Checksum-Type",
]
self.field_data = UserDictCase()
self.org_id = None
def headerParserHandler(self, req):
""" This whole function is ugly as hell. The Auth field in the header used to be required, but now
it must have either the Auth field or the Auth-Session field.
"""
# Initialize the logging
log_debug(3, "Method", req.method)
#Header string. This is what the Auth-Session field will look like in the header.
session_header = "%s-%s" % (self.header_prefix, "Auth-Session")
# legacy rhnpush sends File-MD5sum; translate it into File-Checksum
md5sum_header = "%s-%s" % (self.header_prefix, "File-MD5sum")
if req.headers_in.has_key(md5sum_header):
req.headers_in["%s-%s" % (self.header_prefix, "File-Checksum-Type")] = 'md5'
req.headers_in["%s-%s" % (self.header_prefix, "File-Checksum")] = \
req.headers_in[md5sum_header]
for f in self.required_fields:
hf = "%s-%s" % (self.header_prefix, f)
if not req.headers_in.has_key(hf):
#If the current field is Auth and Auth-Session field isn't present, something is wrong.
if f == "Auth" and not req.headers_in.has_key(session_header):
log_debug(4, "Required field %s missing" % f)
raise rhnFault(500, f)
#The current field is Auth and the Auth-Session field is present, so everything is good.
elif f == "Auth" and req.headers_in.has_key(session_header):
self.field_data["Auth-Session"] = req.headers_in[session_header]
continue
#The current field being looked for isn't the Auth field and it's missing, so something is wrong.
else:
log_debug(4, "Required field %s missing" % f)
raise rhnFault(500, f)
if not (f == "Auth" and not req.headers_in.has_key(hf)):
self.field_data[f] = req.headers_in[hf]
else:
if req.headers_in.has_key(session_header):
self.field_data[f] = req.headers_in[hf]
self.package_name = self.field_data["Package-Name"]
self.package_version = self.field_data["Package-Version"]
self.package_release = self.field_data["Package-Release"]
self.package_arch = self.field_data["Package-Arch"]
self.file_checksum_type = self.field_data["File-Checksum-Type"]
self.file_checksum = self.field_data["File-Checksum"]
#4/18/05 wregglej. if 1051 is in the header's keys, then it's a nosrc package.
self.is_source = (self.package_arch == 'src' or self.package_arch == 'nosrc')
return apache.OK
def handler(self, req):
log_debug(3, "Method", req.method)
return apache.OK
def cleanupHandler(self, req):
return apache.OK
def logHandler(self, req):
return apache.OK
| gpl-2.0 |
Tagar/incubator-airflow | airflow/operators/presto_check_operator.py | 5 | 4689 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.hooks.presto_hook import PrestoHook
from airflow.operators.check_operator import CheckOperator, ValueCheckOperator, IntervalCheckOperator
from airflow.utils.decorators import apply_defaults
class PrestoCheckOperator(CheckOperator):
"""
Performs checks against Presto. The ``PrestoCheckOperator`` expects
a sql query that will return a single row. Each value on that
first row is evaluated using python ``bool`` casting. If any of the
values return ``False`` the check is failed and errors out.
Note that Python bool casting evals the following as ``False``:
* ``False``
* ``0``
* Empty string (``""``)
* Empty list (``[]``)
* Empty dictionary or set (``{}``)
Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if
the count ``== 0``. You can craft much more complex query that could,
for instance, check that the table has the same number of rows as
the source table upstream, or that the count of today's partition is
greater than yesterday's partition, or that a set of metrics are less
than 3 standard deviation for the 7 day average.
This operator can be used as a data quality check in your pipeline, and
depending on where you put it in your DAG, you have the choice to
stop the critical path, preventing from
publishing dubious data, or on the side and receive email alterts
without stopping the progress of the DAG.
:param sql: the sql to be executed
:type sql: string
:param presto_conn_id: reference to the Presto database
:type presto_conn_id: string
"""
@apply_defaults
def __init__(
self, sql,
presto_conn_id='presto_default',
*args, **kwargs):
super(PrestoCheckOperator, self).__init__(sql=sql, *args, **kwargs)
self.presto_conn_id = presto_conn_id
self.sql = sql
def get_db_hook(self):
return PrestoHook(presto_conn_id=self.presto_conn_id)
class PrestoValueCheckOperator(ValueCheckOperator):
"""
Performs a simple value check using sql code.
:param sql: the sql to be executed
:type sql: string
:param presto_conn_id: reference to the Presto database
:type presto_conn_id: string
"""
@apply_defaults
def __init__(
self, sql, pass_value, tolerance=None,
presto_conn_id='presto_default',
*args, **kwargs):
super(PrestoValueCheckOperator, self).__init__(
sql=sql, pass_value=pass_value, tolerance=tolerance,
*args, **kwargs)
self.presto_conn_id = presto_conn_id
def get_db_hook(self):
return PrestoHook(presto_conn_id=self.presto_conn_id)
class PrestoIntervalCheckOperator(IntervalCheckOperator):
"""
Checks that the values of metrics given as SQL expressions are within
a certain tolerance of the ones from days_back before.
:param table: the table name
:type table: str
:param days_back: number of days between ds and the ds we want to check
against. Defaults to 7 days
:type days_back: int
:param metrics_threshold: a dictionary of ratios indexed by metrics
:type metrics_threshold: dict
:param presto_conn_id: reference to the Presto database
:type presto_conn_id: string
"""
@apply_defaults
def __init__(
self, table, metrics_thresholds,
date_filter_column='ds', days_back=-7,
presto_conn_id='presto_default',
*args, **kwargs):
super(PrestoIntervalCheckOperator, self).__init__(
table=table, metrics_thresholds=metrics_thresholds,
date_filter_column=date_filter_column, days_back=days_back,
*args, **kwargs)
self.presto_conn_id = presto_conn_id
def get_db_hook(self):
return PrestoHook(presto_conn_id=self.presto_conn_id)
| apache-2.0 |
nkoech/csacompendium | csacompendium/csa_practice/api/csapractice/csapracticeserializers.py | 1 | 5084 | from csacompendium.csa_practice.models import (
CsaPractice,
CsaTheme,
PracticeLevel,
PracticeType,
)
from csacompendium.utils.hyperlinkedidentity import hyperlinked_identity
from csacompendium.utils.serializersutils import (
FieldMethodSerializer,
get_related_content,
get_related_content_url,
)
from rest_framework.serializers import (
ModelSerializer,
SerializerMethodField
)
from csacompendium.csa_practice.api.researchcsapractice.researchcsapracticeserializers import \
research_csa_practice_serializers
research_csa_practice_serializers = research_csa_practice_serializers()
def csa_practice_serializers():
"""
CSA practice serializers
:return: All CSA practice serializers
:rtype: Object
"""
class CsaPracticeBaseSerializer(ModelSerializer):
"""
Base serializer for DRY implementation.
"""
class Meta:
model = CsaPractice
fields = [
'id',
'practice_code',
'csatheme',
'practicelevel',
'sub_practice_level',
'sub_subpractice_level',
'definition',
'practicetype',
]
class CsaPracticeRelationBaseSerializer(ModelSerializer):
"""
Base serializer for DRY implementation.
"""
csa_theme_url = SerializerMethodField()
practice_level_url = SerializerMethodField()
practice_type_url = SerializerMethodField()
research_relation = SerializerMethodField()
class Meta:
model = CsaPractice
fields = [
'csa_theme_url',
'practice_level_url',
'practice_type_url',
'research_relation',
]
class CsaPracticeFieldMethodSerializer:
"""
Serialize an object based on a provided field
"""
def get_csa_theme_url(self, obj):
"""
Get related content type/object url
:param obj: Current record object
:return: URL to related object
:rtype: String
"""
if obj.csatheme:
return get_related_content_url(CsaTheme, obj.csatheme.id)
def get_practice_level_url(self, obj):
"""
Get related content type/object url
:param obj: Current record object
:return: URL to related object
:rtype: String
"""
if obj.practicelevel:
return get_related_content_url(PracticeLevel, obj.practicelevel.id)
def get_practice_type_url(self, obj):
"""
Get related content type/object url
:param obj: Current record object
:return: URL to related object
:rtype: String
"""
if obj.practicetype:
return get_related_content_url(PracticeType, obj.practicetype.id)
def get_research_relation(self, obj):
"""
Gets research record
:param obj: Current record object
:return: Related research object/record
:rtype: Object/record
"""
request = self.context['request']
ResearchCsaPracticeContentTypeSerializer = research_csa_practice_serializers[
'ResearchCsaPracticeContentTypeSerializer'
]
related_content = get_related_content(
obj, ResearchCsaPracticeContentTypeSerializer, obj.research_csa_practice, request
)
return related_content
class CsaPracticeListSerializer(
CsaPracticeBaseSerializer,
CsaPracticeRelationBaseSerializer,
CsaPracticeFieldMethodSerializer
):
"""
Serialize all records in given fields into an API
"""
url = hyperlinked_identity('csa_practice_api:csa_practice_detail', 'slug')
class Meta:
model = CsaPractice
fields = CsaPracticeBaseSerializer.Meta.fields + ['url', ] + \
CsaPracticeRelationBaseSerializer.Meta.fields
class CsaPracticeDetailSerializer(
CsaPracticeBaseSerializer, CsaPracticeRelationBaseSerializer,
FieldMethodSerializer, CsaPracticeFieldMethodSerializer
):
"""
Serialize single record into an API. This is dependent on fields given.
"""
user = SerializerMethodField()
modified_by = SerializerMethodField()
class Meta:
common_fields = [
'user',
'modified_by',
'last_update',
'time_created',
] + CsaPracticeRelationBaseSerializer.Meta.fields
model = CsaPractice
fields = CsaPracticeBaseSerializer.Meta.fields + common_fields
read_only_fields = ['id', ] + common_fields
return {
'CsaPracticeListSerializer': CsaPracticeListSerializer,
'CsaPracticeDetailSerializer': CsaPracticeDetailSerializer
}
| mit |
jkorell/PTVS | Python/Tests/TestData/DjangoProject/settings.py | 18 | 5380 | # Django settings for DjangoApplication1 project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
from os import environ, path
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': path.join(environ['localappdata'], 'DjangoProjectDatabase.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://example.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '^28avlv8e$sky_08pu926q^+b5&4&5&+ob7ma%v(tn$bg#=&k4'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'DjangoProject.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
path.join(path.dirname(__file__), 'Templates').replace('\\', '/'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'Oar',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| apache-2.0 |
JavierGarciaD/athena | athena/testcases/performance_test.py | 1 | 2286 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# testcases.performance_test.py
'''
@since: 2014-11-25
@author: Javier Garcia
@contact: javier.garcia@bskapital.com
@summary: Tests for the performance module
'''
import unittest
import pandas as pd
import numpy as np
from performance import performance
import math
# pylint: disable=too-many-public-methods
# Nothing I can do here, are Pylint methods
class TestPerformance(unittest.TestCase):
"""
Test the performance measure
"""
def test_create_drowdown1(self):
"""
Test1: non random serie with 3 inflection points
"""
rows = 100
step = 1
values = [100]
inflection1 = 0.15
inflection2 = 0.50
inflection3 = 0.90
for each_row in range(rows - 1):
if each_row < (rows * inflection1):
values.append(values[-1] - step)
elif (each_row >= rows) * inflection1 and \
(each_row < rows) * inflection2:
values.append(values[-1] + step)
elif (each_row >= rows * inflection2) and \
(each_row < rows) * inflection3:
values.append(values[-1] - step)
elif each_row >= rows * inflection3:
values.append(values[-1] + step)
pnl = pd.Series(values, index=np.arange(rows))
result = performance.create_drawdowns(pnl)
expected = (40.0, 49.0)
self.assertEqual(result, expected, 'Drawdown error calculation')
def test_create_sharpe_ratio0(self):
"""
test for correct calculations
"""
simm = [10, 9, 11, 10, 12, 11, 13, 12, 14, 13, 15]
prices = pd.Series(simm)
returns = prices.pct_change()
result = performance.create_sharpe_ratio(returns)
expected = 5.85973697
self.assertAlmostEqual(result, expected)
def test_create_sharpe_ratio1(self):
"""
test for non volatility serie
"""
simm = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
prices = pd.Series(simm)
returns = prices.pct_change()
result = performance.create_sharpe_ratio(returns)
self.assertTrue(math.isnan(result))
| gpl-3.0 |
jnishi/chainer | tests/chainer_tests/test_computational_graph.py | 10 | 8849 | import unittest
import numpy as np
import six
from chainer import computational_graph as c
from chainer import function
from chainer import testing
from chainer import variable
class MockFunction(function.Function):
def __init__(self, n_in, n_out):
self.n_in = n_in
self.n_out = n_out
def forward_cpu(self, xs):
assert len(xs) == self.n_in
return tuple(np.zeros((1, 2)).astype(np.float32)
for _ in six.moves.range(self.n_out))
def backward_cpu(self, xs, gys):
assert len(xs) == self.n_in
assert len(gys) == self.n_out
return tuple(np.zeros_like(xs).astype(np.float32)
for _ in six.moves.range(self.n_in))
def mock_function(xs, n_out):
return MockFunction(len(xs), n_out)(*xs)
def _check(self, outputs, node_num, edge_num):
g = c.build_computational_graph(outputs)
self.assertEqual(len(g.nodes), node_num)
self.assertEqual(len(g.edges), edge_num)
class TestGraphBuilder(unittest.TestCase):
# x-f-y-g-z
def setUp(self):
self.x = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = mock_function((self.x,), 1)
self.z = mock_function((self.y,), 1)
# x
def test_head_variable(self):
_check(self, (self.x, ), 1, 0)
def test_intermediate_variable(self):
# x-f-y
_check(self, (self.y, ), 3, 2)
def test_tail_variable(self):
# x-f-y-g-z
_check(self, (self.z, ), 5, 4)
def test_multiple_outputs(self):
_check(self, (self.x, self.y), 3, 2)
def test_multiple_outputs2(self):
_check(self, (self.x, self.z), 5, 4)
def test_multiple_outputs3(self):
_check(self, (self.y, self.z), 5, 4)
def test_multiple_outputs4(self):
_check(self, (self.x, self.y, self.z), 5, 4)
def test_nontuple_outputs(self):
_check(self, self.z, 5, 4)
def test_raise_array_outputs(self):
with self.assertRaises(TypeError):
c.build_computational_graph(self.z.array)
class TestGraphBuilder2(unittest.TestCase):
# x-f-y1
# \
# g-y2
def setUp(self):
self.x = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y1 = mock_function((self.x,), 1)
self.y2 = mock_function((self.x,), 1)
def test_head_node(self):
_check(self, (self.x, ), 1, 0)
def test_tail_node(self):
_check(self, (self.y1, ), 3, 2)
def test_tail_node2(self):
_check(self, (self.y2, ), 3, 2)
def test_multiple_tails(self):
_check(self, (self.y1, self.y2), 5, 4)
class TestGraphBuilder3(unittest.TestCase):
# x-f-y1
# \
# y2
def setUp(self):
self.x = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y1, self.y2 = mock_function((self.x,), 2)
def test_head_node(self):
_check(self, (self.x, ), 1, 0)
def test_tail_node(self):
_check(self, (self.y1, ), 3, 2)
def test_tail_node2(self):
_check(self, (self.y2, ), 3, 2)
def test_multiple_tails(self):
_check(self, (self.y1, self.y2), 4, 3)
class TestGraphBuilder4(unittest.TestCase):
# x1-f-y
# /
# x2
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x2 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = mock_function((self.x1, self.x2), 1)
def test_head_node1(self):
_check(self, (self.x1, ), 1, 0)
def test_head_node2(self):
_check(self, (self.x2, ), 1, 0)
def test_multiple_heads(self):
_check(self, (self.x1, self.x2), 2, 0)
def test_tail_node(self):
_check(self, (self.y, ), 4, 3)
class TestGraphBuilder5(unittest.TestCase):
def setUp(self):
self.x = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = 2 * self.x
self.f = self.y.creator_node
self.g = c.build_computational_graph((self.y,))
def test_edges(self):
self.assertEqual(len(self.g.edges), 2)
self.assertSetEqual(set(self.g.edges),
{(self.x.node, self.f), (self.f, self.y.node)})
def test_nodes(self):
self.assertEqual(len(self.g.nodes), 3)
self.assertSetEqual(set(self.g.nodes),
{self.x.node, self.f, self.y.node})
class TestGraphBuilder6(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x2 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = self.x1 + self.x2
self.f = self.y.creator_node
self.g = c.build_computational_graph((self.y,))
def test_edges(self):
self.assertEqual(len(self.g.edges), 3)
self.assertSetEqual(set(self.g.edges),
{(self.x1.node, self.f),
(self.x2.node, self.f),
(self.f, self.y.node)})
def test_nodes(self):
self.assertEqual(len(self.g.nodes), 4)
self.assertSetEqual(set(self.g.nodes),
{self.x1.node, self.x2.node, self.f, self.y.node})
class TestGraphBuilder7(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x2 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x3 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = 0.3 * (self.x1 + self.x2) + self.x3
def test_tail_node(self):
_check(self, (self.y, ), 9, 8)
class TestGraphBuilderStylization(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x2 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = self.x1 + self.x2
self.f = self.y.creator_node
self.variable_style = {'label': 'variable_0', 'shape': 'octagon',
'style': 'filled', 'fillcolor': '#E0E0E0'}
self.function_style = {'label': 'function_0', 'shape': 'record',
'style': 'filled', 'fillcolor': '#6495ED'}
self.g = c.build_computational_graph(
(self.y,), variable_style=self.variable_style,
function_style=self.function_style)
def test_dotfile_content(self):
dotfile_content = self.g.dump()
for style in [self.variable_style, self.function_style]:
for key, value in style.items():
self.assertIn('{0}="{1}"'.format(key, value), dotfile_content)
def test_unsupported_format(self):
with self.assertRaises(NotImplementedError):
self.g.dump('graphml')
class TestGraphBuilderShowName(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(
np.zeros((1, 2)).astype(np.float32), name='x1')
self.x2 = variable.Variable(
np.zeros((1, 2)).astype(np.float32), name='x2')
self.y = self.x1 + self.x2
self.y.name = 'y'
def test_show_name(self):
g = c.build_computational_graph((self.x1, self.x2, self.y))
dotfile_content = g.dump()
for var in [self.x1, self.x2, self.y]:
self.assertIn('label="%s:' % var.name, dotfile_content)
def test_dont_show_name(self):
g = c.build_computational_graph(
(self.x1, self.x2, self.y), show_name=False)
dotfile_content = g.dump()
for var in [self.x1, self.x2, self.y]:
self.assertNotIn('label="%s:' % var.name, dotfile_content)
class TestGraphBuilderRankdir(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.x2 = variable.Variable(np.zeros((1, 2)).astype(np.float32))
self.y = self.x1 + self.x2
def test_randir(self):
for rankdir in ['TB', 'BT', 'LR', 'RL']:
g = c.build_computational_graph((self.y,), rankdir=rankdir)
self.assertIn('rankdir=%s' % rankdir, g.dump())
def test_randir_invalid(self):
self.assertRaises(ValueError,
c.build_computational_graph, (self.y,), rankdir='TL')
class TestGraphBuilderRemoveVariable(unittest.TestCase):
def setUp(self):
self.x1 = variable.Variable(np.zeros((1, 2)).astype('f'))
self.x2 = variable.Variable(np.zeros((1, 2)).astype('f'))
self.y = self.x1 + self.x2
self.f = self.y.creator_node
self.g = c.build_computational_graph((self.y,), remove_variable=True)
def test_remove_variable(self):
self.assertIn(self.f.label, self.g.dump())
self.assertNotIn(str(id(self.x1)), self.g.dump())
self.assertNotIn(str(id(self.x2)), self.g.dump())
testing.run_module(__name__, __file__)
| mit |
acuicultor/Radioactive-kernel-HAM | tools/perf/scripts/python/failed-syscalls-by-pid.py | 11180 | 2058 | # failed system call counts, by pid
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide failed system call totals, broken down by pid.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_error_totals()
def raw_syscalls__sys_exit(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, ret):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
if ret < 0:
try:
syscalls[common_comm][common_pid][id][ret] += 1
except TypeError:
syscalls[common_comm][common_pid][id][ret] = 1
def print_error_totals():
if for_comm is not None:
print "\nsyscall errors for %s:\n\n" % (for_comm),
else:
print "\nsyscall errors:\n\n",
print "%-30s %10s\n" % ("comm [pid]", "count"),
print "%-30s %10s\n" % ("------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id in id_keys:
print " syscall: %-16s\n" % syscall_name(id),
ret_keys = syscalls[comm][pid][id].keys()
for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True):
print " err = %-20s %10d\n" % (strerror(ret), val),
| gpl-2.0 |
ceb8/astroquery | astroquery/esa/xmm_newton/tests/dummy_handler.py | 2 | 2055 | """
@author: Elena Colomo
@contact: ecolomo@esa.int
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 4 Sept. 2019
"""
__all__ = ['DummyHandler']
class DummyHandler:
def __init__(self, method, parameters):
self._invokedMethod = method
self._parameters = parameters
def reset(self):
self._parameters = {}
self._invokedMethod = None
def check_call(self, method_name, parameters):
self.check_method(method_name)
self.check_parameters(parameters, method_name)
def check_method(self, method):
if method == self._invokedMethod:
return
else:
raise ValueError("Method '{}' is not invoked. (Invoked method \
is '{}'.)").format(method, self._invokedMethod)
def check_parameters(self, parameters, method_name):
if parameters is None:
return len(self._parameters) == 0
if len(parameters) != len(self._parameters):
raise ValueError("Wrong number of parameters for method '{}'. \
Found: {}. Expected {}").format(
method_name,
len(self._parameters),
len(parameters))
for key in parameters:
if key in self._parameters:
# check value
if self._parameters[key] != parameters[key]:
raise ValueError("Wrong '{}' parameter \
value for method '{}'. \
Found:'{}'. Expected:'{}'").format(
method_name,
key,
self._parameters[key],
parameters[key])
else:
raise ValueError("Parameter '%s' not found in method '%s'",
(str(key), method_name))
return True
| bsd-3-clause |
michelts/lettuce | tests/integration/lib/Django-1.3/django/contrib/gis/db/backends/spatialite/creation.py | 178 | 4393 | import os
from django.conf import settings
from django.core.cache import get_cache
from django.core.cache.backends.db import BaseDatabaseCache
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.db.backends.sqlite3.creation import DatabaseCreation
class SpatiaLiteCreation(DatabaseCreation):
def create_test_db(self, verbosity=1, autoclobber=False):
"""
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
This method is overloaded to load up the SpatiaLite initialization
SQL prior to calling the `syncdb` command.
"""
if verbosity >= 1:
print "Creating test database '%s'..." % self.connection.alias
test_database_name = self._create_test_db(verbosity, autoclobber)
self.connection.close()
self.connection.settings_dict["NAME"] = test_database_name
# Confirm the feature set of the test database
self.connection.features.confirm()
# Need to load the SpatiaLite initialization SQL before running `syncdb`.
self.load_spatialite_sql()
call_command('syncdb', verbosity=verbosity, interactive=False, database=self.connection.alias)
for cache_alias in settings.CACHES:
cache = get_cache(cache_alias)
if isinstance(cache, BaseDatabaseCache):
from django.db import router
if router.allow_syncdb(self.connection.alias, cache.cache_model_class):
call_command('createcachetable', cache._table, database=self.connection.alias)
# Get a cursor (even though we don't need one yet). This has
# the side effect of initializing the test database.
cursor = self.connection.cursor()
return test_database_name
def sql_indexes_for_field(self, model, f, style):
"Return any spatial index creation SQL for the field."
from django.contrib.gis.db.models.fields import GeometryField
output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style)
if isinstance(f, GeometryField):
gqn = self.connection.ops.geo_quote_name
qn = self.connection.ops.quote_name
db_table = model._meta.db_table
output.append(style.SQL_KEYWORD('SELECT ') +
style.SQL_TABLE('AddGeometryColumn') + '(' +
style.SQL_TABLE(gqn(db_table)) + ', ' +
style.SQL_FIELD(gqn(f.column)) + ', ' +
style.SQL_FIELD(str(f.srid)) + ', ' +
style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' +
style.SQL_KEYWORD(str(f.dim)) + ', ' +
style.SQL_KEYWORD(str(int(not f.null))) +
');')
if f.spatial_index:
output.append(style.SQL_KEYWORD('SELECT ') +
style.SQL_TABLE('CreateSpatialIndex') + '(' +
style.SQL_TABLE(gqn(db_table)) + ', ' +
style.SQL_FIELD(gqn(f.column)) + ');')
return output
def load_spatialite_sql(self):
"""
This routine loads up the SpatiaLite SQL file.
"""
# Getting the location of the SpatiaLite SQL file, and confirming
# it exists.
spatialite_sql = self.spatialite_init_file()
if not os.path.isfile(spatialite_sql):
raise ImproperlyConfigured('Could not find the required SpatiaLite initialization '
'SQL file (necessary for testing): %s' % spatialite_sql)
# Opening up the SpatiaLite SQL initialization file and executing
# as a script.
sql_fh = open(spatialite_sql, 'r')
try:
cur = self.connection._cursor()
cur.executescript(sql_fh.read())
finally:
sql_fh.close()
def spatialite_init_file(self):
# SPATIALITE_SQL may be placed in settings to tell GeoDjango
# to use a specific path to the SpatiaLite initilization SQL.
return getattr(settings, 'SPATIALITE_SQL',
'init_spatialite-%s.%s.sql' %
self.connection.ops.spatial_version[:2])
| gpl-3.0 |
nkmk/python-snippets | notebook/numpy_matrix_eig.py | 1 | 1301 | import numpy as np
arr = np.array([[8, 1], [4, 5]])
w, v = np.linalg.eig(arr)
print(w)
# [9. 4.]
print(v)
# [[ 0.70710678 -0.24253563]
# [ 0.70710678 0.9701425 ]]
print('value: ', w[0])
print('vector: ', v[:, 0] / v[0, 0])
# value: 9.0
# vector: [1. 1.]
print(w[np.argmax(w)])
print(v[:, np.argmax(w)])
# 9.0
# [0.70710678 0.70710678]
def get_eigenpairs(arr):
w, v = np.linalg.eig(arr)
eigenpairs = []
for i, val in enumerate(w):
vec = v[:, i] / np.min(np.abs(v[:, i][v[:, i] != 0]))
eigenpairs.append((val, vec))
return eigenpairs
eigenpairs = get_eigenpairs(arr)
for val, vec in eigenpairs:
print('value: {}, vector: {}'.format(val, vec))
# value: 9.0, vector: [1. 1.]
# value: 4.0, vector: [-1. 4.]
arr = np.array([[1, 1, 2], [0, 2, -1], [0, 0, 3]])
eigenpairs = get_eigenpairs(arr)
for val, vec in eigenpairs:
print('value: {}, vector: {}'.format(val, vec))
# value: 1.0, vector: [1. 0. 0.]
# value: 2.0, vector: [1. 1. 0.]
# value: 3.0, vector: [ 1. -2. 2.]
arr = np.array([[3, 2], [-2, 3]])
eigenpairs = get_eigenpairs(arr)
for val, vec in eigenpairs:
print('value: {}, vector: {}'.format(val, vec))
# value: (3+2.0000000000000004j), vector: [0.-1.j 1.+0.j]
# value: (3-2.0000000000000004j), vector: [0.+1.j 1.-0.j]
| mit |
analyseuc3m/ANALYSE-v1 | lms/djangoapps/mobile_api/course_info/tests.py | 3 | 8039 | """
Tests for course_info
"""
import ddt
from django.conf import settings
from xmodule.html_module import CourseInfoModule
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.xml_importer import import_course_from_xml
from milestones.tests.utils import MilestonesTestCaseMixin
from ..testutils import (
MobileAPITestCase, MobileCourseAccessTestMixin, MobileAuthTestMixin
)
@ddt.ddt
class TestUpdates(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTestMixin, MilestonesTestCaseMixin):
"""
Tests for /api/mobile/v0.5/course_info/{course_id}/updates
"""
REVERSE_INFO = {'name': 'course-updates-list', 'params': ['course_id']}
def verify_success(self, response):
super(TestUpdates, self).verify_success(response)
self.assertEqual(response.data, [])
@ddt.data(True, False)
def test_updates(self, new_format):
"""
Tests updates endpoint with /static in the content.
Tests both new updates format (using "items") and old format (using "data").
"""
self.login_and_enroll()
# create course Updates item in modulestore
updates_usage_key = self.course.id.make_usage_key('course_info', 'updates')
course_updates = modulestore().create_item(
self.user.id,
updates_usage_key.course_key,
updates_usage_key.block_type,
block_id=updates_usage_key.block_id
)
# store content in Updates item (either new or old format)
num_updates = 3
if new_format:
for num in range(1, num_updates + 1):
course_updates.items.append(
{
"id": num,
"date": "Date" + str(num),
"content": "<a href=\"/static/\">Update" + str(num) + "</a>",
"status": CourseInfoModule.STATUS_VISIBLE
}
)
else:
update_data = ""
# old format stores the updates with the newest first
for num in range(num_updates, 0, -1):
update_data += "<li><h2>Date" + str(num) + "</h2><a href=\"/static/\">Update" + str(num) + "</a></li>"
course_updates.data = u"<ol>" + update_data + "</ol>"
modulestore().update_item(course_updates, self.user.id)
# call API
response = self.api_response()
# verify static URLs are replaced in the content returned by the API
self.assertNotIn("\"/static/", response.content)
# verify static URLs remain in the underlying content
underlying_updates = modulestore().get_item(updates_usage_key)
underlying_content = underlying_updates.items[0]['content'] if new_format else underlying_updates.data
self.assertIn("\"/static/", underlying_content)
# verify content and sort order of updates (most recent first)
for num in range(1, num_updates + 1):
update_data = response.data[num_updates - num]
self.assertEquals(num, update_data['id'])
self.assertEquals("Date" + str(num), update_data['date'])
self.assertIn("Update" + str(num), update_data['content'])
@ddt.ddt
class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTestMixin, MilestonesTestCaseMixin):
"""
Tests for /api/mobile/v0.5/course_info/{course_id}/handouts
"""
REVERSE_INFO = {'name': 'course-handouts-list', 'params': ['course_id']}
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_handouts(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
response = self.api_response(expected_response_code=200)
self.assertIn("Sample", response.data['handouts_html'])
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_no_handouts(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
# delete handouts in course
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.course.id):
self.store.delete_item(handouts_usage_key, self.user.id)
response = self.api_response(expected_response_code=200)
self.assertIsNone(response.data['handouts_html'])
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_empty_handouts(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
# set handouts to empty tags
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
underlying_handouts = self.store.get_item(handouts_usage_key)
underlying_handouts.data = "<ol></ol>"
self.store.update_item(underlying_handouts, self.user.id)
response = self.api_response(expected_response_code=200)
self.assertIsNone(response.data['handouts_html'])
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_handouts_static_rewrites(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
# check that we start with relative static assets
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
underlying_handouts = self.store.get_item(handouts_usage_key)
self.assertIn('\'/static/', underlying_handouts.data)
# but shouldn't finish with any
response = self.api_response()
self.assertNotIn('\'/static/', response.data['handouts_html'])
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_jump_to_id_handout_href(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
# check that we start with relative static assets
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
underlying_handouts = self.store.get_item(handouts_usage_key)
underlying_handouts.data = "<a href=\"/jump_to_id/identifier\">Intracourse Link</a>"
self.store.update_item(underlying_handouts, self.user.id)
# but shouldn't finish with any
response = self.api_response()
self.assertIn("/courses/{}/jump_to_id/".format(self.course.id), response.data['handouts_html'])
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_course_url_handout_href(self, default_ms):
with self.store.default_store(default_ms):
self.add_mobile_available_toy_course()
# check that we start with relative static assets
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
underlying_handouts = self.store.get_item(handouts_usage_key)
underlying_handouts.data = "<a href=\"/course/identifier\">Linked Content</a>"
self.store.update_item(underlying_handouts, self.user.id)
# but shouldn't finish with any
response = self.api_response()
self.assertIn("/courses/{}/".format(self.course.id), response.data['handouts_html'])
def add_mobile_available_toy_course(self):
""" use toy course with handouts, and make it mobile_available """
course_items = import_course_from_xml(
self.store, self.user.id,
settings.COMMON_TEST_DATA_ROOT, ['toy'],
create_if_not_present=True
)
self.course = course_items[0]
self.course.mobile_available = True
self.store.update_item(self.course, self.user.id)
self.login_and_enroll()
| agpl-3.0 |
toanalien/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py | 115 | 26224 | # Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import StringIO
from webkitpy.common.checkout.scm import CheckoutNeedsUpdate
from webkitpy.common.checkout.scm.scm_mock import MockSCM
from webkitpy.common.net.bugzilla import Attachment
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.layout_tests.models import test_results
from webkitpy.layout_tests.models import test_failures
from webkitpy.thirdparty.mock import Mock
from webkitpy.tool.commands.commandtest import CommandsTest
from webkitpy.tool.commands.queues import *
from webkitpy.tool.commands.queuestest import QueuesTest
from webkitpy.tool.commands.stepsequence import StepSequence
from webkitpy.common.net.statusserver_mock import MockStatusServer
from webkitpy.tool.mocktool import MockTool, MockOptions
class TestCommitQueue(CommitQueue):
def __init__(self, tool=None):
CommitQueue.__init__(self)
if tool:
self.bind_to_tool(tool)
self._options = MockOptions(confirm=False, parent_command="commit-queue", port=None)
def begin_work_queue(self):
output_capture = OutputCapture()
output_capture.capture_output()
CommitQueue.begin_work_queue(self)
output_capture.restore_output()
class TestQueue(AbstractPatchQueue):
name = "test-queue"
class TestReviewQueue(AbstractReviewQueue):
name = "test-review-queue"
class TestFeederQueue(FeederQueue):
_sleep_duration = 0
class AbstractQueueTest(CommandsTest):
def test_log_directory(self):
self.assertEqual(TestQueue()._log_directory(), os.path.join("..", "test-queue-logs"))
def _assert_run_webkit_patch(self, run_args, port=None):
queue = TestQueue()
tool = MockTool()
tool.status_server.bot_id = "gort"
tool.executive = Mock()
queue.bind_to_tool(tool)
queue._options = Mock()
queue._options.port = port
queue.run_webkit_patch(run_args)
expected_run_args = ["echo", "--status-host=example.com", "--bot-id=gort"]
if port:
expected_run_args.append("--port=%s" % port)
expected_run_args.extend(run_args)
tool.executive.run_command.assert_called_with(expected_run_args, cwd='/mock-checkout')
def test_run_webkit_patch(self):
self._assert_run_webkit_patch([1])
self._assert_run_webkit_patch(["one", 2])
self._assert_run_webkit_patch([1], port="mockport")
def test_iteration_count(self):
queue = TestQueue()
queue._options = Mock()
queue._options.iterations = 3
self.assertTrue(queue.should_continue_work_queue())
self.assertTrue(queue.should_continue_work_queue())
self.assertTrue(queue.should_continue_work_queue())
self.assertFalse(queue.should_continue_work_queue())
def test_no_iteration_count(self):
queue = TestQueue()
queue._options = Mock()
self.assertTrue(queue.should_continue_work_queue())
self.assertTrue(queue.should_continue_work_queue())
self.assertTrue(queue.should_continue_work_queue())
self.assertTrue(queue.should_continue_work_queue())
def _assert_log_message(self, script_error, log_message):
failure_log = AbstractQueue._log_from_script_error_for_upload(script_error, output_limit=10)
self.assertTrue(failure_log.read(), log_message)
def test_log_from_script_error_for_upload(self):
self._assert_log_message(ScriptError("test"), "test")
unicode_tor = u"WebKit \u2661 Tor Arne Vestb\u00F8!"
utf8_tor = unicode_tor.encode("utf-8")
self._assert_log_message(ScriptError(unicode_tor), utf8_tor)
script_error = ScriptError(unicode_tor, output=unicode_tor)
expected_output = "%s\nLast %s characters of output:\n%s" % (utf8_tor, 10, utf8_tor[-10:])
self._assert_log_message(script_error, expected_output)
class FeederQueueTest(QueuesTest):
def test_feeder_queue(self):
queue = TestFeederQueue()
tool = MockTool(log_executive=True)
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("feeder-queue"),
"process_work_item": """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)
Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)
MOCK setting flag 'commit-queue' to '-' on attachment '10001' with comment 'Rejecting attachment 10001 from commit-queue.\n\nnon-committer@example.com does not have committer permissions according to http://trac.webkit.org/browser/trunk/Tools/Scripts/webkitpy/common/config/committers.py.
- If you do not have committer rights please read http://webkit.org/coding/contributing.html for instructions on how to use bugzilla flags.
- If you have committer rights please correct the error in Tools/Scripts/webkitpy/common/config/committers.py by adding yourself to the file (no review needed). The commit-queue restarts itself every 2 hours. After restart the commit-queue will correctly respect your committer rights.'
MOCK: update_work_items: commit-queue [10005, 10000]
Feeding commit-queue items [10005, 10000]
Feeding EWS (1 r? patch, 1 new)
MOCK: submit_to_ews: 10002
""",
"handle_unexpected_error": "Mock error message\n",
}
self.assert_queue_outputs(queue, tool=tool, expected_logs=expected_logs)
class AbstractPatchQueueTest(CommandsTest):
def test_next_patch(self):
queue = AbstractPatchQueue()
tool = MockTool()
queue.bind_to_tool(tool)
queue._options = Mock()
queue._options.port = None
self.assertIsNone(queue._next_patch())
tool.status_server = MockStatusServer(work_items=[2, 10000, 10001])
expected_stdout = "MOCK: fetch_attachment: 2 is not a known attachment id\n" # A mock-only message to prevent us from making mistakes.
expected_logs = "MOCK: release_work_item: None 2\n"
patch = OutputCapture().assert_outputs(self, queue._next_patch, expected_stdout=expected_stdout, expected_logs=expected_logs)
# The patch.id() == 2 is ignored because it doesn't exist.
self.assertEqual(patch.id(), 10000)
self.assertEqual(queue._next_patch().id(), 10001)
self.assertEqual(queue._next_patch(), None) # When the queue is empty
class PatchProcessingQueueTest(CommandsTest):
def test_upload_results_archive_for_patch(self):
queue = PatchProcessingQueue()
queue.name = "mock-queue"
tool = MockTool()
queue.bind_to_tool(tool)
queue._options = Mock()
queue._options.port = None
patch = queue._tool.bugs.fetch_attachment(10001)
expected_logs = """MOCK add_attachment_to_bug: bug_id=50000, description=Archive of layout-test-results from bot for mac-snowleopard filename=layout-test-results.zip mimetype=None
-- Begin comment --
The attached test failures were seen while running run-webkit-tests on the mock-queue.
Port: mac-snowleopard Platform: MockPlatform 1.0
-- End comment --
"""
OutputCapture().assert_outputs(self, queue._upload_results_archive_for_patch, [patch, Mock()], expected_logs=expected_logs)
class NeedsUpdateSequence(StepSequence):
def _run(self, tool, options, state):
raise CheckoutNeedsUpdate([], 1, "", None)
class AlwaysCommitQueueTool(object):
def __init__(self):
self.status_server = MockStatusServer()
def command_by_name(self, name):
return CommitQueue
class SecondThoughtsCommitQueue(TestCommitQueue):
def __init__(self, tool=None):
self._reject_patch = False
TestCommitQueue.__init__(self, tool)
def run_command(self, command):
# We want to reject the patch after the first validation,
# so wait to reject it until after some other command has run.
self._reject_patch = True
return CommitQueue.run_command(self, command)
def refetch_patch(self, patch):
if not self._reject_patch:
return self._tool.bugs.fetch_attachment(patch.id())
attachment_dictionary = {
"id": patch.id(),
"bug_id": patch.bug_id(),
"name": "Rejected",
"is_obsolete": True,
"is_patch": False,
"review": "-",
"reviewer_email": "foo@bar.com",
"commit-queue": "-",
"committer_email": "foo@bar.com",
"attacher_email": "Contributer1",
}
return Attachment(attachment_dictionary, None)
class CommitQueueTest(QueuesTest):
def _mock_test_result(self, testname):
return test_results.TestResult(testname, [test_failures.FailureTextMismatch()])
def test_commit_queue(self):
tool = MockTool()
tool.filesystem.write_text_file('/tmp/layout-test-results/full_results.json', '') # Otherwise the commit-queue will hit a KeyError trying to read the results from the MockFileSystem.
tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '')
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("commit-queue"),
"process_work_item": """Running: webkit-patch --status-host=example.com clean --port=mac
MOCK: update_status: commit-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update --port=mac
MOCK: update_status: commit-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10000 --port=mac
MOCK: update_status: commit-queue Applied patch
Running: webkit-patch --status-host=example.com validate-changelog --check-oops --non-interactive 10000 --port=mac
MOCK: update_status: commit-queue ChangeLog validated
Running: webkit-patch --status-host=example.com build --no-clean --no-update --build-style=release --port=mac
MOCK: update_status: commit-queue Built patch
Running: webkit-patch --status-host=example.com build-and-test --no-clean --no-update --test --non-interactive --port=mac
MOCK: update_status: commit-queue Passed tests
Running: webkit-patch --status-host=example.com land-attachment --force-clean --non-interactive --parent-command=commit-queue 10000 --port=mac
MOCK: update_status: commit-queue Landed patch
MOCK: update_status: commit-queue Pass
MOCK: release_work_item: commit-queue 10000
""",
"handle_script_error": "ScriptError error message\n\nMOCK output\n",
"handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nMock error message'\n",
}
self.assert_queue_outputs(CommitQueue(), tool=tool, expected_logs=expected_logs)
def test_commit_queue_failure(self):
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("commit-queue"),
"process_work_item": """MOCK: update_status: commit-queue Cleaned working directory
MOCK: update_status: commit-queue Updated working directory
MOCK: update_status: commit-queue Patch does not apply
MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nMOCK script error
Full output: http://dummy_url'
MOCK: update_status: commit-queue Fail
MOCK: release_work_item: commit-queue 10000
""",
"handle_script_error": "ScriptError error message\n\nMOCK output\n",
"handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nMock error message'\n",
}
queue = CommitQueue()
def mock_run_webkit_patch(command):
if command[0] == 'clean' or command[0] == 'update':
# We want cleaning to succeed so we can error out on a step
# that causes the commit-queue to reject the patch.
return
raise ScriptError('MOCK script error')
queue.run_webkit_patch = mock_run_webkit_patch
self.assert_queue_outputs(queue, expected_logs=expected_logs)
def test_commit_queue_failure_with_failing_tests(self):
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("commit-queue"),
"process_work_item": """MOCK: update_status: commit-queue Cleaned working directory
MOCK: update_status: commit-queue Updated working directory
MOCK: update_status: commit-queue Patch does not apply
MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nNew failing tests:
mock_test_name.html
another_test_name.html
Full output: http://dummy_url'
MOCK: update_status: commit-queue Fail
MOCK: release_work_item: commit-queue 10000
""",
"handle_script_error": "ScriptError error message\n\nMOCK output\n",
"handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nMock error message'\n",
}
queue = CommitQueue()
def mock_run_webkit_patch(command):
if command[0] == 'clean' or command[0] == 'update':
# We want cleaning to succeed so we can error out on a step
# that causes the commit-queue to reject the patch.
return
queue._expected_failures.unexpected_failures_observed = lambda results: ["mock_test_name.html", "another_test_name.html"]
raise ScriptError('MOCK script error')
queue.run_webkit_patch = mock_run_webkit_patch
self.assert_queue_outputs(queue, expected_logs=expected_logs)
def test_rollout(self):
tool = MockTool()
tool.filesystem.write_text_file('/tmp/layout-test-results/full_results.json', '') # Otherwise the commit-queue will hit a KeyError trying to read the results from the MockFileSystem.
tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '')
tool.buildbot.light_tree_on_fire()
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("commit-queue"),
"process_work_item": """Running: webkit-patch --status-host=example.com clean --port=%(port)s
MOCK: update_status: commit-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update --port=%(port)s
MOCK: update_status: commit-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10000 --port=%(port)s
MOCK: update_status: commit-queue Applied patch
Running: webkit-patch --status-host=example.com validate-changelog --check-oops --non-interactive 10000 --port=%(port)s
MOCK: update_status: commit-queue ChangeLog validated
Running: webkit-patch --status-host=example.com build --no-clean --no-update --build-style=release --port=%(port)s
MOCK: update_status: commit-queue Built patch
Running: webkit-patch --status-host=example.com build-and-test --no-clean --no-update --test --non-interactive --port=%(port)s
MOCK: update_status: commit-queue Passed tests
Running: webkit-patch --status-host=example.com land-attachment --force-clean --non-interactive --parent-command=commit-queue 10000 --port=%(port)s
MOCK: update_status: commit-queue Landed patch
MOCK: update_status: commit-queue Pass
MOCK: release_work_item: commit-queue 10000
""" % {"port": "mac"},
"handle_script_error": "ScriptError error message\n\nMOCK output\n",
"handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.\n\nMock error message'\n",
}
self.assert_queue_outputs(CommitQueue(), tool=tool, expected_logs=expected_logs)
def test_rollout_lands(self):
tool = MockTool()
tool.buildbot.light_tree_on_fire()
rollout_patch = tool.bugs.fetch_attachment(10005) # _patch6, a rollout patch.
assert(rollout_patch.is_rollout())
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("commit-queue"),
"process_work_item": """Running: webkit-patch --status-host=example.com clean --port=%(port)s
MOCK: update_status: commit-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update --port=%(port)s
MOCK: update_status: commit-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10005 --port=%(port)s
MOCK: update_status: commit-queue Applied patch
Running: webkit-patch --status-host=example.com validate-changelog --check-oops --non-interactive 10005 --port=%(port)s
MOCK: update_status: commit-queue ChangeLog validated
Running: webkit-patch --status-host=example.com land-attachment --force-clean --non-interactive --parent-command=commit-queue 10005 --port=%(port)s
MOCK: update_status: commit-queue Landed patch
MOCK: update_status: commit-queue Pass
MOCK: release_work_item: commit-queue 10005
""" % {"port": "mac"},
"handle_script_error": "ScriptError error message\n\nMOCK output\n",
"handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10005' with comment 'Rejecting attachment 10005 from commit-queue.\n\nMock error message'\n",
}
self.assert_queue_outputs(CommitQueue(), tool=tool, work_item=rollout_patch, expected_logs=expected_logs)
def test_auto_retry(self):
queue = CommitQueue()
options = Mock()
options.parent_command = "commit-queue"
tool = AlwaysCommitQueueTool()
sequence = NeedsUpdateSequence(None)
expected_logs = """Commit failed because the checkout is out of date. Please update and try again.
MOCK: update_status: commit-queue Tests passed, but commit failed (checkout out of date). Updating, then landing without building or re-running tests.
"""
state = {'patch': None}
OutputCapture().assert_outputs(self, sequence.run_and_handle_errors, [tool, options, state], expected_exception=TryAgain, expected_logs=expected_logs)
self.assertTrue(options.update)
self.assertFalse(options.build)
self.assertFalse(options.test)
def test_manual_reject_during_processing(self):
queue = SecondThoughtsCommitQueue(MockTool())
queue.begin_work_queue()
queue._tool.filesystem.write_text_file('/tmp/layout-test-results/full_results.json', '') # Otherwise the commit-queue will hit a KeyError trying to read the results from the MockFileSystem.
queue._tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '')
queue._options = Mock()
queue._options.port = None
expected_logs = """Running: webkit-patch --status-host=example.com clean --port=mac
MOCK: update_status: commit-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update --port=mac
MOCK: update_status: commit-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10000 --port=mac
MOCK: update_status: commit-queue Applied patch
Running: webkit-patch --status-host=example.com validate-changelog --check-oops --non-interactive 10000 --port=mac
MOCK: update_status: commit-queue ChangeLog validated
Running: webkit-patch --status-host=example.com build --no-clean --no-update --build-style=release --port=mac
MOCK: update_status: commit-queue Built patch
Running: webkit-patch --status-host=example.com build-and-test --no-clean --no-update --test --non-interactive --port=mac
MOCK: update_status: commit-queue Passed tests
MOCK: update_status: commit-queue Retry
MOCK: release_work_item: commit-queue 10000
"""
self.maxDiff = None
OutputCapture().assert_outputs(self, queue.process_work_item, [QueuesTest.mock_work_item], expected_logs=expected_logs)
def test_report_flaky_tests(self):
queue = TestCommitQueue(MockTool())
expected_logs = """MOCK bug comment: bug_id=50002, cc=None
--- Begin comment ---
The commit-queue just saw foo/bar.html flake (text diff) while processing attachment 10000 on bug 50000.
Port: MockPort Platform: MockPlatform 1.0
--- End comment ---
MOCK add_attachment_to_bug: bug_id=50002, description=Failure diff from bot filename=failure.diff mimetype=None
MOCK bug comment: bug_id=50002, cc=None
--- Begin comment ---
The commit-queue just saw bar/baz.html flake (text diff) while processing attachment 10000 on bug 50000.
Port: MockPort Platform: MockPlatform 1.0
--- End comment ---
bar/baz-diffs.txt does not exist in results archive, uploading entire archive.
MOCK add_attachment_to_bug: bug_id=50002, description=Archive of layout-test-results from bot filename=layout-test-results.zip mimetype=None
MOCK bug comment: bug_id=50000, cc=None
--- Begin comment ---
The commit-queue encountered the following flaky tests while processing attachment 10000:
foo/bar.html bug 50002 (author: abarth@webkit.org)
bar/baz.html bug 50002 (author: abarth@webkit.org)
The commit-queue is continuing to process your patch.
--- End comment ---
"""
test_names = ["foo/bar.html", "bar/baz.html"]
test_results = [self._mock_test_result(name) for name in test_names]
class MockZipFile(object):
def __init__(self):
self.fp = StringIO()
def read(self, path):
return ""
def namelist(self):
# This is intentionally missing one diffs.txt to exercise the "upload the whole zip" codepath.
return ['foo/bar-diffs.txt']
OutputCapture().assert_outputs(self, queue.report_flaky_tests, [QueuesTest.mock_work_item, test_results, MockZipFile()], expected_logs=expected_logs)
def test_did_pass_testing_ews(self):
tool = MockTool()
patch = tool.bugs.fetch_attachment(10000)
queue = TestCommitQueue(tool)
self.assertFalse(queue.did_pass_testing_ews(patch))
class StyleQueueTest(QueuesTest):
def test_style_queue_with_style_exception(self):
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("style-queue"),
"process_work_item": """Running: webkit-patch --status-host=example.com clean
MOCK: update_status: style-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update
MOCK: update_status: style-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10000
MOCK: update_status: style-queue Applied patch
Running: webkit-patch --status-host=example.com apply-watchlist-local 50000
MOCK: update_status: style-queue Watchlist applied
Running: webkit-patch --status-host=example.com check-style-local --non-interactive --quiet
MOCK: update_status: style-queue Style checked
MOCK: update_status: style-queue Pass
MOCK: release_work_item: style-queue 10000
""",
"handle_unexpected_error": "Mock error message\n",
"handle_script_error": "MOCK output\n",
}
tool = MockTool(executive_throws_when_run=set(['check-style']))
self.assert_queue_outputs(StyleQueue(), expected_logs=expected_logs, tool=tool)
def test_style_queue_with_watch_list_exception(self):
expected_logs = {
"begin_work_queue": self._default_begin_work_queue_logs("style-queue"),
"process_work_item": """Running: webkit-patch --status-host=example.com clean
MOCK: update_status: style-queue Cleaned working directory
Running: webkit-patch --status-host=example.com update
MOCK: update_status: style-queue Updated working directory
Running: webkit-patch --status-host=example.com apply-attachment --no-update --non-interactive 10000
MOCK: update_status: style-queue Applied patch
Running: webkit-patch --status-host=example.com apply-watchlist-local 50000
Exception for ['echo', '--status-host=example.com', 'apply-watchlist-local', 50000]
MOCK command output
MOCK: update_status: style-queue Unabled to apply watchlist
Running: webkit-patch --status-host=example.com check-style-local --non-interactive --quiet
MOCK: update_status: style-queue Style checked
MOCK: update_status: style-queue Pass
MOCK: release_work_item: style-queue 10000
""",
"handle_unexpected_error": "Mock error message\n",
"handle_script_error": "MOCK output\n",
}
tool = MockTool(executive_throws_when_run=set(['apply-watchlist-local']))
self.assert_queue_outputs(StyleQueue(), expected_logs=expected_logs, tool=tool)
| bsd-3-clause |
jimyx17/jimh | lib/requests/packages/urllib3/__init__.py | 309 | 1692 | # urllib3/__init__.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
urllib3 - Thread-safe connection pooling and re-using.
"""
__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'
__license__ = 'MIT'
__version__ = 'dev'
from .connectionpool import (
HTTPConnectionPool,
HTTPSConnectionPool,
connection_from_url
)
from . import exceptions
from .filepost import encode_multipart_formdata
from .poolmanager import PoolManager, ProxyManager, proxy_from_url
from .response import HTTPResponse
from .util import make_headers, get_host
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
def add_stderr_logger(level=logging.DEBUG):
"""
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
"""
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another package.
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(level)
logger.debug('Added an stderr logging handler to logger: %s' % __name__)
return handler
# ... Clean up.
del NullHandler
| gpl-3.0 |
Anvil/maestro-ng | maestro/guestutils.py | 4 | 4570 | # Copyright (C) 2013-2014 SignalFuse, Inc.
# Copyright (C) 2015 SignalFx, Inc.
#
# Utility functions for service start scripts that help work with Maestro
# orchestration.
import netifaces
import os
import re
class MaestroEnvironmentError(Exception):
pass
def get_environment_name():
"""Return the name of the environment the container calling this in a part
of."""
return os.environ.get('MAESTRO_ENVIRONMENT_NAME', 'local')
def get_service_name():
"""Returns the service name of the container calling it."""
name = os.environ.get('SERVICE_NAME', '')
if not name:
raise MaestroEnvironmentError('Service name was not defined')
return name
def get_container_name():
"""Returns the name of the container calling it."""
name = os.environ.get('CONTAINER_NAME', '')
if not name:
raise MaestroEnvironmentError('Container name was not defined')
return name
def get_container_host_address():
"""Return the publicly-addressable IP address of the host of the
container."""
address = os.environ.get('CONTAINER_HOST_ADDRESS', '')
if not address:
raise MaestroEnvironmentError('Container host address was not defined')
return address
def get_container_internal_address():
"""Return the internal, private IP address assigned to the container."""
return netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
def get_port(name, default=None):
"""Return the exposed (internal) port number for the given port, or the
given default if not found."""
return get_specific_exposed_port(
get_service_name(),
get_container_name(),
name, default)
def get_specific_host(service, container):
"""Return the hostname/address of a specific container/instance of the
given service."""
try:
return os.environ['{}_{}_HOST'.format(_to_env_var_name(service),
_to_env_var_name(container))]
except:
raise MaestroEnvironmentError(
'No host defined for container {} of service {}'
.format(container, service))
def get_specific_exposed_port(service, container, port, default=None):
"""Return the exposed (internal) port number of a specific port of a
specific container from a given service."""
try:
return int(os.environ.get(
'{}_{}_{}_INTERNAL_PORT'.format(_to_env_var_name(service),
_to_env_var_name(container),
_to_env_var_name(port)).upper(),
default))
except:
raise MaestroEnvironmentError(
'No internal port {} defined for container {} of service {}'
.format(port, container, service))
def get_specific_port(service, container, port, default=None):
"""Return the external port number of a specific port of a specific
container from a given service."""
try:
return int(os.environ.get(
'{}_{}_{}_PORT'.format(_to_env_var_name(service),
_to_env_var_name(container),
_to_env_var_name(port)).upper(),
default))
except:
raise MaestroEnvironmentError(
'No port {} defined for container {} of service {}'
.format(port, container, service))
def get_node_list(service, ports=[], minimum=1):
"""Build a list of nodes for the given service from the environment,
eventually adding the ports from the list of port names. The resulting
entries will be of the form 'host[:port1[:port2]]' and sorted by container
name."""
nodes = []
for container in _get_service_instance_names(service):
node = get_specific_host(service, container)
for port in ports:
node = '{}:{}'.format(node,
get_specific_port(service, container, port))
nodes.append(node)
if len(nodes) < minimum:
raise MaestroEnvironmentError(
'No or not enough {} nodes configured'.format(service))
return nodes
def _to_env_var_name(s):
"""Transliterate a service or container name into the form used for
environment variable names."""
return re.sub(r'[^\w]', '_', s).upper()
def _get_service_instance_names(service):
"""Return the list of container/instance names for the given service."""
key = '{}_INSTANCES'.format(_to_env_var_name(service))
if key not in os.environ:
return []
return os.environ[key].split(',')
| apache-2.0 |
ojengwa/sympy | doc/ext/sympylive.py | 104 | 1289 | """
sympylive
~~~~~~~~~
Allow `SymPy Live <http://live.sympy.org/>`_ to be used for interactive
evaluation of SymPy's code examples.
:copyright: Copyright 2014 by the SymPy Development Team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def builder_inited(app):
if not app.config.sympylive_url:
raise ExtensionError('sympylive_url config value must be set'
' for the sympylive extension to work')
app.add_javascript(app.config.sympylive_url + '/static/utilities.js')
app.add_javascript(app.config.sympylive_url + '/static/external/classy.js')
app.add_stylesheet(app.config.sympylive_url + '/static/live-core.css')
app.add_stylesheet(app.config.sympylive_url +
'/static/live-autocomplete.css')
app.add_stylesheet(app.config.sympylive_url + '/static/live-sphinx.css')
app.add_javascript(app.config.sympylive_url + '/static/live-core.js')
app.add_javascript(app.config.sympylive_url +
'/static/live-autocomplete.js')
app.add_javascript(app.config.sympylive_url + '/static/live-sphinx.js')
def setup(app):
app.add_config_value('sympylive_url', 'http://live.sympy.org', False)
app.connect('builder-inited', builder_inited)
| bsd-3-clause |
v0i0/lammps | tools/i-pi/ipi/inputs/outputs.py | 41 | 14724 | """Deals with creating the output objects.
Copyright (C) 2013, Joshua More and Michele Ceriotti
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/>.
Classes:
InputOutputs: Creates a list of all the output objects.
InputProperties: Deals with property output.
InputTrajectory: Deals with trajectory output.
InputCheckpoint: Deals with restart file output.
"""
import numpy as np
from copy import copy
import ipi.engine.outputs
from ipi.utils.depend import *
from ipi.utils.inputvalue import *
from ipi.engine.properties import getkey
__all__=['InputOutputs', 'InputProperties', 'InputTrajectory',
'InputCheckpoint']
class InputProperties(InputArray):
"""Simple input class to describe output for properties.
Storage class for PropertyOutput.
Attributes:
filename: The name of the file to output to.
stride: The number of steps that should be taken between outputting the
data to file.
flush: An integer describing how often the output streams are flushed,
so that it doesn't wait for the buffer to fill before outputting to
file.
"""
default_help = """This class deals with the output of properties to one file. Between each property tag there should be an array of strings, each of which specifies one property to be output."""
default_label = "PROPERTIES"
attribs = copy(InputArray.attribs)
attribs["filename"] = (InputAttribute,{ "dtype" : str, "default": "out",
"help": "A string to specify the name of the file that is output. The file name is given by 'prefix'.'filename' + format_specifier. The format specifier may also include a number if multiple similar files are output."} )
attribs["stride"] = (InputAttribute,{ "dtype" : int, "default": 1,
"help": "The number of steps between successive writes." } )
attribs["flush"] = (InputAttribute, {"dtype" : int, "default" : 1,
"help" : "How often should streams be flushed. 1 means each time, zero means never." })
def __init__(self, help=None, default=None, dtype=None, dimension=None):
"""Initializes InputProperties.
Just calls the parent initialization function with appropriate arguments.
"""
super(InputProperties,self).__init__(help=help, default=default, dtype=str, dimension=dimension)
def fetch(self):
"""Returns a PropertyOutput object."""
return ipi.engine.outputs.PropertyOutput(filename=self.filename.fetch(),
stride=self.stride.fetch(), flush=self.flush.fetch(), outlist=super(InputProperties,self).fetch())
def store(self, prop):
"""Stores a PropertyOutput object."""
super(InputProperties,self).store(prop.outlist)
self.stride.store(prop.stride)
self.flush.store(prop.flush)
self.filename.store(prop.filename)
def check(self):
"""Checks for optional parameters."""
super(InputProperties,self).check()
if self.stride.fetch() < 0:
raise ValueError("The stride length for the properties file output must be positive.")
class InputTrajectory(InputValue):
"""Simple input class to describe output for trajectories.
Storage class for TrajectoryOutput.
Attributes:
filename: The (base) name of the file to output to.
stride: The number of steps that should be taken between outputting the
data to file.
format: The format of the trajectory output file.
cell_units: The units that the cell parameters are given in.
bead: If the trajectory is a per-bead property, this can be used to
specify a single bead to output. If negative, it defaults to
the centroid.
flush: An integer describing how often the output streams are flushed,
so that it doesn't wait for the buffer to fill before outputting to
file.
"""
default_help = """This class defines how one trajectory file should be output. Between each trajectory tag one string should be given, which specifies what data is to be output."""
default_label = "TRAJECTORY"
attribs = copy(InputValue.attribs)
attribs["filename"] = (InputAttribute,{ "dtype" : str, "default": "traj",
"help": "A string to specify the name of the file that is output. The file name is given by 'prefix'.'filename' + format_specifier. The format specifier may also include a number if multiple similar files are output."} )
attribs["stride"] = (InputAttribute,{ "dtype" : int, "default": 1,
"help": "The number of steps between successive writes." } )
attribs["format"] = (InputAttribute,{ "dtype" : str, "default": "xyz",
"help": "The output file format.",
"options": ['xyz', 'pdb'] } )
attribs["cell_units"] = (InputAttribute,{ "dtype" : str, "default": "",
"help": "The units for the cell dimensions." } )
attribs["bead"] = (InputAttribute,{ "dtype" : int, "default": -1,
"help": "Print out only the specified bead. A negative value means print all." } )
attribs["flush"] = (InputAttribute, {"dtype" : int, "default" : 1,
"help" : "How often should streams be flushed. 1 means each time, zero means never." })
def __init__(self, help=None, default=None, dtype=None, dimension=None):
"""Initializes InputTrajectory.
Just calls the parent initialization function with appropriate arguments.
"""
super(InputTrajectory,self).__init__(help=help, default=default, dtype=str, dimension=dimension)
def fetch(self):
"""Returns a TrajectoryOutput object."""
return ipi.engine.outputs.TrajectoryOutput(filename=self.filename.fetch(), stride=self.stride.fetch(),
flush=self.flush.fetch(), what=super(InputTrajectory,self).fetch(),
format=self.format.fetch(), cell_units=self.cell_units.fetch(), ibead=self.bead.fetch())
def store(self, traj):
"""Stores a PropertyOutput object."""
super(InputTrajectory,self).store(traj.what)
self.stride.store(traj.stride)
self.flush.store(traj.flush)
self.filename.store(traj.filename)
self.format.store(traj.format)
self.cell_units.store(traj.cell_units)
self.bead.store(traj.ibead)
def check(self):
"""Checks for optional parameters."""
super(InputTrajectory,self).check()
if self.stride.fetch() < 0:
raise ValueError("The stride length for the trajectory file output must be positive.")
class InputCheckpoint(InputValue):
"""Simple input class to describe output for properties.
Storage class for CheckpointOutput.
Attributes:
filename: The (base) name of the file to output to.
stride: The number of steps that should be taken between outputting the
data to file.
overwrite: whether checkpoints should be overwritten, or multiple
files output.
"""
default_help = """This class defines how a checkpoint file should be output. Optionally, between the checkpoint tags, you can specify one integer giving the current step of the simulation. By default this integer will be zero."""
default_label = "CHECKPOINT"
attribs=copy(InputValue.attribs)
attribs["filename"] = (InputAttribute,{ "dtype" : str, "default": "restart",
"help": "A string to specify the name of the file that is output. The file name is given by 'prefix'.'filename' + format_specifier. The format specifier may also include a number if multiple similar files are output."} )
attribs["stride"] = (InputAttribute,{ "dtype" : int, "default": 1,
"help": "The number of steps between successive writes." } )
attribs["overwrite"] = (InputAttribute,{ "dtype" : bool, "default": True,
"help": "This specifies whether or not each consecutive checkpoint file will overwrite the old one."} )
def __init__(self, help=None, default=None, dtype=None, dimension=None):
"""Initializes InputCheckpoint.
Just calls the parent initialization function with appropriate arguments.
"""
super(InputCheckpoint,self).__init__(help=help, default=default, dtype=int, dimension=dimension)
def fetch(self):
"""Returns a CheckpointOutput object."""
step = super(InputCheckpoint,self).fetch()
return ipi.engine.outputs.CheckpointOutput(self.filename.fetch(), self.stride.fetch(), self.overwrite.fetch(), step=step )
def parse(self, xml=None, text=""):
"""Overwrites the standard parse function so that we can specify this tag
in the input without any data.
We can use the syntax <checkpoint /> to do this
Args:
xml: An xml node containing all the data for the parent tag.
text: The data to read the data from. Will be None if we have not
specified any data.
"""
# just a quick hack to allow an empty element
try:
super(InputCheckpoint,self).parse(xml,text)
except: #TODO make this except a specific exception, not every one
self.value = 0 #This could hide actual errors, at least in theory.
def store(self, chk):
"""Stores a CheckpointOutput object."""
super(InputCheckpoint,self).store(chk.step)
self.stride.store(chk.stride)
self.filename.store(chk.filename)
self.overwrite.store(chk.overwrite)
def check(self):
"""Checks for optional parameters."""
super(InputCheckpoint,self).check()
if self.stride.fetch() < 0:
raise ValueError("The stride length for the checkpoint file output must be positive.")
class InputOutputs(Input):
""" List of outputs input class.
An example of a dynamic input class: a variable number of tags might be
present, corresponding to different output requests. This allows for
instance to print multiple property outputs, with different content
and/or output frequency.
Attributes:
prefix: A string that will be appended to all output files from this
simulation.
Dynamic fields:
trajectory: Specifies a trajectory to be output
properties: Specifies some properties to be output.
checkpoint: Specifies a checkpoint file to be output.
"""
attribs = { "prefix" : ( InputAttribute, { "dtype" : str,
"default" : "i-pi",
"help" : "A string that will be prepended to each output file name. The file name is given by 'prefix'.'filename' + format_specifier. The format specifier may also include a number if multiple similar files are output." })
}
dynamic = { "properties" : (InputProperties, { "help" : "Each of the properties tags specify how to create a file in which one or more properties are written, one line per frame. " } ),
"trajectory" : (InputTrajectory, { "help" : "Each of the trajectory tags specify how to create a trajectory file, containing a list of per-atom coordinate properties. " } ),
"checkpoint" : (InputCheckpoint, { "help" : "Each of the checkpoint tags specify how to create a checkpoint file, which can be used to restart a simulation. " } ),
}
default_help = """This class defines how properties, trajectories and checkpoints should be output during the simulation. May contain zero, one or many instances of properties, trajectory or checkpoint tags, each giving instructions on how one output file should be created and managed."""
default_label = "OUTPUTS"
@classmethod
def make_default(cls):
"""Used to make the default value of the outputs class for use when no
output is specified.
Needed since this is a fairly complicated default, with many mutable
objects, and the default has to be generated by a function that does not
use any mutable objects as arguments.
"""
return [ ipi.engine.outputs.PropertyOutput(filename="i-pi.md", stride=10, outlist=[ "time", "step", "conserved", "temperature", "potential", "kinetic_cv" ] ),
ipi.engine.outputs.TrajectoryOutput(filename="i-pi.pos", stride=100, what="positions", format="xyz"),
ipi.engine.outputs.CheckpointOutput(filename="i-pi.checkpoint", stride=1000, overwrite=True)]
def fetch(self):
"""Returns a list of the output objects included in this dynamic
container.
Returns:
A list of tuples, with each tuple being of the form ('type', 'object')
where 'type' is the type of output object and 'object' is a particular
object of that type.
"""
super(InputOutputs, self).fetch()
outlist = [ p.fetch() for (n, p) in self.extra ]
prefix = self.prefix.fetch()
if not prefix == "":
for p in outlist:
p.filename = prefix + "." + p.filename
return outlist
def store(self, plist):
""" Stores a list of the output objects, creating a sequence of
dynamic containers.
Args:
plist: A list of tuples, with each tuple being of the form
('type', 'object') where 'type' is the type of forcefield and
'object' is a particular object of that type.
"""
super(InputOutputs, self).store()
self.extra = []
self.prefix.store("")
for el in plist:
if (isinstance(el, ipi.engine.outputs.PropertyOutput)):
ip = InputProperties()
ip.store(el)
self.extra.append(("properties", ip))
elif (isinstance(el, ipi.engine.outputs.TrajectoryOutput)):
ip = InputTrajectory()
ip.store(el)
self.extra.append(("trajectory", ip))
elif (isinstance(el, ipi.engine.outputs.CheckpointOutput)):
ip = InputCheckpoint()
ip.store(el)
self.extra.append(("checkpoint", ip))
| gpl-2.0 |
ElJulio/SoftI2C | I2C.py | 1 | 3915 | #!/usr/bin/python
#Soft implementation of an i2c Master
import time
import RPi.GPIO as GPIO
class i2cMaster:
int_clk = -1
SDA = 17 #default sda
SCL = 27 #default scl
def tick(self,anz):
time.sleep(anz*self.int_clk)
def init(self,bitrate,SDAPIN,SCLPIN):
if(SDAPIN != SCLPIN):
self.SCL = SCLPIN
self.SDA = SDAPIN
else:
print "SDA = GPIO"+str(self.SDA)+" SCL = GPIO"+str(self.SCL)
#configer SCL as output
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.SCL, GPIO.OUT)
GPIO.setup(self.SDA, GPIO.OUT)
GPIO.output(self.SDA, GPIO.HIGH)
GPIO.output(self.SCL, GPIO.HIGH)
if bitrate == 100:
self.int_clk = 0.0000025
elif bitrate == 400:
self.int_clk = 0.000000625
elif bitrate == 1000:
self.int_clk = 1
elif bitrate == 3200:
self.int_clk = 1
def Start(self):
#SCL
# ______
# | |______
#SDA
# ___
# | |_________
GPIO.setup(self.SDA, GPIO.OUT) #cnfigure SDA as output
GPIO.output(self.SDA, GPIO.HIGH)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(1)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(1)
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
def ReadAck(self):
GPIO.setup(self.SDA, GPIO.IN)
readbuffer =0
for i in range(8):
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
readbuffer |= (GPIO.input(self.SDA)<< 7) >> i
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
GPIO.setup(self.SDA, GPIO.OUT)
GPIO.output(self.SDA, GPIO.LOW)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(2)
return readbuffer
def ReadNack(self):
GPIO.setup(self.SDA, GPIO.IN)
readbuffer =0
for i in range(8):
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
readbuffer |= (GPIO.input(self.SDA)<< 7) >> i
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
GPIO.setup(self.SDA, GPIO.OUT)
GPIO.output(self.SDA, GPIO.HIGH)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(2)
return readbuffer
def WriteByte(self,byte):
if byte > 0xff:
return -1
#print byte
GPIO.setup(self.SDA, GPIO.OUT)
for i in range(8):
#MSB First
if (byte << i) & 0x80 == 0x80:
GPIO.output(self.SDA, GPIO.HIGH)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
GPIO.output(self.SDA, GPIO.LOW)
self.tick(2)
else:
GPIO.output(self.SDA, GPIO.LOW)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
GPIO.setup(self.SDA, GPIO.IN)
GPIO.output(self.SCL, GPIO.HIGH)
#self.tick(1)
#Get The ACK
#if GPIO.input(self.SDA):
# print "ACK"
#else:
# print "NACK"
self.tick(2)
GPIO.output(self.SCL, GPIO.LOW)
self.tick(2)
def Stop(self):
#SCL
# _____________
# |
#SDA
# __________
# __|
GPIO.setup(self.SDA, GPIO.OUT) #cnfigure SDA as output
GPIO.output(self.SDA, GPIO.LOW)
GPIO.output(self.SCL, GPIO.HIGH)
self.tick(1)
GPIO.output(self.SDA, GPIO.HIGH)
self.tick(3)
| gpl-3.0 |
mszewczy/odoo | addons/product/_common.py | 316 | 1448 | # -*- 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/>.
#
##############################################################################
from openerp import tools
def rounding(f, r):
# TODO for trunk: log deprecation warning
# _logger.warning("Deprecated rounding method, please use tools.float_round to round floats.")
return tools.float_round(f, precision_rounding=r)
# TODO for trunk: add rounding method parameter to tools.float_round and use this method as hook
def ceiling(f, r):
if not r:
return f
return tools.float_round(f, precision_rounding=r, rounding_method='UP')
| agpl-3.0 |
mekanix/api | onelove/api/__init__.py | 5 | 1054 | from flask import render_template
from flask_rest_api import Api
class MyApi(Api):
def _openapi_swagger_ui(self):
return render_template('swaggerui.html', title=self._app.name)
def register_blueprints(app, prefix, blueprints):
for blueprint in blueprints:
app.api.register_blueprint(
blueprint,
url_prefix='{}/{}'.format(
prefix,
blueprint.name,
),
)
def create_api(app):
from .auth import blueprint as auth
from .application import blueprint as application
from .cluster import blueprint as cluster
from .host import blueprint as host
from .me import blueprint as me
from .provider import blueprint as provider
from .service import blueprint as service
from .user import blueprint as user
app.api = MyApi(app)
register_blueprints(
app,
'/api/v0',
[
auth,
cluster,
me,
provider,
service,
user,
],
)
| gpl-3.0 |
bwrsandman/openerp-hr | hr_labour_union/__openerp__.py | 1 | 1550 | #-*- coding:utf-8 -*-
#
#
# Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# 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': 'Labour Union',
'version': '1.0',
'category': 'Generic Modules/Human Resources',
'description': """
Labour Union
=====================
This module adds:
* Field on employee record denoting whether the employee is a member of a labour union
* Salary rule for deducting union fee from union members
""",
'author': 'Michael Telahun Makonnen <mmakonnen@gmail.com>',
'website': 'http://miketelahun.wordpress.com',
'depends': [
'hr',
'hr_payroll',
],
'init_xml': [
],
'update_xml': [
'hr_labour_union_data.xml',
'hr_labour_union_view.xml',
],
'test': [
],
'demo_xml': [
],
'installable': True,
'active': False,
}
| agpl-3.0 |
alex/warehouse | warehouse/config.py | 1 | 16992 | # 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 enum
import os
import shlex
import transaction
from pyramid import renderers
from pyramid.config import Configurator as _Configurator
from pyramid.response import Response
from pyramid.security import Allow
from pyramid.tweens import EXCVIEW
from pyramid_rpc.xmlrpc import XMLRPCRenderer
from warehouse import __commit__
from warehouse.utils.static import ManifestCacheBuster
from warehouse.utils.wsgi import ProxyFixer, VhmRootRemover, HostRewrite
class Environment(enum.Enum):
production = "production"
development = "development"
class Configurator(_Configurator):
def add_wsgi_middleware(self, middleware, *args, **kwargs):
middlewares = self.get_settings().setdefault("wsgi.middlewares", [])
middlewares.append((middleware, args, kwargs))
def make_wsgi_app(self, *args, **kwargs):
# Get the WSGI application from the underlying configurator
app = super().make_wsgi_app(*args, **kwargs)
# Look to see if we have any WSGI middlewares configured.
for middleware, args, kw in self.get_settings()["wsgi.middlewares"]:
app = middleware(app, *args, **kw)
# Finally, return our now wrapped app
return app
class RootFactory:
__parent__ = None
__name__ = None
__acl__ = [
(Allow, "group:admins", "admin"),
]
def __init__(self, request):
pass
def require_https_tween_factory(handler, registry):
if not registry.settings.get("enforce_https", True):
return handler
def require_https_tween(request):
# If we have an :action URL and we're not using HTTPS, then we want to
# return a 403 error.
if request.params.get(":action", None) and request.scheme != "https":
resp = Response(
"SSL is required.",
status=403,
content_type="text/plain",
)
resp.status = "403 SSL is required"
resp.headers["X-Fastly-Error"] = "803"
return resp
return handler(request)
return require_https_tween
def activate_hook(request):
if request.path.startswith(("/_debug_toolbar/", "/static/")):
return False
return True
def template_view(config, name, route, template, route_kw=None):
if route_kw is None:
route_kw = {}
config.add_route(name, route, **route_kw)
config.add_view(renderer=template, route_name=name)
def maybe_set(settings, name, envvar, coercer=None, default=None):
if envvar in os.environ:
value = os.environ[envvar]
if coercer is not None:
value = coercer(value)
settings.setdefault(name, value)
elif default is not None:
settings.setdefault(name, default)
def maybe_set_compound(settings, base, name, envvar):
if envvar in os.environ:
value = shlex.split(os.environ[envvar])
kwargs = {k: v for k, v in (i.split("=") for i in value[1:])}
settings[".".join([base, name])] = value[0]
for key, value in kwargs.items():
settings[".".join([base, key])] = value
def configure(settings=None):
if settings is None:
settings = {}
# Add information about the current copy of the code.
settings.setdefault("warehouse.commit", __commit__)
# Set the environment from an environment variable, if one hasn't already
# been set.
maybe_set(
settings, "warehouse.env", "WAREHOUSE_ENV", Environment,
default=Environment.production,
)
# Pull in default configuration from the environment.
maybe_set(settings, "warehouse.token", "WAREHOUSE_TOKEN")
maybe_set(settings, "warehouse.num_proxies", "WAREHOUSE_NUM_PROXIES", int)
maybe_set(settings, "warehouse.theme", "WAREHOUSE_THEME")
maybe_set(settings, "warehouse.domain", "WAREHOUSE_DOMAIN")
maybe_set(settings, "forklift.domain", "FORKLIFT_DOMAIN")
maybe_set(settings, "warehouse.legacy_domain", "WAREHOUSE_LEGACY_DOMAIN")
maybe_set(settings, "site.name", "SITE_NAME", default="Warehouse")
maybe_set(settings, "aws.key_id", "AWS_ACCESS_KEY_ID")
maybe_set(settings, "aws.secret_key", "AWS_SECRET_ACCESS_KEY")
maybe_set(settings, "aws.region", "AWS_REGION")
maybe_set(settings, "gcloud.credentials", "GCLOUD_CREDENTIALS")
maybe_set(settings, "gcloud.project", "GCLOUD_PROJECT")
maybe_set(settings, "warehouse.trending_table", "WAREHOUSE_TRENDING_TABLE")
maybe_set(settings, "celery.broker_url", "AMQP_URL")
maybe_set(settings, "celery.result_url", "REDIS_URL")
maybe_set(settings, "celery.scheduler_url", "REDIS_URL")
maybe_set(settings, "database.url", "DATABASE_URL")
maybe_set(settings, "elasticsearch.url", "ELASTICSEARCH_URL")
maybe_set(settings, "sentry.dsn", "SENTRY_DSN")
maybe_set(settings, "sentry.transport", "SENTRY_TRANSPORT")
maybe_set(settings, "sessions.url", "REDIS_URL")
maybe_set(settings, "download_stats.url", "REDIS_URL")
maybe_set(settings, "ratelimit.url", "REDIS_URL")
maybe_set(settings, "recaptcha.site_key", "RECAPTCHA_SITE_KEY")
maybe_set(settings, "recaptcha.secret_key", "RECAPTCHA_SECRET_KEY")
maybe_set(settings, "sessions.secret", "SESSION_SECRET")
maybe_set(settings, "camo.url", "CAMO_URL")
maybe_set(settings, "camo.key", "CAMO_KEY")
maybe_set(settings, "docs.url", "DOCS_URL")
maybe_set(settings, "mail.host", "MAL_HOST")
maybe_set(settings, "mail.port", "MAIL_PORT")
maybe_set(settings, "mail.username", "MAIL_USERNAME")
maybe_set(settings, "mail.password", "MAIL_PASSWORD")
maybe_set(settings, "mail.sender", "MAIL_SENDER")
maybe_set(settings, "ga.tracking_id", "GA_TRACKING_ID")
maybe_set(settings, "statuspage.url", "STATUSPAGE_URL")
maybe_set_compound(settings, "files", "backend", "FILES_BACKEND")
maybe_set_compound(settings, "origin_cache", "backend", "ORIGIN_CACHE")
settings.setdefault("mail.ssl", True)
# Add the settings we use when the environment is set to development.
if settings["warehouse.env"] == Environment.development:
settings.setdefault("enforce_https", False)
settings.setdefault("pyramid.reload_assets", True)
settings.setdefault("pyramid.reload_templates", True)
settings.setdefault("pyramid.prevent_http_cache", True)
settings.setdefault("debugtoolbar.hosts", ["0.0.0.0/0"])
settings.setdefault(
"debugtoolbar.panels",
[
".".join(["pyramid_debugtoolbar.panels", panel])
for panel in [
"versions.VersionDebugPanel",
"settings.SettingsDebugPanel",
"headers.HeaderDebugPanel",
"request_vars.RequestVarsDebugPanel",
"renderings.RenderingsDebugPanel",
"logger.LoggingPanel",
"performance.PerformanceDebugPanel",
"routes.RoutesDebugPanel",
"sqla.SQLADebugPanel",
"tweens.TweensDebugPanel",
"introspection.IntrospectionDebugPanel",
]
],
)
# Actually setup our Pyramid Configurator with the values pulled in from
# the environment as well as the ones passed in to the configure function.
config = Configurator(settings=settings)
config.set_root_factory(RootFactory)
# Register our CSRF support. We do this here, immediately after we've
# created the Configurator instance so that we ensure to get our defaults
# set ASAP before anything else has a chance to set them and possibly call
# Configurator().commit()
config.include(".csrf")
# Include anything needed by the development environment.
if config.registry.settings["warehouse.env"] == Environment.development:
config.include("pyramid_debugtoolbar")
# Register our logging support
config.include(".logging")
# We'll want to use Jinja2 as our template system.
config.include("pyramid_jinja2")
# Including pyramid_mailer for sending emails through SMTP.
# Lower environments (< prod) shouldn't send the actual email's, so we are
# adding pyramid_mailer.debug to route the email's to disk.
if config.registry.settings["warehouse.env"] == Environment.production:
config.include("pyramid_mailer")
else:
config.include("pyramid_mailer.debug")
# We want to use newstyle gettext
config.add_settings({"jinja2.newstyle": True})
# We also want to use Jinja2 for .html templates as well, because we just
# assume that all templates will be using Jinja.
config.add_jinja2_renderer(".html")
# Sometimes our files are .txt files and we still want to use Jinja2 to
# render them.
config.add_jinja2_renderer(".txt")
# Anytime we want to render a .xml template, we'll also use Jinja.
config.add_jinja2_renderer(".xml")
# We need to enable our Client Side Include extension
config.get_settings().setdefault(
"jinja2.extensions",
["warehouse.utils.html.ClientSideIncludeExtension"],
)
# We'll want to configure some filters for Jinja2 as well.
filters = config.get_settings().setdefault("jinja2.filters", {})
filters.setdefault(
"format_classifiers",
"warehouse.filters:format_classifiers",
)
filters.setdefault("format_tags", "warehouse.filters:format_tags")
filters.setdefault("json", "warehouse.filters:tojson")
filters.setdefault("readme", "warehouse.filters:readme")
filters.setdefault("shorten_number", "warehouse.filters:shorten_number")
filters.setdefault("urlparse", "warehouse.filters:urlparse")
filters.setdefault(
"contains_valid_uris",
"warehouse.filters:contains_valid_uris"
)
filters.setdefault(
"format_package_type",
"warehouse.filters:format_package_type"
)
filters.setdefault("parse_version", "warehouse.filters:parse_version")
# We also want to register some global functions for Jinja
jglobals = config.get_settings().setdefault("jinja2.globals", {})
jglobals.setdefault("is_valid_uri", "warehouse.utils.http:is_valid_uri")
jglobals.setdefault("gravatar", "warehouse.utils.gravatar:gravatar")
jglobals.setdefault("gravatar_profile", "warehouse.utils.gravatar:profile")
jglobals.setdefault("now", "warehouse.utils:now")
# We'll store all of our templates in one location, warehouse/templates
# so we'll go ahead and add that to the Jinja2 search path.
config.add_jinja2_search_path("warehouse:templates", name=".html")
config.add_jinja2_search_path("warehouse:templates", name=".txt")
config.add_jinja2_search_path("warehouse:templates", name=".xml")
# We want to configure our JSON renderer to sort the keys, and also to use
# an ultra compact serialization format.
config.add_renderer(
"json",
renderers.JSON(sort_keys=True, separators=(",", ":")),
)
# Configure retry support.
config.add_settings({"retry.attempts": 3})
config.include("pyramid_retry")
# Configure our transaction handling so that each request gets its own
# transaction handler and the lifetime of the transaction is tied to the
# lifetime of the request.
config.add_settings({
"tm.manager_hook": lambda request: transaction.TransactionManager(),
"tm.activate_hook": activate_hook,
"tm.annotate_user": False,
})
config.include("pyramid_tm")
# Register support for services
config.include("pyramid_services")
# Register support for XMLRPC and override it's renderer to allow
# specifying custom dumps arguments.
config.include("pyramid_rpc.xmlrpc")
config.add_renderer("xmlrpc", XMLRPCRenderer(allow_none=True))
# Register support for our legacy action URLs
config.include(".legacy.action_routing")
# Register support for our domain predicates
config.include(".domain")
# Register support for template views.
config.add_directive("add_template_view", template_view, action_wrap=False)
# Register support for internationalization and localization
config.include(".i18n")
# Register the configuration for the PostgreSQL database.
config.include(".db")
# Register support for our rate limiting mechanisms
config.include(".rate_limiting")
config.include(".static")
config.include(".policy")
config.include(".search")
# Register the support for AWS and Google Cloud
config.include(".aws")
config.include(".gcloud")
# Register the support for Celery Tasks
config.include(".tasks")
# Register our session support
config.include(".sessions")
# Register our support for http and origin caching
config.include(".cache.http")
config.include(".cache.origin")
# Register our authentication support.
config.include(".accounts")
# Allow the packaging app to register any services it has.
config.include(".packaging")
# Configure redirection support
config.include(".redirects")
# Register all our URL routes for Warehouse.
config.include(".routes")
# Include our admin application
config.include(".admin")
# Register forklift, at least until we split it out into it's own project.
config.include(".forklift")
# Block non HTTPS requests for the legacy ?:action= routes when they are
# sent via POST.
config.add_tween("warehouse.config.require_https_tween_factory")
# Enable compression of our HTTP responses
config.add_tween(
"warehouse.utils.compression.compression_tween_factory",
over=[
"warehouse.cache.http.conditional_http_tween_factory",
"pyramid_debugtoolbar.toolbar_tween_factory",
"warehouse.raven.raven_tween_factory",
EXCVIEW,
],
)
# Enable Warehouse to serve our static files
prevent_http_cache = \
config.get_settings().get("pyramid.prevent_http_cache", False)
config.add_static_view(
"static",
"warehouse:static/dist/",
# Don't cache at all if prevent_http_cache is true, else we'll cache
# the files for 10 years.
cache_max_age=0 if prevent_http_cache else 10 * 365 * 24 * 60 * 60,
)
config.add_cache_buster(
"warehouse:static/dist/",
ManifestCacheBuster(
"warehouse:static/dist/manifest.json",
reload=config.registry.settings["pyramid.reload_assets"],
strict=not prevent_http_cache,
),
)
config.whitenoise_serve_static(
autorefresh=prevent_http_cache,
max_age=0 if prevent_http_cache else 10 * 365 * 24 * 60 * 60,
manifest="warehouse:static/dist/manifest.json",
)
config.whitenoise_add_files("warehouse:static/dist/", prefix="/static/")
# Enable Warehouse to serve our locale files
config.add_static_view("locales", "warehouse:locales/")
# Enable support of passing certain values like remote host, client
# address, and protocol support in from an outer proxy to the application.
config.add_wsgi_middleware(
ProxyFixer,
token=config.registry.settings["warehouse.token"],
num_proxies=config.registry.settings.get("warehouse.num_proxies", 1),
)
# Protect against cache poisoning via the X-Vhm-Root headers.
config.add_wsgi_middleware(VhmRootRemover)
# Fix our host header when getting sent upload.pypi.io as a HOST.
# TODO: Remove this, this is at the wrong layer.
config.add_wsgi_middleware(HostRewrite)
# We want Raven to be the last things we add here so that it's the outer
# most WSGI middleware.
config.include(".raven")
# Register Content-Security-Policy service
config.include(".csp")
# Register recaptcha service
config.include(".recaptcha")
config.add_settings({
"http": {
"verify": "/etc/ssl/certs/",
},
})
config.include(".http")
# Add our theme if one was configured
if config.get_settings().get("warehouse.theme"):
config.include(config.get_settings()["warehouse.theme"])
# Scan everything for configuration
config.scan(
ignore=[
"warehouse.migrations.env",
"warehouse.celery",
"warehouse.wsgi",
],
)
# Finally, commit all of our changes
config.commit()
return config
| apache-2.0 |
TinLe/Diamond | src/collectors/example/test/testexample.py | 38 | 1240 | #!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from diamond.collector import Collector
from example import ExampleCollector
################################################################################
class TestExampleCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('ExampleCollector', {
'interval': 10
})
self.collector = ExampleCollector(config, None)
def test_import(self):
self.assertTrue(ExampleCollector)
@patch.object(Collector, 'publish')
def test(self, publish_mock):
self.collector.collect()
metrics = {
'my.example.metric': 42
}
self.setDocExample(collector=self.collector.__class__.__name__,
metrics=metrics,
defaultpath=self.collector.config['path'])
self.assertPublishedMany(publish_mock, metrics)
################################################################################
if __name__ == "__main__":
unittest.main()
| mit |
TheTimmy/spack | var/spack/repos/builtin/packages/gradle/package.py | 3 | 4173 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
from distutils.dir_util import copy_tree
class Gradle(Package):
"""Gradle is an open source build automation system that builds
upon the concepts of Apache Ant and Apache Maven and introduces
a Groovy-based domain-specific language (DSL) instead of the XML
form used by Apache Maven for declaring the project configuration.
Gradle uses a directed acyclic graph ("DAG") to determine the
order in which tasks can be run."""
homepage = "https://gradle.org"
url = "https://services.gradle.org/distributions/gradle-3.4-all.zip"
version('3.4', '5ae23dbd730dea22eb79cd97a072f06a')
version('3.3', '355f61e9c5d092d49577765ab3712dc0')
version('3.2.1', 'd44dba900ff364103e1f45c0f4b27bbe')
version('3.2', '296cb0e8a94bf72dd80ff7f0ebbf33ed')
version('3.1', '21b34a8c6bae67c729b37b4bd59cf9d0')
version('3.0', '0a7533599b86909c85b117e897501165')
version('2.14.1', 'f74b094923ae76f15f138d42373bb4bc')
version('2.14', 'e069dca1ec042665d61c85caeb4b32ed')
version('2.13', '8e7b31a8b8500752c3d80bd683d120c1')
version('2.12', '42cce06d8fe3a7125ac9b2a6dcc13927')
version('2.11', 'd99911cb2d0e86293e1793efc61cd642')
version('2.10', 'c5d8e57186b60c6d6485682f9907b257')
version('2.9', '1ee1a98b9a73c24633c14abf7f2a5189')
version('2.8', '9f0e8b0c195d7ea6335a724bc90622a9')
version('2.7', '77a77e364c1e2005c62909e6f51a434a')
version('2.6', '6947e873602b3668b2f3cd8e2dd228f1')
version('2.5', '17295dee02217cbe4f07b0d8bb72c467')
version('2.4', 'e1528eeca5c66579ebaee4c7c13bec2a')
version('2.3', '26c527220d869dbd6bb8cd903dd044e1')
version('2.2.1', '1107fbaf94ab7eae26d76d71b5f8db13')
version('2.2', '143830aea6bbed4ee77baa3dd191745f')
version('2.1', '603c07bc1fa737809ef0d9bc5b11960a')
version('2.0', '1d0853b99e6097ea3dea5f3604dc0846')
version('1.12', 'f957126d8e84d7ee7c859d02c2ae1fc1')
version('1.11', '36d2e8f0d5059c815496775af5f688b4')
version('1.10', 'c7ea1213cee7cf2272c5189dbc6f983b')
version('1.9', 'cc0a214649b283cc9594b5b82cb84ce5')
version('1.8', '1733ee0850618a73b54c9ba407de56b6')
version('1.5', '80e60e3b71f1745bbf06f41795ac2908')
version('1.4', 'cc934cab80bed0caccaa096b83cd4d67')
version('1.3', 'f6bce3798f4ee184926592e9a6893e0e')
version('1.2', 'c4741339370bd5e825b2abb9f2cb5b40')
version('1.1', 'afb37b4b35a30ebd5d758c333c147ce9')
version('1.0', '7697cb1e78c7e7362aa422d1790238bd')
version('0.9.2', '8574a445267ce3ad21558e300d854d24')
version('0.9.1', '8fa0acfbcdf01a8425c1f797f5079e21')
version('0.9', '9da1eb9fb32d9c303de5fd5568694634')
version('0.8', '73a0ed51b6ec00a7d3a9d242d51aae60')
version('0.7', 'a8417dbbd62f7013002cb55a44f12cc3')
depends_on('java')
def install(self, spec, prefix):
copy_tree('.', prefix)
| lgpl-2.1 |
onecloud/neutron | neutron/plugins/nec/packet_filter.py | 8 | 11671 | # Copyright 2012-2013 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# @author: Ryota MIBU
from neutron.openstack.common import excutils
from neutron.openstack.common import log as logging
from neutron.plugins.nec.common import config
from neutron.plugins.nec.common import exceptions as nexc
from neutron.plugins.nec.db import api as ndb
from neutron.plugins.nec.db import packetfilter as pf_db
LOG = logging.getLogger(__name__)
class PacketFilterMixin(pf_db.PacketFilterDbMixin):
"""Mixin class to add packet filter to NECPluginV2."""
@property
def packet_filter_enabled(self):
if not hasattr(self, '_packet_filter_enabled'):
self._packet_filter_enabled = (
config.OFC.enable_packet_filter and
self.ofc.driver.filter_supported())
return self._packet_filter_enabled
def remove_packet_filter_extension_if_disabled(self, aliases):
if not self.packet_filter_enabled:
LOG.debug(_('Disabled packet-filter extension.'))
aliases.remove('packet-filter')
def create_packet_filter(self, context, packet_filter):
"""Create a new packet_filter entry on DB, then try to activate it."""
LOG.debug(_("create_packet_filter() called, packet_filter=%s ."),
packet_filter)
if hasattr(self.ofc.driver, 'validate_filter_create'):
pf = packet_filter['packet_filter']
self.ofc.driver.validate_filter_create(context, pf)
pf = super(PacketFilterMixin, self).create_packet_filter(
context, packet_filter)
return self.activate_packet_filter_if_ready(context, pf)
def update_packet_filter(self, context, id, packet_filter):
"""Update packet_filter entry on DB, and recreate it if changed.
If any rule of the packet_filter was changed, recreate it on OFC.
"""
LOG.debug(_("update_packet_filter() called, "
"id=%(id)s packet_filter=%(packet_filter)s ."),
{'id': id, 'packet_filter': packet_filter})
pf_data = packet_filter['packet_filter']
if hasattr(self.ofc.driver, 'validate_filter_update'):
self.ofc.driver.validate_filter_update(context, pf_data)
# validate ownership
pf_old = self.get_packet_filter(context, id)
pf = super(PacketFilterMixin, self).update_packet_filter(
context, id, packet_filter)
def _packet_filter_changed(old_pf, new_pf):
LOG.debug('old_pf=%(old_pf)s, new_pf=%(new_pf)s',
{'old_pf': old_pf, 'new_pf': new_pf})
# When the status is ERROR, force sync to OFC.
if old_pf['status'] == pf_db.PF_STATUS_ERROR:
LOG.debug('update_packet_filter: Force filter update '
'because the previous status is ERROR.')
return True
for key in new_pf:
if key in ('id', 'name', 'tenant_id', 'network_id',
'in_port', 'status'):
continue
if old_pf[key] != new_pf[key]:
return True
return False
if _packet_filter_changed(pf_old, pf):
if hasattr(self.ofc.driver, 'update_filter'):
# admin_state is changed
if pf_old['admin_state_up'] != pf['admin_state_up']:
LOG.debug('update_packet_filter: admin_state '
'is changed to %s', pf['admin_state_up'])
if pf['admin_state_up']:
self.activate_packet_filter_if_ready(context, pf)
else:
self.deactivate_packet_filter(context, pf)
elif pf['admin_state_up']:
LOG.debug('update_packet_filter: admin_state is '
'unchanged (True)')
if self.ofc.exists_ofc_packet_filter(context, id):
pf = self._update_packet_filter(context, pf, pf_data)
else:
pf = self.activate_packet_filter_if_ready(context, pf)
else:
LOG.debug('update_packet_filter: admin_state is unchanged '
'(False). No need to update OFC filter.')
else:
pf = self.deactivate_packet_filter(context, pf)
pf = self.activate_packet_filter_if_ready(context, pf)
return pf
def _update_packet_filter(self, context, new_pf, pf_data):
pf_id = new_pf['id']
prev_status = new_pf['status']
try:
# If previous status is ERROR, try to sync all attributes.
pf = new_pf if prev_status == pf_db.PF_STATUS_ERROR else pf_data
self.ofc.update_ofc_packet_filter(context, pf_id, pf)
new_status = pf_db.PF_STATUS_ACTIVE
if new_status != prev_status:
self._update_resource_status(context, "packet_filter",
pf_id, new_status)
new_pf['status'] = new_status
return new_pf
except Exception as exc:
with excutils.save_and_reraise_exception():
if (isinstance(exc, nexc.OFCException) or
isinstance(exc, nexc.OFCConsistencyBroken)):
LOG.error(_("Failed to create packet_filter id=%(id)s on "
"OFC: %(exc)s"),
{'id': pf_id, 'exc': exc})
new_status = pf_db.PF_STATUS_ERROR
if new_status != prev_status:
self._update_resource_status(context, "packet_filter",
pf_id, new_status)
def delete_packet_filter(self, context, id):
"""Deactivate and delete packet_filter."""
LOG.debug(_("delete_packet_filter() called, id=%s ."), id)
# validate ownership
pf = self.get_packet_filter(context, id)
# deactivate_packet_filter() raises an exception
# if an error occurs during processing.
pf = self.deactivate_packet_filter(context, pf)
super(PacketFilterMixin, self).delete_packet_filter(context, id)
def activate_packet_filter_if_ready(self, context, packet_filter):
"""Activate packet_filter by creating filter on OFC if ready.
Conditions to create packet_filter on OFC are:
* packet_filter admin_state is UP
* (if 'in_port' is specified) portinfo is available
"""
LOG.debug(_("activate_packet_filter_if_ready() called, "
"packet_filter=%s."), packet_filter)
pf_id = packet_filter['id']
in_port_id = packet_filter.get('in_port')
current = packet_filter['status']
pf_status = current
if not packet_filter['admin_state_up']:
LOG.debug(_("activate_packet_filter_if_ready(): skip pf_id=%s, "
"packet_filter.admin_state_up is False."), pf_id)
elif in_port_id and not ndb.get_portinfo(context.session, in_port_id):
LOG.debug(_("activate_packet_filter_if_ready(): skip "
"pf_id=%s, no portinfo for the in_port."), pf_id)
elif self.ofc.exists_ofc_packet_filter(context, packet_filter['id']):
LOG.debug(_("_activate_packet_filter_if_ready(): skip, "
"ofc_packet_filter already exists."))
else:
LOG.debug(_("activate_packet_filter_if_ready(): create "
"packet_filter id=%s on OFC."), pf_id)
try:
self.ofc.create_ofc_packet_filter(context, pf_id,
packet_filter)
pf_status = pf_db.PF_STATUS_ACTIVE
except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
LOG.error(_("Failed to create packet_filter id=%(id)s on "
"OFC: %(exc)s"), {'id': pf_id, 'exc': exc})
pf_status = pf_db.PF_STATUS_ERROR
if pf_status != current:
self._update_resource_status(context, "packet_filter", pf_id,
pf_status)
packet_filter.update({'status': pf_status})
return packet_filter
def deactivate_packet_filter(self, context, packet_filter):
"""Deactivate packet_filter by deleting filter from OFC if exixts."""
LOG.debug(_("deactivate_packet_filter_if_ready() called, "
"packet_filter=%s."), packet_filter)
pf_id = packet_filter['id']
if not self.ofc.exists_ofc_packet_filter(context, pf_id):
LOG.debug(_("deactivate_packet_filter(): skip, "
"Not found OFC Mapping for packet_filter id=%s."),
pf_id)
return packet_filter
LOG.debug(_("deactivate_packet_filter(): "
"deleting packet_filter id=%s from OFC."), pf_id)
try:
self.ofc.delete_ofc_packet_filter(context, pf_id)
self._update_resource_status_if_changed(
context, "packet_filter", packet_filter, pf_db.PF_STATUS_DOWN)
return packet_filter
except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
with excutils.save_and_reraise_exception():
LOG.error(_("Failed to delete packet_filter id=%(id)s "
"from OFC: %(exc)s"),
{'id': pf_id, 'exc': str(exc)})
self._update_resource_status_if_changed(
context, "packet_filter", packet_filter,
pf_db.PF_STATUS_ERROR)
def activate_packet_filters_by_port(self, context, port_id):
if not self.packet_filter_enabled:
return
filters = {'in_port': [port_id], 'admin_state_up': [True],
'status': [pf_db.PF_STATUS_DOWN]}
pfs = self.get_packet_filters(context, filters=filters)
for pf in pfs:
self.activate_packet_filter_if_ready(context, pf)
def deactivate_packet_filters_by_port(self, context, port_id,
raise_exc=True):
if not self.packet_filter_enabled:
return
filters = {'in_port': [port_id], 'status': [pf_db.PF_STATUS_ACTIVE]}
pfs = self.get_packet_filters(context, filters=filters)
error = False
for pf in pfs:
try:
self.deactivate_packet_filter(context, pf)
except (nexc.OFCException, nexc.OFCMappingNotFound):
error = True
if raise_exc and error:
raise nexc.OFCException(_('Error occurred while disabling packet '
'filter(s) for port %s'), port_id)
def get_packet_filters_for_port(self, context, port):
if self.packet_filter_enabled:
return super(PacketFilterMixin,
self).get_packet_filters_for_port(context, port)
| apache-2.0 |
CurtisMJ/g800f_custom_kernel | tools/perf/scripts/python/net_dropmonitor.py | 1258 | 1562 | # Monitor the system for dropped packets and proudce a report of drop locations and counts
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
drop_log = {}
kallsyms = []
def get_kallsyms_table():
global kallsyms
try:
f = open("/proc/kallsyms", "r")
linecount = 0
for line in f:
linecount = linecount+1
f.seek(0)
except:
return
j = 0
for line in f:
loc = int(line.split()[0], 16)
name = line.split()[2]
j = j +1
if ((j % 100) == 0):
print "\r" + str(j) + "/" + str(linecount),
kallsyms.append({ 'loc': loc, 'name' : name})
print "\r" + str(j) + "/" + str(linecount)
kallsyms.sort()
return
def get_sym(sloc):
loc = int(sloc)
for i in kallsyms[::-1]:
if loc >= i['loc']:
return (i['name'], loc - i['loc'])
return (None, 0)
def print_drop_table():
print "%25s %25s %25s" % ("LOCATION", "OFFSET", "COUNT")
for i in drop_log.keys():
(sym, off) = get_sym(i)
if sym == None:
sym = i
print "%25s %25s %25s" % (sym, off, drop_log[i])
def trace_begin():
print "Starting trace (Ctrl-C to dump results)"
def trace_end():
print "Gathering kallsyms data"
get_kallsyms_table()
print_drop_table()
# called from perf, when it finds a correspoinding event
def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm,
skbaddr, location, protocol):
slocation = str(location)
try:
drop_log[slocation] = drop_log[slocation] + 1
except:
drop_log[slocation] = 1
| gpl-2.0 |
tjanez/ansible | lib/ansible/modules/system/gluster_volume.py | 14 | 17007 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Taneli Leppä <taneli@crasman.fi>
#
# This file is part of Ansible (sort of)
#
# 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/>.
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = """
module: gluster_volume
short_description: Manage GlusterFS volumes
description:
- Create, remove, start, stop and tune GlusterFS volumes
version_added: "1.9"
options:
name:
required: true
description:
- The volume name
state:
required: true
choices: [ 'present', 'absent', 'started', 'stopped' ]
description:
- Use present/absent ensure if a volume exists or not,
use started/stopped to control it's availability.
cluster:
required: false
default: null
description:
- List of hosts to use for probing and brick setup
host:
required: false
default: null
description:
- Override local hostname (for peer probing purposes)
replicas:
required: false
default: null
description:
- Replica count for volume
arbiter:
required: false
default: null
description:
- Arbiter count for volume
version_added: "2.3"
stripes:
required: false
default: null
description:
- Stripe count for volume
disperses:
required: false
default: null
description:
- Disperse count for volume
version_added: "2.2"
redundancies:
required: false
default: null
description:
- Redundancy count for volume
version_added: "2.2"
transport:
required: false
choices: [ 'tcp', 'rdma', 'tcp,rdma' ]
default: 'tcp'
description:
- Transport type for volume
bricks:
required: false
default: null
description:
- Brick paths on servers. Multiple brick paths can be separated by commas
aliases: ['brick']
start_on_create:
choices: [ 'yes', 'no']
required: false
default: 'yes'
description:
- Controls whether the volume is started after creation or not, defaults to yes
rebalance:
choices: [ 'yes', 'no']
required: false
default: 'no'
description:
- Controls whether the cluster is rebalanced after changes
directory:
required: false
default: null
description:
- Directory for limit-usage
options:
required: false
default: null
description:
- A dictionary/hash with options/settings for the volume
quota:
required: false
default: null
description:
- Quota value for limit-usage (be sure to use 10.0MB instead of 10MB, see quota list)
force:
required: false
default: null
description:
- If brick is being created in the root partition, module will fail.
Set force to true to override this behaviour
notes:
- "Requires cli tools for GlusterFS on servers"
- "Will add new bricks, but not remove them"
author: "Taneli Leppä (@rosmo)"
"""
EXAMPLES = """
- name: create gluster volume
gluster_volume:
state: present
name: test1
bricks: /bricks/brick1/g1
rebalance: yes
cluster:
- 192.0.2.10
- 192.0.2.11
run_once: true
- name: tune
gluster_volume:
state: present
name: test1
options:
performance.cache-size: 256MB
- name: start gluster volume
gluster_volume:
state: started
name: test1
- name: limit usage
gluster_volume:
state: present
name: test1
directory: /foo
quota: 20.0MB
- name: stop gluster volume
gluster_volume:
state: stopped
name: test1
- name: remove gluster volume
gluster_volume:
state: absent
name: test1
- name: create gluster volume with multiple bricks
gluster_volume:
state: present
name: test2
bricks: /bricks/brick1/g2,/bricks/brick2/g2
cluster:
- 192.0.2.10
- 192.0.2.11
run_once: true
"""
import shutil
import time
import socket
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.basic import *
glusterbin = ''
def run_gluster(gargs, **kwargs):
global glusterbin
global module
args = [glusterbin]
args.extend(gargs)
try:
rc, out, err = module.run_command(args, **kwargs)
if rc != 0:
module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
except Exception:
e = get_exception()
module.fail_json(msg='error running gluster (%s) command: %s' % (' '.join(args), str(e)))
return out
def run_gluster_nofail(gargs, **kwargs):
global glusterbin
global module
args = [glusterbin]
args.extend(gargs)
rc, out, err = module.run_command(args, **kwargs)
if rc != 0:
return None
return out
def run_gluster_yes(gargs):
global glusterbin
global module
args = [glusterbin]
args.extend(gargs)
rc, out, err = module.run_command(args, data='y\n')
if rc != 0:
module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
return out
def get_peers():
out = run_gluster([ 'peer', 'status'])
i = 0
peers = {}
hostname = None
uuid = None
state = None
shortNames = False
for row in out.split('\n'):
if ': ' in row:
key, value = row.split(': ')
if key.lower() == 'hostname':
hostname = value
shortNames = False
if key.lower() == 'uuid':
uuid = value
if key.lower() == 'state':
state = value
peers[hostname] = [ uuid, state ]
elif row.lower() == 'other names:':
shortNames = True
elif row != '' and shortNames == True:
peers[row] = [ uuid, state ]
elif row == '':
shortNames = False
return peers
def get_volumes():
out = run_gluster([ 'volume', 'info' ])
volumes = {}
volume = {}
for row in out.split('\n'):
if ': ' in row:
key, value = row.split(': ')
if key.lower() == 'volume name':
volume['name'] = value
volume['options'] = {}
volume['quota'] = False
if key.lower() == 'volume id':
volume['id'] = value
if key.lower() == 'status':
volume['status'] = value
if key.lower() == 'transport-type':
volume['transport'] = value
if value.lower().endswith(' (arbiter)'):
if not 'arbiters' in volume:
volume['arbiters'] = []
value = value[:-10]
volume['arbiters'].append(value)
if key.lower() != 'bricks' and key.lower()[:5] == 'brick':
if not 'bricks' in volume:
volume['bricks'] = []
volume['bricks'].append(value)
# Volume options
if '.' in key:
if not 'options' in volume:
volume['options'] = {}
volume['options'][key] = value
if key == 'features.quota' and value == 'on':
volume['quota'] = True
else:
if row.lower() != 'bricks:' and row.lower() != 'options reconfigured:':
if len(volume) > 0:
volumes[volume['name']] = volume
volume = {}
return volumes
def get_quotas(name, nofail):
quotas = {}
if nofail:
out = run_gluster_nofail([ 'volume', 'quota', name, 'list' ])
if not out:
return quotas
else:
out = run_gluster([ 'volume', 'quota', name, 'list' ])
for row in out.split('\n'):
if row[:1] == '/':
q = re.split('\s+', row)
quotas[q[0]] = q[1]
return quotas
def wait_for_peer(host):
for x in range(0, 4):
peers = get_peers()
if host in peers and peers[host][1].lower().find('peer in cluster') != -1:
return True
time.sleep(1)
return False
def probe(host, myhostname):
global module
out = run_gluster([ 'peer', 'probe', host ])
if out.find('localhost') == -1 and not wait_for_peer(host):
module.fail_json(msg='failed to probe peer %s on %s' % (host, myhostname))
changed = True
def probe_all_peers(hosts, peers, myhostname):
for host in hosts:
host = host.strip() # Clean up any extra space for exact comparison
if host not in peers:
probe(host, myhostname)
def create_volume(name, stripe, replica, arbiter, disperse, redundancy, transport, hosts, bricks, force):
args = [ 'volume', 'create' ]
args.append(name)
if stripe:
args.append('stripe')
args.append(str(stripe))
if replica:
args.append('replica')
args.append(str(replica))
if arbiter:
args.append('arbiter')
args.append(str(arbiter))
if disperse:
args.append('disperse')
args.append(str(disperse))
if redundancy:
args.append('redundancy')
args.append(str(redundancy))
args.append('transport')
args.append(transport)
for brick in bricks:
for host in hosts:
args.append(('%s:%s' % (host, brick)))
if force:
args.append('force')
run_gluster(args)
def start_volume(name):
run_gluster([ 'volume', 'start', name ])
def stop_volume(name):
run_gluster_yes([ 'volume', 'stop', name ])
def set_volume_option(name, option, parameter):
run_gluster([ 'volume', 'set', name, option, parameter ])
def add_bricks(name, new_bricks, stripe, replica, force):
args = [ 'volume', 'add-brick', name ]
if stripe:
args.append('stripe')
args.append(str(stripe))
if replica:
args.append('replica')
args.append(str(replica))
args.extend(new_bricks)
if force:
args.append('force')
run_gluster(args)
def do_rebalance(name):
run_gluster([ 'volume', 'rebalance', name, 'start' ])
def enable_quota(name):
run_gluster([ 'volume', 'quota', name, 'enable' ])
def set_quota(name, directory, value):
run_gluster([ 'volume', 'quota', name, 'limit-usage', directory, value ])
def main():
### MAIN ###
global module
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True, default=None, aliases=['volume']),
state=dict(required=True, choices=[ 'present', 'absent', 'started', 'stopped', 'rebalanced' ]),
cluster=dict(required=False, default=None, type='list'),
host=dict(required=False, default=None),
stripes=dict(required=False, default=None, type='int'),
replicas=dict(required=False, default=None, type='int'),
arbiters=dict(required=False, default=None, type='int'),
disperses=dict(required=False, default=None, type='int'),
redundancies=dict(required=False, default=None, type='int'),
transport=dict(required=False, default='tcp', choices=[ 'tcp', 'rdma', 'tcp,rdma' ]),
bricks=dict(required=False, default=None, aliases=['brick']),
start_on_create=dict(required=False, default=True, type='bool'),
rebalance=dict(required=False, default=False, type='bool'),
options=dict(required=False, default={}, type='dict'),
quota=dict(required=False),
directory=dict(required=False, default=None),
force=dict(required=False, default=False, type='bool'),
)
)
global glusterbin
glusterbin = module.get_bin_path('gluster', True)
changed = False
action = module.params['state']
volume_name = module.params['name']
cluster= module.params['cluster']
brick_paths = module.params['bricks']
stripes = module.params['stripes']
replicas = module.params['replicas']
arbiters = module.params['arbiters']
disperses = module.params['disperses']
redundancies = module.params['redundancies']
transport = module.params['transport']
myhostname = module.params['host']
start_on_create = module.boolean(module.params['start_on_create'])
rebalance = module.boolean(module.params['rebalance'])
force = module.boolean(module.params['force'])
if not myhostname:
myhostname = socket.gethostname()
# Clean up if last element is empty. Consider that yml can look like this:
# cluster="{% for host in groups['glusterfs'] %}{{ hostvars[host]['private_ip'] }},{% endfor %}"
if cluster is not None and len(cluster) > 1 and cluster[-1] == '':
cluster = cluster[0:-1]
if cluster is None or cluster[0] == '':
cluster = [myhostname]
if brick_paths is not None and "," in brick_paths:
brick_paths = brick_paths.split(",")
else:
brick_paths = [brick_paths]
options = module.params['options']
quota = module.params['quota']
directory = module.params['directory']
# get current state info
peers = get_peers()
volumes = get_volumes()
quotas = {}
if volume_name in volumes and volumes[volume_name]['quota'] and volumes[volume_name]['status'].lower() == 'started':
quotas = get_quotas(volume_name, True)
# do the work!
if action == 'absent':
if volume_name in volumes:
if volumes[volume_name]['status'].lower() != 'stopped':
stop_volume(volume_name)
run_gluster_yes([ 'volume', 'delete', volume_name ])
changed = True
if action == 'present':
probe_all_peers(cluster, peers, myhostname)
# create if it doesn't exist
if volume_name not in volumes:
create_volume(volume_name, stripes, replicas, arbiters, disperses, redundancies, transport, cluster, brick_paths, force)
volumes = get_volumes()
changed = True
if volume_name in volumes:
if volumes[volume_name]['status'].lower() != 'started' and start_on_create:
start_volume(volume_name)
changed = True
# switch bricks
new_bricks = []
removed_bricks = []
all_bricks = []
for node in cluster:
for brick_path in brick_paths:
brick = '%s:%s' % (node, brick_path)
all_bricks.append(brick)
if brick not in volumes[volume_name]['bricks']:
new_bricks.append(brick)
# this module does not yet remove bricks, but we check those anyways
for brick in volumes[volume_name]['bricks']:
if brick not in all_bricks:
removed_bricks.append(brick)
if new_bricks:
add_bricks(volume_name, new_bricks, stripes, replicas, force)
changed = True
# handle quotas
if quota:
if not volumes[volume_name]['quota']:
enable_quota(volume_name)
quotas = get_quotas(volume_name, False)
if directory not in quotas or quotas[directory] != quota:
set_quota(volume_name, directory, quota)
changed = True
# set options
for option in options.keys():
if option not in volumes[volume_name]['options'] or volumes[volume_name]['options'][option] != options[option]:
set_volume_option(volume_name, option, options[option])
changed = True
else:
module.fail_json(msg='failed to create volume %s' % volume_name)
if action != 'delete' and volume_name not in volumes:
module.fail_json(msg='volume not found %s' % volume_name)
if action == 'started':
if volumes[volume_name]['status'].lower() != 'started':
start_volume(volume_name)
changed = True
if action == 'stopped':
if volumes[volume_name]['status'].lower() != 'stopped':
stop_volume(volume_name)
changed = True
if changed:
volumes = get_volumes()
if rebalance:
do_rebalance(volume_name)
facts = {}
facts['glusterfs'] = { 'peers': peers, 'volumes': volumes, 'quotas': quotas }
module.exit_json(changed=changed, ansible_facts=facts)
if __name__ == '__main__':
main()
| gpl-3.0 |
bryantrobbins/baseball | shared/btr3baseball/JobRepository.py | 1 | 1924 | import boto3
import uuid
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
class JobRepository:
def __init__(self, jobTable):
self.table = boto3.resource('dynamodb').Table(jobTable)
def getJob(self, jobId):
try:
response = self.table.get_item(
Key={
'job-id': jobId
}
)
except ClientError as e:
print(e.response['Error']['Message'])
return None
else:
item = response['Item']
return item
def createJob(self, config):
# Generate job ID uuid
jobId = str(uuid.uuid4())
response = self.table.put_item(
Item={
'job-id': jobId,
'job-details': config
}
)
return jobId
def updateForSuccess(self, jobId):
print('Updating job record for success')
response = self.table.update_item(
Key={
'job-id': jobId
},
UpdateExpression="set #K = :m",
ExpressionAttributeNames={
"#K":"job-status"
},
ExpressionAttributeValues={
':m': "COMPLETE",
},
ReturnValues="UPDATED_NEW"
)
return response
def updateForError(self, jobId):
print('Updating job record for error')
def updateWithMessageId(self, jobId, messageId):
response = self.table.update_item(
Key={
'job-id': jobId
},
UpdateExpression="set #K = :m",
ExpressionAttributeNames={
"#K":"message-id"
},
ExpressionAttributeValues={
':m': messageId,
},
ReturnValues="ALL_NEW"
)
return response['Attributes']
| apache-2.0 |
kevclarx/ansible | lib/ansible/modules/database/mysql/mysql_db.py | 43 | 15371 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Mark Theunissen <mark.theunissen@gmail.com>
# Sponsored by Four Kitchens http://fourkitchens.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/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: mysql_db
short_description: Add or remove MySQL databases from a remote host.
description:
- Add or remove MySQL databases from a remote host.
version_added: "0.6"
options:
name:
description:
- name of the database to add or remove
- name=all May only be provided if I(state) is C(dump) or C(import).
- if name=all Works like --all-databases option for mysqldump (Added in 2.0)
required: true
default: null
aliases: [ db ]
state:
description:
- The database state
required: false
default: present
choices: [ "present", "absent", "dump", "import" ]
collation:
description:
- Collation mode (sorting). This only applies to new table/databases and does not update existing ones, this is a limitation of MySQL.
required: false
default: null
encoding:
description:
- Encoding mode to use, examples include C(utf8) or C(latin1_swedish_ci)
required: false
default: null
target:
description:
- Location, on the remote host, of the dump file to read from or write to. Uncompressed SQL
files (C(.sql)) as well as bzip2 (C(.bz2)), gzip (C(.gz)) and xz (Added in 2.0) compressed files are supported.
required: false
single_transaction:
description:
- Execute the dump in a single transaction
required: false
default: false
version_added: "2.1"
quick:
description:
- Option used for dumping large tables
required: false
default: true
version_added: "2.1"
author: "Ansible Core Team"
requirements:
- mysql (command line binary)
- mysqldump (command line binary)
notes:
- Requires the python-mysqldb package on the remote host, as well as mysql and mysqldump binaries.
extends_documentation_fragment: mysql
'''
EXAMPLES = '''
- name: Create a new database with name 'bobdata'
mysql_db:
name: bobdata
state: present
# Copy database dump file to remote host and restore it to database 'my_db'
- name: Copy database dump file
copy:
src: dump.sql.bz2
dest: /tmp
- name: Restore database
mysql_db:
name: my_db
state: import
target: /tmp/dump.sql.bz2
- name: Dump all databases to hostname.sql
mysql_db:
state: dump
name: all
target: /tmp/{{ inventory_hostname }}.sql
- name: Import file.sql similar to mysql -u <username> -p <password> < hostname.sql
mysql_db:
state: import
name: all
target: /tmp/{{ inventory_hostname }}.sql
'''
import os
import pipes
import stat
import subprocess
try:
import MySQLdb
except ImportError:
mysqldb_found = False
else:
mysqldb_found = True
# ===========================================
# MySQL module specific support methods.
#
def db_exists(cursor, db):
res = cursor.execute("SHOW DATABASES LIKE %s", (db.replace("_", "\_"),))
return bool(res)
def db_delete(cursor, db):
query = "DROP DATABASE %s" % mysql_quote_identifier(db, 'database')
cursor.execute(query)
return True
def db_dump(module, host, user, password, db_name, target, all_databases, port, config_file, socket=None, ssl_cert=None, ssl_key=None, ssl_ca=None,
single_transaction=None, quick=None):
cmd = module.get_bin_path('mysqldump', True)
# If defined, mysqldump demands --defaults-extra-file be the first option
if config_file:
cmd += " --defaults-extra-file=%s" % pipes.quote(config_file)
if user is not None:
cmd += " --user=%s" % pipes.quote(user)
if password is not None:
cmd += " --password=%s" % pipes.quote(password)
if ssl_cert is not None:
cmd += " --ssl-cert=%s" % pipes.quote(ssl_cert)
if ssl_key is not None:
cmd += " --ssl-key=%s" % pipes.quote(ssl_key)
if ssl_cert is not None:
cmd += " --ssl-ca=%s" % pipes.quote(ssl_ca)
if socket is not None:
cmd += " --socket=%s" % pipes.quote(socket)
else:
cmd += " --host=%s --port=%i" % (pipes.quote(host), port)
if all_databases:
cmd += " --all-databases"
else:
cmd += " %s" % pipes.quote(db_name)
if single_transaction:
cmd += " --single-transaction=true"
if quick:
cmd += " --quick"
path = None
if os.path.splitext(target)[-1] == '.gz':
path = module.get_bin_path('gzip', True)
elif os.path.splitext(target)[-1] == '.bz2':
path = module.get_bin_path('bzip2', True)
elif os.path.splitext(target)[-1] == '.xz':
path = module.get_bin_path('xz', True)
if path:
cmd = '%s | %s > %s' % (cmd, path, pipes.quote(target))
else:
cmd += " > %s" % pipes.quote(target)
rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)
return rc, stdout, stderr
def db_import(module, host, user, password, db_name, target, all_databases, port, config_file, socket=None, ssl_cert=None, ssl_key=None, ssl_ca=None):
if not os.path.exists(target):
return module.fail_json(msg="target %s does not exist on the host" % target)
cmd = [module.get_bin_path('mysql', True)]
# --defaults-file must go first, or errors out
if config_file:
cmd.append("--defaults-extra-file=%s" % pipes.quote(config_file))
if user:
cmd.append("--user=%s" % pipes.quote(user))
if password:
cmd.append("--password=%s" % pipes.quote(password))
if socket is not None:
cmd.append("--socket=%s" % pipes.quote(socket))
if ssl_cert is not None:
cmd.append("--ssl-cert=%s" % pipes.quote(ssl_cert))
if ssl_key is not None:
cmd.append("--ssl-key=%s" % pipes.quote(ssl_key))
if ssl_cert is not None:
cmd.append("--ssl-ca=%s" % pipes.quote(ssl_ca))
else:
cmd.append("--host=%s" % pipes.quote(host))
cmd.append("--port=%i" % port)
if not all_databases:
cmd.append("-D")
cmd.append(pipes.quote(db_name))
comp_prog_path = None
if os.path.splitext(target)[-1] == '.gz':
comp_prog_path = module.get_bin_path('gzip', required=True)
elif os.path.splitext(target)[-1] == '.bz2':
comp_prog_path = module.get_bin_path('bzip2', required=True)
elif os.path.splitext(target)[-1] == '.xz':
comp_prog_path = module.get_bin_path('xz', required=True)
if comp_prog_path:
p1 = subprocess.Popen([comp_prog_path, '-dc', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(cmd, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout2, stderr2) = p2.communicate()
p1.stdout.close()
p1.wait()
if p1.returncode != 0:
stderr1 = p1.stderr.read()
return p1.returncode, '', stderr1
else:
return p2.returncode, stdout2, stderr2
else:
cmd = ' '.join(cmd)
cmd += " < %s" % pipes.quote(target)
rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)
return rc, stdout, stderr
def db_create(cursor, db, encoding, collation):
query_params = dict(enc=encoding, collate=collation)
query = ['CREATE DATABASE %s' % mysql_quote_identifier(db, 'database')]
if encoding:
query.append("CHARACTER SET %(enc)s")
if collation:
query.append("COLLATE %(collate)s")
query = ' '.join(query)
cursor.execute(query, query_params)
return True
# ===========================================
# Module execution.
#
def main():
module = AnsibleModule(
argument_spec=dict(
login_user=dict(default=None),
login_password=dict(default=None, no_log=True),
login_host=dict(default="localhost"),
login_port=dict(default=3306, type='int'),
login_unix_socket=dict(default=None),
name=dict(required=True, aliases=['db']),
encoding=dict(default=""),
collation=dict(default=""),
target=dict(default=None, type='path'),
state=dict(default="present", choices=["absent", "present", "dump", "import"]),
ssl_cert=dict(default=None, type='path'),
ssl_key=dict(default=None, type='path'),
ssl_ca=dict(default=None, type='path'),
connect_timeout=dict(default=30, type='int'),
config_file=dict(default="~/.my.cnf", type='path'),
single_transaction=dict(default=False, type='bool'),
quick=dict(default=True, type='bool'),
),
supports_check_mode=True
)
if not mysqldb_found:
module.fail_json(msg="the python mysqldb module is required")
db = module.params["name"]
encoding = module.params["encoding"]
collation = module.params["collation"]
state = module.params["state"]
target = module.params["target"]
socket = module.params["login_unix_socket"]
login_port = module.params["login_port"]
if login_port < 0 or login_port > 65535:
module.fail_json(msg="login_port must be a valid unix port number (0-65535)")
ssl_cert = module.params["ssl_cert"]
ssl_key = module.params["ssl_key"]
ssl_ca = module.params["ssl_ca"]
connect_timeout = module.params['connect_timeout']
config_file = module.params['config_file']
login_password = module.params["login_password"]
login_user = module.params["login_user"]
login_host = module.params["login_host"]
single_transaction = module.params["single_transaction"]
quick = module.params["quick"]
if state in ['dump', 'import']:
if target is None:
module.fail_json(msg="with state=%s target is required" % state)
if db == 'all':
db = 'mysql'
all_databases = True
else:
all_databases = False
else:
if db == 'all':
module.fail_json(msg="name is not allowed to equal 'all' unless state equals import, or dump.")
try:
cursor = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca,
connect_timeout=connect_timeout)
except Exception:
e = get_exception()
if os.path.exists(config_file):
module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or %s has the credentials. "
"Exception message: %s" % (config_file, e))
else:
module.fail_json(msg="unable to find %s. Exception message: %s" % (config_file, e))
changed = False
if not os.path.exists(config_file):
config_file = None
if db_exists(cursor, db):
if state == "absent":
if module.check_mode:
module.exit_json(changed=True, db=db)
else:
try:
changed = db_delete(cursor, db)
except Exception:
e = get_exception()
module.fail_json(msg="error deleting database: " + str(e))
module.exit_json(changed=changed, db=db)
elif state == "dump":
if module.check_mode:
module.exit_json(changed=True, db=db)
else:
rc, stdout, stderr = db_dump(module, login_host, login_user,
login_password, db, target, all_databases,
login_port, config_file, socket, ssl_cert, ssl_key,
ssl_ca, single_transaction, quick)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db, msg=stdout)
elif state == "import":
if module.check_mode:
module.exit_json(changed=True, db=db)
else:
rc, stdout, stderr = db_import(module, login_host, login_user,
login_password, db, target,
all_databases,
login_port, config_file,
socket, ssl_cert, ssl_key, ssl_ca)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db, msg=stdout)
elif state == "present":
if module.check_mode:
module.exit_json(changed=False, db=db)
module.exit_json(changed=False, db=db)
else:
if state == "present":
if module.check_mode:
changed = True
else:
try:
changed = db_create(cursor, db, encoding, collation)
except Exception:
e = get_exception()
module.fail_json(msg="error creating database: " + str(e))
module.exit_json(changed=changed, db=db)
elif state == "import":
if module.check_mode:
module.exit_json(changed=True, db=db)
else:
try:
changed = db_create(cursor, db, encoding, collation)
if changed:
rc, stdout, stderr = db_import(module, login_host, login_user,
login_password, db, target, all_databases,
login_port, config_file, socket, ssl_cert, ssl_key, ssl_ca)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db, msg=stdout)
except Exception:
e = get_exception()
module.fail_json(msg="error creating database: " + str(e))
elif state == "absent":
if module.check_mode:
module.exit_json(changed=False, db=db)
module.exit_json(changed=False, db=db)
elif state == "dump":
if module.check_mode:
module.exit_json(changed=False, db=db)
module.fail_json(msg="Cannot dump database %s - not found" % (db))
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.database import *
from ansible.module_utils.mysql import *
if __name__ == '__main__':
main()
| gpl-3.0 |
adaussy/eclipse-monkey-revival | plugins/python/org.eclipse.eclipsemonkey.lang.python/Lib/base64.py | 229 | 11357 | #! /usr/bin/env python
"""RFC 3548: Base16, Base32, Base64 Data Encodings"""
# Modified 04-Oct-1995 by Jack Jansen to use binascii module
# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support
import re
import struct
import binascii
__all__ = [
# Legacy interface exports traditional RFC 1521 Base64 encodings
'encode', 'decode', 'encodestring', 'decodestring',
# Generalized interface for other encodings
'b64encode', 'b64decode', 'b32encode', 'b32decode',
'b16encode', 'b16decode',
# Standard Base64 encoding
'standard_b64encode', 'standard_b64decode',
# Some common Base64 alternatives. As referenced by RFC 3458, see thread
# starting at:
#
# http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html
'urlsafe_b64encode', 'urlsafe_b64decode',
]
_translation = [chr(_x) for _x in range(256)]
EMPTYSTRING = ''
def _translate(s, altchars):
translation = _translation[:]
for k, v in altchars.items():
translation[ord(k)] = v
return s.translate(''.join(translation))
# Base64 encoding/decoding uses binascii
def b64encode(s, altchars=None):
"""Encode a string using Base64.
s is the string to encode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The encoded string is returned.
"""
# Strip off the trailing newline
encoded = binascii.b2a_base64(s)[:-1]
if altchars is not None:
return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
return encoded
def b64decode(s, altchars=None):
"""Decode a Base64 encoded string.
s is the string to decode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies the
alternative alphabet used instead of the '+' and '/' characters.
The decoded string is returned. A TypeError is raised if s were
incorrectly padded or if there are non-alphabet characters present in the
string.
"""
if altchars is not None:
s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
try:
return binascii.a2b_base64(s)
except binascii.Error, msg:
# Transform this exception for consistency
raise TypeError(msg)
def standard_b64encode(s):
"""Encode a string using the standard Base64 alphabet.
s is the string to encode. The encoded string is returned.
"""
return b64encode(s)
def standard_b64decode(s):
"""Decode a string encoded with the standard Base64 alphabet.
s is the string to decode. The decoded string is returned. A TypeError
is raised if the string is incorrectly padded or if there are non-alphabet
characters present in the string.
"""
return b64decode(s)
def urlsafe_b64encode(s):
"""Encode a string using a url-safe Base64 alphabet.
s is the string to encode. The encoded string is returned. The alphabet
uses '-' instead of '+' and '_' instead of '/'.
"""
return b64encode(s, '-_')
def urlsafe_b64decode(s):
"""Decode a string encoded with the standard Base64 alphabet.
s is the string to decode. The decoded string is returned. A TypeError
is raised if the string is incorrectly padded or if there are non-alphabet
characters present in the string.
The alphabet uses '-' instead of '+' and '_' instead of '/'.
"""
return b64decode(s, '-_')
# Base32 encoding/decoding must be done in Python
_b32alphabet = {
0: 'A', 9: 'J', 18: 'S', 27: '3',
1: 'B', 10: 'K', 19: 'T', 28: '4',
2: 'C', 11: 'L', 20: 'U', 29: '5',
3: 'D', 12: 'M', 21: 'V', 30: '6',
4: 'E', 13: 'N', 22: 'W', 31: '7',
5: 'F', 14: 'O', 23: 'X',
6: 'G', 15: 'P', 24: 'Y',
7: 'H', 16: 'Q', 25: 'Z',
8: 'I', 17: 'R', 26: '2',
}
_b32tab = _b32alphabet.items()
_b32tab.sort()
_b32tab = [v for k, v in _b32tab]
_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()])
def b32encode(s):
"""Encode a string using Base32.
s is the string to encode. The encoded string is returned.
"""
parts = []
quanta, leftover = divmod(len(s), 5)
# Pad the last quantum with zero bits if necessary
if leftover:
s += ('\0' * (5 - leftover))
quanta += 1
for i in range(quanta):
# c1 and c2 are 16 bits wide, c3 is 8 bits wide. The intent of this
# code is to process the 40 bits in units of 5 bits. So we take the 1
# leftover bit of c1 and tack it onto c2. Then we take the 2 leftover
# bits of c2 and tack them onto c3. The shifts and masks are intended
# to give us values of exactly 5 bits in width.
c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5])
c2 += (c1 & 1) << 16 # 17 bits wide
c3 += (c2 & 3) << 8 # 10 bits wide
parts.extend([_b32tab[c1 >> 11], # bits 1 - 5
_b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10
_b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15
_b32tab[c2 >> 12], # bits 16 - 20 (1 - 5)
_b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)
_b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)
_b32tab[c3 >> 5], # bits 31 - 35 (1 - 5)
_b32tab[c3 & 0x1f], # bits 36 - 40 (1 - 5)
])
encoded = EMPTYSTRING.join(parts)
# Adjust for any leftover partial quanta
if leftover == 1:
return encoded[:-6] + '======'
elif leftover == 2:
return encoded[:-4] + '===='
elif leftover == 3:
return encoded[:-3] + '==='
elif leftover == 4:
return encoded[:-1] + '='
return encoded
def b32decode(s, casefold=False, map01=None):
"""Decode a Base32 encoded string.
s is the string to decode. Optional casefold is a flag specifying whether
a lowercase alphabet is acceptable as input. For security purposes, the
default is False.
RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O
(oh), and for optional mapping of the digit 1 (one) to either the letter I
(eye) or letter L (el). The optional argument map01 when not None,
specifies which letter the digit 1 should be mapped to (when map01 is not
None, the digit 0 is always mapped to the letter O). For security
purposes the default is None, so that 0 and 1 are not allowed in the
input.
The decoded string is returned. A TypeError is raised if s were
incorrectly padded or if there are non-alphabet characters present in the
string.
"""
quanta, leftover = divmod(len(s), 8)
if leftover:
raise TypeError('Incorrect padding')
# Handle section 2.4 zero and one mapping. The flag map01 will be either
# False, or the character to map the digit 1 (one) to. It should be
# either L (el) or I (eye).
if map01:
s = _translate(s, {'0': 'O', '1': map01})
if casefold:
s = s.upper()
# Strip off pad characters from the right. We need to count the pad
# characters because this will tell us how many null bytes to remove from
# the end of the decoded string.
padchars = 0
mo = re.search('(?P<pad>[=]*)$', s)
if mo:
padchars = len(mo.group('pad'))
if padchars > 0:
s = s[:-padchars]
# Now decode the full quanta
parts = []
acc = 0
shift = 35
for c in s:
val = _b32rev.get(c)
if val is None:
raise TypeError('Non-base32 digit found')
acc += _b32rev[c] << shift
shift -= 5
if shift < 0:
parts.append(binascii.unhexlify('%010x' % acc))
acc = 0
shift = 35
# Process the last, partial quanta
last = binascii.unhexlify('%010x' % acc)
if padchars == 0:
last = '' # No characters
elif padchars == 1:
last = last[:-1]
elif padchars == 3:
last = last[:-2]
elif padchars == 4:
last = last[:-3]
elif padchars == 6:
last = last[:-4]
else:
raise TypeError('Incorrect padding')
parts.append(last)
return EMPTYSTRING.join(parts)
# RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns
# lowercase. The RFC also recommends against accepting input case
# insensitively.
def b16encode(s):
"""Encode a string using Base16.
s is the string to encode. The encoded string is returned.
"""
return binascii.hexlify(s).upper()
def b16decode(s, casefold=False):
"""Decode a Base16 encoded string.
s is the string to decode. Optional casefold is a flag specifying whether
a lowercase alphabet is acceptable as input. For security purposes, the
default is False.
The decoded string is returned. A TypeError is raised if s were
incorrectly padded or if there are non-alphabet characters present in the
string.
"""
if casefold:
s = s.upper()
if re.search('[^0-9A-F]', s):
raise TypeError('Non-base16 digit found')
return binascii.unhexlify(s)
# Legacy interface. This code could be cleaned up since I don't believe
# binascii has any line length limitations. It just doesn't seem worth it
# though.
MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE//4)*3
def encode(input, output):
"""Encode a file."""
while True:
s = input.read(MAXBINSIZE)
if not s:
break
while len(s) < MAXBINSIZE:
ns = input.read(MAXBINSIZE-len(s))
if not ns:
break
s += ns
line = binascii.b2a_base64(s)
output.write(line)
def decode(input, output):
"""Decode a file."""
while True:
line = input.readline()
if not line:
break
s = binascii.a2b_base64(line)
output.write(s)
def encodestring(s):
"""Encode a string into multiple lines of base-64 data."""
pieces = []
for i in range(0, len(s), MAXBINSIZE):
chunk = s[i : i + MAXBINSIZE]
pieces.append(binascii.b2a_base64(chunk))
return "".join(pieces)
def decodestring(s):
"""Decode a string."""
return binascii.a2b_base64(s)
# Useable as a script...
def test():
"""Small test program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
with open(args[0], 'rb') as f:
func(f, sys.stdout)
else:
func(sys.stdin, sys.stdout)
def test1():
s0 = "Aladdin:open sesame"
s1 = encodestring(s0)
s2 = decodestring(s1)
print s0, repr(s1), s2
if __name__ == '__main__':
test()
| epl-1.0 |
eriser/picasso-graphic | tools/gyp/build/lib/gyp/MSVSSettings_test.py | 778 | 65880 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for the MSVSSettings.py file."""
import StringIO
import unittest
import gyp.MSVSSettings as MSVSSettings
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.stderr = StringIO.StringIO()
def _ExpectedWarnings(self, expected):
"""Compares recorded lines to expected warnings."""
self.stderr.seek(0)
actual = self.stderr.read().split('\n')
actual = [line for line in actual if line]
self.assertEqual(sorted(expected), sorted(actual))
def testValidateMSVSSettings_tool_names(self):
"""Tests that only MSVS tool names are allowed."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {},
'VCLinkerTool': {},
'VCMIDLTool': {},
'foo': {},
'VCResourceCompilerTool': {},
'VCLibrarianTool': {},
'VCManifestTool': {},
'ClCompile': {}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized tool foo',
'Warning: unrecognized tool ClCompile'])
def testValidateMSVSSettings_settings(self):
"""Tests that for invalid MSVS settings."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '5',
'BrowseInformation': 'fdkslj',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '-1',
'CompileAs': '1',
'DebugInformationFormat': '2',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': '1',
'ExceptionHandling': '1',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '1',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '1',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'string1;string2',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '1',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '1',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '2',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'CLRImageType': '2',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '2',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': '2',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'ErrorReporting': '2',
'FixedBaseAddress': '2',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '2',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '2',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '2',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '2',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '2',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'true',
'Version': 'a string1'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'CPreprocessOptions': 'a string1',
'DefaultCharType': '1',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '1',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'notgood': 'bogus',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'VCResourceCompilerTool': {
'AdditionalOptions': 'a string1',
'AdditionalIncludeDirectories': 'folder1;folder2',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'notgood2': 'bogus',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a string1',
'ManifestResourceFile': 'a_file_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'truel',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}},
self.stderr)
self._ExpectedWarnings([
'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '
'index value (5) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/BrowseInformation, '
"invalid literal for int() with base 10: 'fdkslj'",
'Warning: for VCCLCompilerTool/CallingConvention, '
'index value (-1) not in expected range [0, 3)',
'Warning: for VCCLCompilerTool/DebugInformationFormat, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCCLCompilerTool/Enableprefast',
'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ',
'Warning: for VCLinkerTool/TargetMachine, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCMIDLTool/notgood',
'Warning: unrecognized setting VCResourceCompilerTool/notgood2',
'Warning: for VCManifestTool/UpdateFileHashes, '
"expected bool; got 'truel'"
''])
def testValidateMSBuildSettings_settings(self):
"""Tests that for invalid MSBuild settings."""
MSVSSettings.ValidateMSBuildSettings(
{'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'false',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'BuildingInIDE': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'CompileAsManaged': 'Pure',
'CreateHotpatchableImage': 'true',
'DebugInformationFormat': 'ProgramDatabase',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'SyncCThrow',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Precise',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'FunctionLevelLinking': 'false',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'false',
'MinimalRebuild': 'true',
'MultiProcessorCompilation': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Disabled',
'PrecompiledHeader': 'NotUsing',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'string1;string2',
'PreprocessOutputPath': 'a string1',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'false',
'ProcessorNumber': '33',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TreatSpecificWarningsAsErrors': 'string1;string2',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UseUnicodeForAssemblerListing': 'true',
'WarningLevel': 'TurnOffAllWarnings',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'Link': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'BuildingInIDE': 'true',
'CLRImageType': 'ForceIJWImage',
'CLRSupportLastError': 'Enabled',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'CreateHotPatchableImage': 'X86Image',
'DataExecutionPrevention': 'false',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': 'NotSet',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'FixedBaseAddress': 'false',
'ForceFileOutput': 'Enabled',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'a_file_list',
'ImageHasSafeExceptionHandlers': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'false',
'LinkDLL': 'true',
'LinkErrorReporting': 'SendErrorReport',
'LinkStatus': 'true',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'MSDOSStubFileName': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': 'false',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'PreventDllBinding': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SectionAlignment': '33',
'SetChecksum': 'true',
'ShowProgress': 'LinkVerboseREF',
'SpecifySectionAttributes': 'a string1',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Console',
'SupportNobindOfDelayLoadedDLL': 'true',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TrackerLogDirectory': 'a_folder',
'TreatLinkerWarningAsErrors': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'AsInvoker',
'UACUIAccess': 'true',
'Version': 'a string1'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'Culture': '0x236',
'IgnoreStandardIncludePath': 'true',
'NullTerminateStrings': 'true',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ApplicationConfigurationMode': 'true',
'ClientStubFile': 'a_file_name',
'CPreprocessOptions': 'a string1',
'DefaultCharType': 'Signed',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'EnableCustom',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateClientFiles': 'Stub',
'GenerateServerFiles': 'None',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'LocaleID': '33',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'ServerStubFile': 'a_file_name',
'StructMemberAlignment': 'NotSet',
'SuppressCompilerWarnings': 'true',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Itanium',
'TrackerLogDirectory': 'a_folder',
'TypeLibFormat': 'NewFormat',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'Lib': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'DisplayLibrary': 'a string1',
'ErrorReporting': 'PromptImmediately',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkTimeCodeGeneration': 'true',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'Name': 'a_file_name',
'OutputFile': 'a_file_name',
'RemoveObjects': 'file1;file2',
'SubSystem': 'Console',
'SuppressStartupBanner': 'true',
'TargetMachine': 'MachineX86i',
'TrackerLogDirectory': 'a_folder',
'TreatLibWarningAsErrors': 'true',
'UseUnicodeResponseFiles': 'true',
'Verbose': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'EnableDPIAwareness': 'fal',
'GenerateCatalogFiles': 'truel',
'GenerateCategoryTags': 'true',
'InputResourceManifests': 'a string1',
'ManifestFromManagedAssembly': 'a_file_name',
'notgood3': 'bogus',
'OutputManifestFile': 'a_file_name',
'OutputResourceManifests': 'a string1',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressDependencyElement': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'a_file_name'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized setting ClCompile/Enableprefast',
'Warning: unrecognized setting ClCompile/ZZXYZ',
'Warning: unrecognized setting Manifest/notgood3',
'Warning: for Manifest/GenerateCatalogFiles, '
"expected bool; got 'truel'",
'Warning: for Lib/TargetMachine, unrecognized enumerated value '
'MachineX86i',
"Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"])
def testConvertToMSBuildSettings_empty(self):
"""Tests an empty conversion."""
msvs_settings = {}
expected_msbuild_settings = {}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_minimal(self):
"""Tests a minimal conversion."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': '0',
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': '1',
'ErrorReporting': '1',
'DataExecutionPrevention': '2',
},
}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': 'Default',
},
'Link': {
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'LinkErrorReporting': 'PromptImmediately',
'DataExecutionPrevention': 'true',
},
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_warnings(self):
"""Tests conversion that generates warnings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2',
# These are incorrect values:
'BasicRuntimeChecks': '12',
'BrowseInformation': '21',
'UsePrecompiledHeader': '13',
'GeneratePreprocessedFile': '14'},
'VCLinkerTool': {
# These are incorrect values:
'Driver': '10',
'LinkTimeCodeGeneration': '31',
'ErrorReporting': '21',
'FixedBaseAddress': '6'},
'VCResourceCompilerTool': {
# Custom
'Culture': '1003'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2'},
'Link': {},
'ResourceCompile': {
# Custom
'Culture': '0x03eb'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([
'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to '
'MSBuild, index value (12) not in expected range [0, 4)',
'Warning: while converting VCCLCompilerTool/BrowseInformation to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to '
'MSBuild, index value (13) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to '
'MSBuild, value must be one of [0, 1, 2]; got 14',
'Warning: while converting VCLinkerTool/Driver to '
'MSBuild, index value (10) not in expected range [0, 4)',
'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to '
'MSBuild, index value (31) not in expected range [0, 5)',
'Warning: while converting VCLinkerTool/ErrorReporting to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCLinkerTool/FixedBaseAddress to '
'MSBuild, index value (6) not in expected range [0, 3)',
])
def testConvertToMSBuildSettings_full_synthetic(self):
"""Tests conversion of all the MSBuild settings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '1',
'BrowseInformation': '2',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '0',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': '0',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '1',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '0',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '2',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '0',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '0',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': '1',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': '1',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '0',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'ErrorReporting': '0',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2;file3',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '1',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '0',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '0',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '3',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '1',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'false',
'UseUnicodeResponseFiles': 'true',
'Version': 'a_string'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': '0',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '2',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'EmbedManifest': 'true',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'ManifestResourceFile': 'my_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string /J',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'true',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': 'NotSet',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'AnySuitable',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'Create',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'WarningLevel': 'Level2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'Link': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': 'ForceIJWImage',
'CLRThreadAttribute': 'STAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': 'Driver',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'NoErrorReport',
'LinkTimeCodeGeneration': 'PGInstrument',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': '',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'true',
'ShowProgress': 'NotSet',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Windows',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineARM',
'TerminalServerAware': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'HighestAvailable',
'UACUIAccess': 'true',
'Version': 'a_string'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '0x03eb',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': 'Unsigned',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'All',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '4',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Win32',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'Lib': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'my_name'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'false'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_actual(self):
"""Tests the conversion of an actual project.
A VS2008 project with most of the options defined was created through the
VS2008 IDE. It was then converted to VS2010. The tool settings found in
the .vcproj and .vcxproj files were converted to the two dictionaries
msvs_settings and expected_msbuild_settings.
Note that for many settings, the VS2010 converter adds macros like
%(AdditionalIncludeDirectories) to make sure than inherited values are
included. Since the Gyp projects we generate do not use inheritance,
we removed these macros. They were:
ClCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)'
AdditionalOptions: ' %(AdditionalOptions)'
AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)'
DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
ForcedIncludeFiles: ';%(ForcedIncludeFiles)',
ForcedUsingFiles: ';%(ForcedUsingFiles)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
UndefinePreprocessorDefinitions:
';%(UndefinePreprocessorDefinitions)',
Link:
AdditionalDependencies: ';%(AdditionalDependencies)',
AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)',
AdditionalManifestDependencies:
';%(AdditionalManifestDependencies)',
AdditionalOptions: ' %(AdditionalOptions)',
AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)',
AssemblyLinkResource: ';%(AssemblyLinkResource)',
DelayLoadDLLs: ';%(DelayLoadDLLs)',
EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)',
ForceSymbolReferences: ';%(ForceSymbolReferences)',
IgnoreSpecificDefaultLibraries:
';%(IgnoreSpecificDefaultLibraries)',
ResourceCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)',
AdditionalOptions: ' %(AdditionalOptions)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
Manifest:
AdditionalManifestFiles: ';%(AdditionalManifestFiles)',
AdditionalOptions: ' %(AdditionalOptions)',
InputResourceManifests: ';%(InputResourceManifests)',
"""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)\\a',
'AssemblerOutput': '1',
'BasicRuntimeChecks': '3',
'BrowseInformation': '1',
'BrowseInformationFile': '$(IntDir)\\e',
'BufferSecurityCheck': 'false',
'CallingConvention': '1',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '2',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '2',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'GeneratePreprocessedFile': '2',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': '$(IntDir)\\b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche',
'PrecompiledHeaderThrough': 'StdAfx.hd',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb',
'RuntimeLibrary': '3',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'false',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '0',
'UseUnicodeResponseFiles': 'false',
'WarnAsError': 'true',
'WarningLevel': '3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)\\c'},
'VCLinkerTool': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': '1',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': '3',
'CLRThreadAttribute': '1',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': '1',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'ErrorReporting': '2',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'false',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'flob;flok',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': '2',
'LinkIncremental': '0',
'LinkLibraryDependencies': 'false',
'LinkTimeCodeGeneration': '1',
'ManifestFile':
'$(IntDir)\\$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'OptimizeForWindows98': '2',
'OptimizeReferences': '2',
'OutputFile': '$(OutDir)\\$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'false',
'ShowProgress': '1',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': '1',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '1',
'TerminalServerAware': '1',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'false',
'Version': '333'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '3084',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res',
'ShowProgress': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'DependencyInformationFile': '$(IntDir)\\mt.depdfd',
'EmbedManifest': 'false',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'ManifestResourceFile':
'$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'false',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more /J',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)a',
'AssemblerOutput': 'AssemblyCode',
'BasicRuntimeChecks': 'EnableFastChecks',
'BrowseInformation': 'true',
'BrowseInformationFile': '$(IntDir)e',
'BufferSecurityCheck': 'false',
'CallingConvention': 'FastCall',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Queue',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Size',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': '$(IntDir)b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'NotUsing', # Actual conversion gives ''
'PrecompiledHeaderFile': 'StdAfx.hd',
'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'PreprocessSuppressLineNumbers': 'true',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb',
'RuntimeLibrary': 'MultiThreadedDebugDLL',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '4Bytes',
'SuppressStartupBanner': 'false',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'WarningLevel': 'Level3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)c'},
'Link': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': 'true',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': 'ForceSafeILImage',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': 'UpOnly',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'flob;flok',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'QueueForNextLogin',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'NoEntryPoint': 'true',
'OptimizeReferences': 'true',
'OutputFile': '$(OutDir)$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'false',
'ShowProgress': 'LinkVerbose',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': 'Console',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': 'RequireAdministrator',
'UACUIAccess': 'true',
'Version': '333'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '0x0c0c',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)%(Filename)3.res',
'ShowProgress': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'false',
'UseLibraryDependencyInputs': 'true'},
'': {
'EmbedManifest': 'false',
'GenerateManifest': 'false',
'IgnoreImportLibrary': 'true',
'LinkIncremental': ''
},
'ManifestResourceCompile': {
'ResourceOutputFileName':
'$(IntDir)$(TargetFileName).embed.manifest.resfdsf'}
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
wetneb/django | tests/urlpatterns_reverse/urls.py | 12 | 4424 | import warnings
from django.conf.urls import include, patterns, url
from django.utils.deprecation import RemovedInDjango20Warning
from .views import (
absolute_kwargs_view, defaults_view, empty_view, empty_view_partial,
empty_view_wrapped, nested_view,
)
other_patterns = [
url(r'non_path_include/$', empty_view, name='non_path_include'),
url(r'nested_path/$', nested_view),
]
# test deprecated patterns() function. convert to list of urls() in Django 2.0
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)
urlpatterns = patterns('',
url(r'^places/([0-9]+)/$', empty_view, name='places'),
url(r'^places?/$', empty_view, name="places?"),
url(r'^places+/$', empty_view, name="places+"),
url(r'^places*/$', empty_view, name="places*"),
url(r'^(?:places/)?$', empty_view, name="places2?"),
url(r'^(?:places/)+$', empty_view, name="places2+"),
url(r'^(?:places/)*$', empty_view, name="places2*"),
url(r'^places/([0-9]+|[a-z_]+)/', empty_view, name="places3"),
url(r'^places/(?P<id>[0-9]+)/$', empty_view, name="places4"),
url(r'^people/(?P<name>\w+)/$', empty_view, name="people"),
url(r'^people/(?:name/)', empty_view, name="people2"),
url(r'^people/(?:name/(\w+)/)?', empty_view, name="people2a"),
url(r'^people/(?P<name>\w+)-(?P=name)/$', empty_view, name="people_backref"),
url(r'^optional/(?P<name>.*)/(?:.+/)?', empty_view, name="optional"),
url(r'^hardcoded/$', empty_view, name="hardcoded"),
url(r'^hardcoded/doc\.pdf$', empty_view, name="hardcoded2"),
url(r'^people/(?P<state>\w\w)/(?P<name>\w+)/$', empty_view, name="people3"),
url(r'^people/(?P<state>\w\w)/(?P<name>[0-9])/$', empty_view, name="people4"),
url(r'^people/((?P<state>\w\w)/test)?/(\w+)/$', empty_view, name="people6"),
url(r'^character_set/[abcdef0-9]/$', empty_view, name="range"),
url(r'^character_set/[\w]/$', empty_view, name="range2"),
url(r'^price/\$([0-9]+)/$', empty_view, name="price"),
url(r'^price/[$]([0-9]+)/$', empty_view, name="price2"),
url(r'^price/[\$]([0-9]+)/$', empty_view, name="price3"),
url(r'^product/(?P<product>\w+)\+\(\$(?P<price>[0-9]+(\.[0-9]+)?)\)/$', empty_view, name="product"),
url(r'^headlines/(?P<year>[0-9]+)\.(?P<month>[0-9]+)\.(?P<day>[0-9]+)/$', empty_view, name="headlines"),
url(r'^windows_path/(?P<drive_name>[A-Z]):\\(?P<path>.+)/$', empty_view, name="windows"),
url(r'^special_chars/(?P<chars>.+)/$', empty_view, name="special"),
url(r'^(?P<name>.+)/[0-9]+/$', empty_view, name="mixed"),
url(r'^repeats/a{1,2}/$', empty_view, name="repeats"),
url(r'^repeats/a{2,4}/$', empty_view, name="repeats2"),
url(r'^repeats/a{2}/$', empty_view, name="repeats3"),
url(r'^(?i)CaseInsensitive/(\w+)', empty_view, name="insensitive"),
url(r'^test/1/?', empty_view, name="test"),
url(r'^(?i)test/2/?$', empty_view, name="test2"),
url(r'^outer/(?P<outer>[0-9]+)/', include('urlpatterns_reverse.included_urls')),
url(r'^outer-no-kwargs/([0-9]+)/', include('urlpatterns_reverse.included_no_kwargs_urls')),
url('', include('urlpatterns_reverse.extra_urls')),
# Partials should be fine.
url(r'^partial/', empty_view_partial, name="partial"),
url(r'^partial_wrapped/', empty_view_wrapped, name="partial_wrapped"),
# This is non-reversible, but we shouldn't blow up when parsing it.
url(r'^(?:foo|bar)(\w+)/$', empty_view, name="disjunction"),
# Regression views for #9038. See tests for more details
url(r'arg_view/$', 'urlpatterns_reverse.views.kwargs_view'),
url(r'arg_view/(?P<arg1>[0-9]+)/$', 'urlpatterns_reverse.views.kwargs_view'),
url(r'absolute_arg_view/(?P<arg1>[0-9]+)/$', absolute_kwargs_view),
url(r'absolute_arg_view/$', absolute_kwargs_view),
# Tests for #13154. Mixed syntax to test both ways of defining URLs.
url(r'defaults_view1/(?P<arg1>[0-9]+)/', defaults_view, {'arg2': 1}, name='defaults'),
(r'defaults_view2/(?P<arg1>[0-9]+)/', defaults_view, {'arg2': 2}, 'defaults'),
url('^includes/', include(other_patterns)),
# Security tests
url('(.+)/security/$', empty_view, name='security'),
)
| bsd-3-clause |
mnahm5/django-estore | Lib/site-packages/troposphere/awslambda.py | 2 | 4948 | from . import AWSObject, AWSProperty, Join
from .validators import positive_integer
MEMORY_VALUES = [x for x in range(128, 1600, 64)]
def validate_memory_size(memory_value):
""" Validate memory size for Lambda Function
:param memory_value: The memory size specified in the Function
:return: The provided memory size if it is valid
"""
memory_value = int(positive_integer(memory_value))
if memory_value not in MEMORY_VALUES:
raise ValueError("Lambda Function memory size must be one of:\n %s" %
", ".join(str(mb) for mb in MEMORY_VALUES))
return memory_value
class Code(AWSProperty):
props = {
'S3Bucket': (basestring, False),
'S3Key': (basestring, False),
'S3ObjectVersion': (basestring, False),
'ZipFile': (basestring, False)
}
@staticmethod
def check_zip_file(zip_file):
maxlength = 4096
toolong = (
"ZipFile length cannot exceed %d characters. For larger "
"source use S3Bucket/S3Key properties instead. "
"Current length: %d"
)
if zip_file is None:
return
if isinstance(zip_file, basestring):
z_length = len(zip_file)
if z_length > maxlength:
raise ValueError(toolong % (maxlength, z_length))
return
if isinstance(zip_file, Join):
# This code tries to combine the length of all the strings in a
# join. If a part is not a string, we do not count it (length 0).
delimiter, values = zip_file.data['Fn::Join']
# Return if there are no values to join
if not values or len(values) <= 0:
return
# Get the length of the delimiter
if isinstance(delimiter, basestring):
d_length = len(delimiter)
else:
d_length = 0
# Get the length of each value that will be joined
v_lengths = [len(v) for v in values if isinstance(v, basestring)]
# Add all the lengths together
z_length = sum(v_lengths)
z_length += (len(values)-1) * d_length
if z_length > maxlength:
raise ValueError(toolong % (maxlength, z_length))
return
def validate(self):
zip_file = self.properties.get('ZipFile')
s3_bucket = self.properties.get('S3Bucket')
s3_key = self.properties.get('S3Key')
s3_object_version = self.properties.get('S3ObjectVersion')
if zip_file and s3_bucket:
raise ValueError("You can't specify both 'S3Bucket' and 'ZipFile'")
if zip_file and s3_key:
raise ValueError("You can't specify both 'S3Key' and 'ZipFile'")
if zip_file and s3_object_version:
raise ValueError(
"You can't specify both 'S3ObjectVersion' and 'ZipFile'"
)
Code.check_zip_file(zip_file)
if not zip_file and not (s3_bucket and s3_key):
raise ValueError(
"You must specify a bucket location (both the 'S3Bucket' and "
"'S3Key' properties) or the 'ZipFile' property"
)
class VPCConfig(AWSProperty):
props = {
'SecurityGroupIds': (list, True),
'SubnetIds': (list, True),
}
class EventSourceMapping(AWSObject):
resource_type = "AWS::Lambda::EventSourceMapping"
props = {
'BatchSize': (positive_integer, False),
'Enabled': (bool, False),
'EventSourceArn': (basestring, True),
'FunctionName': (basestring, True),
'StartingPosition': (basestring, True),
}
class Function(AWSObject):
resource_type = "AWS::Lambda::Function"
props = {
'Code': (Code, True),
'Description': (basestring, False),
'FunctionName': (basestring, False),
'Handler': (basestring, True),
'MemorySize': (validate_memory_size, False),
'Role': (basestring, True),
'Runtime': (basestring, True),
'Timeout': (positive_integer, False),
'VpcConfig': (VPCConfig, False),
}
class Permission(AWSObject):
resource_type = "AWS::Lambda::Permission"
props = {
'Action': (basestring, True),
'FunctionName': (basestring, True),
'Principal': (basestring, True),
'SourceAccount': (basestring, False),
'SourceArn': (basestring, False),
}
class Alias(AWSObject):
resource_type = "AWS::Lambda::Alias"
props = {
'Description': (basestring, False),
'FunctionName': (basestring, True),
'FunctionVersion': (basestring, True),
'Name': (basestring, True),
}
class Version(AWSObject):
resource_type = "AWS::Lambda::Version"
props = {
'CodeSha256': (basestring, False),
'Description': (basestring, False),
'FunctionName': (basestring, True),
}
| mit |
run2/citytour | 4symantec/Lib/site-packages/numpy-1.9.2-py2.7-win-amd64.egg/numpy/distutils/misc_util.py | 40 | 80374 | from __future__ import division, absolute_import, print_function
import os
import re
import sys
import imp
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import distutils
from distutils.errors import DistutilsError
try:
set
except NameError:
from sets import Set as set
from numpy.distutils.compat import get_exception
__all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict',
'dict_append', 'appendpath', 'generate_config_py',
'get_cmd', 'allpath', 'get_mathlibs',
'terminal_has_colors', 'red_text', 'green_text', 'yellow_text',
'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings',
'has_f_sources', 'has_cxx_sources', 'filter_sources',
'get_dependencies', 'is_local_src_dir', 'get_ext_source_files',
'get_script_files', 'get_lib_source_files', 'get_data_files',
'dot_join', 'get_frame', 'minrelpath', 'njoin',
'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language',
'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info']
class InstallableLib(object):
"""
Container to hold information on an installable library.
Parameters
----------
name : str
Name of the installed library.
build_info : dict
Dictionary holding build information.
target_dir : str
Absolute path specifying where to install the library.
See Also
--------
Configuration.add_installed_library
Notes
-----
The three parameters are stored as attributes with the same names.
"""
def __init__(self, name, build_info, target_dir):
self.name = name
self.build_info = build_info
self.target_dir = target_dir
def quote_args(args):
# don't used _nt_quote_args as it does not check if
# args items already have quotes or not.
args = list(args)
for i in range(len(args)):
a = args[i]
if ' ' in a and a[0] not in '"\'':
args[i] = '"%s"' % (a)
return args
def allpath(name):
"Convert a /-separated pathname to one using the OS's path separator."
splitted = name.split('/')
return os.path.join(*splitted)
def rel_path(path, parent_path):
"""Return path relative to parent_path.
"""
pd = os.path.abspath(parent_path)
apath = os.path.abspath(path)
if len(apath)<len(pd):
return path
if apath==pd:
return ''
if pd == apath[:len(pd)]:
assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)]))
path = apath[len(pd)+1:]
return path
def get_path_from_frame(frame, parent_path=None):
"""Return path of the module given a frame object from the call stack.
Returned path is relative to parent_path when given,
otherwise it is absolute path.
"""
# First, try to find if the file name is in the frame.
try:
caller_file = eval('__file__', frame.f_globals, frame.f_locals)
d = os.path.dirname(os.path.abspath(caller_file))
except NameError:
# __file__ is not defined, so let's try __name__. We try this second
# because setuptools spoofs __name__ to be '__main__' even though
# sys.modules['__main__'] might be something else, like easy_install(1).
caller_name = eval('__name__', frame.f_globals, frame.f_locals)
__import__(caller_name)
mod = sys.modules[caller_name]
if hasattr(mod, '__file__'):
d = os.path.dirname(os.path.abspath(mod.__file__))
else:
# we're probably running setup.py as execfile("setup.py")
# (likely we're building an egg)
d = os.path.abspath('.')
# hmm, should we use sys.argv[0] like in __builtin__ case?
if parent_path is not None:
d = rel_path(d, parent_path)
return d or '.'
def njoin(*path):
"""Join two or more pathname components +
- convert a /-separated pathname to one using the OS's path separator.
- resolve `..` and `.` from path.
Either passing n arguments as in njoin('a','b'), or a sequence
of n names as in njoin(['a','b']) is handled, or a mixture of such arguments.
"""
paths = []
for p in path:
if is_sequence(p):
# njoin(['a', 'b'], 'c')
paths.append(njoin(*p))
else:
assert is_string(p)
paths.append(p)
path = paths
if not path:
# njoin()
joined = ''
else:
# njoin('a', 'b')
joined = os.path.join(*path)
if os.path.sep != '/':
joined = joined.replace('/', os.path.sep)
return minrelpath(joined)
def get_mathlibs(path=None):
"""Return the MATHLIB line from numpyconfig.h
"""
if path is not None:
config_file = os.path.join(path, '_numpyconfig.h')
else:
# Look for the file in each of the numpy include directories.
dirs = get_numpy_include_dirs()
for path in dirs:
fn = os.path.join(path, '_numpyconfig.h')
if os.path.exists(fn):
config_file = fn
break
else:
raise DistutilsError('_numpyconfig.h not found in numpy include '
'dirs %r' % (dirs,))
fid = open(config_file)
mathlibs = []
s = '#define MATHLIB'
for line in fid:
if line.startswith(s):
value = line[len(s):].strip()
if value:
mathlibs.extend(value.split(','))
fid.close()
return mathlibs
def minrelpath(path):
"""Resolve `..` and '.' from path.
"""
if not is_string(path):
return path
if '.' not in path:
return path
l = path.split(os.sep)
while l:
try:
i = l.index('.', 1)
except ValueError:
break
del l[i]
j = 1
while l:
try:
i = l.index('..', j)
except ValueError:
break
if l[i-1]=='..':
j += 1
else:
del l[i], l[i-1]
j = 1
if not l:
return ''
return os.sep.join(l)
def _fix_paths(paths, local_path, include_non_existing):
assert is_sequence(paths), repr(type(paths))
new_paths = []
assert not is_string(paths), repr(paths)
for n in paths:
if is_string(n):
if '*' in n or '?' in n:
p = glob.glob(n)
p2 = glob.glob(njoin(local_path, n))
if p2:
new_paths.extend(p2)
elif p:
new_paths.extend(p)
else:
if include_non_existing:
new_paths.append(n)
print('could not resolve pattern in %r: %r' %
(local_path, n))
else:
n2 = njoin(local_path, n)
if os.path.exists(n2):
new_paths.append(n2)
else:
if os.path.exists(n):
new_paths.append(n)
elif include_non_existing:
new_paths.append(n)
if not os.path.exists(n):
print('non-existing path in %r: %r' %
(local_path, n))
elif is_sequence(n):
new_paths.extend(_fix_paths(n, local_path, include_non_existing))
else:
new_paths.append(n)
return [minrelpath(p) for p in new_paths]
def gpaths(paths, local_path='', include_non_existing=True):
"""Apply glob to paths and prepend local_path if needed.
"""
if is_string(paths):
paths = (paths,)
return _fix_paths(paths, local_path, include_non_existing)
_temporary_directory = None
def clean_up_temporary_directory():
global _temporary_directory
if not _temporary_directory:
return
try:
shutil.rmtree(_temporary_directory)
except OSError:
pass
_temporary_directory = None
def make_temp_file(suffix='', prefix='', text=True):
global _temporary_directory
if not _temporary_directory:
_temporary_directory = tempfile.mkdtemp()
atexit.register(clean_up_temporary_directory)
fid, name = tempfile.mkstemp(suffix=suffix,
prefix=prefix,
dir=_temporary_directory,
text=text)
fo = os.fdopen(fid, 'w')
return fo, name
# Hooks for colored terminal output.
# See also http://www.livinglogic.de/Python/ansistyle
def terminal_has_colors():
if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ:
# Avoid importing curses that causes illegal operation
# with a message:
# PYTHON2 caused an invalid page fault in
# module CYGNURSES7.DLL as 015f:18bbfc28
# Details: Python 2.3.3 [GCC 3.3.1 (cygming special)]
# ssh to Win32 machine from debian
# curses.version is 2.2
# CYGWIN_98-4.10, release 1.5.7(0.109/3/2))
return 0
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
try:
import curses
curses.setupterm()
if (curses.tigetnum("colors") >= 0
and curses.tigetnum("pairs") >= 0
and ((curses.tigetstr("setf") is not None
and curses.tigetstr("setb") is not None)
or (curses.tigetstr("setaf") is not None
and curses.tigetstr("setab") is not None)
or curses.tigetstr("scp") is not None)):
return 1
except Exception:
pass
return 0
if terminal_has_colors():
_colour_codes = dict(black=0, red=1, green=2, yellow=3,
blue=4, magenta=5, cyan=6, white=7, default=9)
def colour_text(s, fg=None, bg=None, bold=False):
seq = []
if bold:
seq.append('1')
if fg:
fgcode = 30 + _colour_codes.get(fg.lower(), 0)
seq.append(str(fgcode))
if bg:
bgcode = 40 + _colour_codes.get(fg.lower(), 7)
seq.append(str(bgcode))
if seq:
return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s)
else:
return s
else:
def colour_text(s, fg=None, bg=None):
return s
def default_text(s):
return colour_text(s, 'default')
def red_text(s):
return colour_text(s, 'red')
def green_text(s):
return colour_text(s, 'green')
def yellow_text(s):
return colour_text(s, 'yellow')
def cyan_text(s):
return colour_text(s, 'cyan')
def blue_text(s):
return colour_text(s, 'blue')
#########################
def cyg2win32(path):
if sys.platform=='cygwin' and path.startswith('/cygdrive'):
path = path[10] + ':' + os.path.normcase(path[11:])
return path
def mingw32():
"""Return true when using mingw32 environment.
"""
if sys.platform=='win32':
if os.environ.get('OSTYPE', '')=='msys':
return True
if os.environ.get('MSYSTEM', '')=='MINGW32':
return True
return False
def msvc_runtime_library():
"Return name of MSVC runtime library if Python was built with MSVC >= 7"
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
lib = {'1300': 'msvcr70', # MSVC 7.0
'1310': 'msvcr71', # MSVC 7.1
'1400': 'msvcr80', # MSVC 8
'1500': 'msvcr90', # MSVC 9 (VS 2008)
'1600': 'msvcr100', # MSVC 10 (aka 2010)
}.get(msc_ver, None)
else:
lib = None
return lib
#########################
#XXX need support for .C that is also C++
cxx_ext_match = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match
fortran_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\Z', re.I).match
f90_ext_match = re.compile(r'.*[.](f90|f95)\Z', re.I).match
f90_module_name_match = re.compile(r'\s*module\s*(?P<name>[\w_]+)', re.I).match
def _get_f90_modules(source):
"""Return a list of Fortran f90 module names that
given source file defines.
"""
if not f90_ext_match(source):
return []
modules = []
f = open(source, 'r')
for line in f:
m = f90_module_name_match(line)
if m:
name = m.group('name')
modules.append(name)
# break # XXX can we assume that there is one module per file?
f.close()
return modules
def is_string(s):
return isinstance(s, str)
def all_strings(lst):
"""Return True if all items in lst are string objects. """
for item in lst:
if not is_string(item):
return False
return True
def is_sequence(seq):
if is_string(seq):
return False
try:
len(seq)
except:
return False
return True
def is_glob_pattern(s):
return is_string(s) and ('*' in s or '?' is s)
def as_list(seq):
if is_sequence(seq):
return list(seq)
else:
return [seq]
def get_language(sources):
# not used in numpy/scipy packages, use build_ext.detect_language instead
"""Determine language value (c,f77,f90) from sources """
language = None
for source in sources:
if isinstance(source, str):
if f90_ext_match(source):
language = 'f90'
break
elif fortran_ext_match(source):
language = 'f77'
return language
def has_f_sources(sources):
"""Return True if sources contains Fortran files """
for source in sources:
if fortran_ext_match(source):
return True
return False
def has_cxx_sources(sources):
"""Return True if sources contains C++ files """
for source in sources:
if cxx_ext_match(source):
return True
return False
def filter_sources(sources):
"""Return four lists of filenames containing
C, C++, Fortran, and Fortran 90 module sources,
respectively.
"""
c_sources = []
cxx_sources = []
f_sources = []
fmodule_sources = []
for source in sources:
if fortran_ext_match(source):
modules = _get_f90_modules(source)
if modules:
fmodule_sources.append(source)
else:
f_sources.append(source)
elif cxx_ext_match(source):
cxx_sources.append(source)
else:
c_sources.append(source)
return c_sources, cxx_sources, f_sources, fmodule_sources
def _get_headers(directory_list):
# get *.h files from list of directories
headers = []
for d in directory_list:
head = glob.glob(os.path.join(d, "*.h")) #XXX: *.hpp files??
headers.extend(head)
return headers
def _get_directories(list_of_sources):
# get unique directories from list of sources.
direcs = []
for f in list_of_sources:
d = os.path.split(f)
if d[0] != '' and not d[0] in direcs:
direcs.append(d[0])
return direcs
def get_dependencies(sources):
#XXX scan sources for include statements
return _get_headers(_get_directories(sources))
def is_local_src_dir(directory):
"""Return true if directory is local directory.
"""
if not is_string(directory):
return False
abs_dir = os.path.abspath(directory)
c = os.path.commonprefix([os.getcwd(), abs_dir])
new_dir = abs_dir[len(c):].split(os.sep)
if new_dir and not new_dir[0]:
new_dir = new_dir[1:]
if new_dir and new_dir[0]=='build':
return False
new_dir = os.sep.join(new_dir)
return os.path.isdir(new_dir)
def general_source_files(top_path):
pruned_directories = {'CVS':1, '.svn':1, 'build':1}
prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
pruned = [ d for d in dirnames if d not in pruned_directories ]
dirnames[:] = pruned
for f in filenames:
if not prune_file_pat.search(f):
yield os.path.join(dirpath, f)
def general_source_directories_files(top_path):
"""Return a directory name relative to top_path and
files contained.
"""
pruned_directories = ['CVS', '.svn', 'build']
prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
pruned = [ d for d in dirnames if d not in pruned_directories ]
dirnames[:] = pruned
for d in dirnames:
dpath = os.path.join(dirpath, d)
rpath = rel_path(dpath, top_path)
files = []
for f in os.listdir(dpath):
fn = os.path.join(dpath, f)
if os.path.isfile(fn) and not prune_file_pat.search(fn):
files.append(fn)
yield rpath, files
dpath = top_path
rpath = rel_path(dpath, top_path)
filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \
if not prune_file_pat.search(f)]
files = [f for f in filenames if os.path.isfile(f)]
yield rpath, files
def get_ext_source_files(ext):
# Get sources and any include files in the same directory.
filenames = []
sources = [_m for _m in ext.sources if is_string(_m)]
filenames.extend(sources)
filenames.extend(get_dependencies(sources))
for d in ext.depends:
if is_local_src_dir(d):
filenames.extend(list(general_source_files(d)))
elif os.path.isfile(d):
filenames.append(d)
return filenames
def get_script_files(scripts):
scripts = [_m for _m in scripts if is_string(_m)]
return scripts
def get_lib_source_files(lib):
filenames = []
sources = lib[1].get('sources', [])
sources = [_m for _m in sources if is_string(_m)]
filenames.extend(sources)
filenames.extend(get_dependencies(sources))
depends = lib[1].get('depends', [])
for d in depends:
if is_local_src_dir(d):
filenames.extend(list(general_source_files(d)))
elif os.path.isfile(d):
filenames.append(d)
return filenames
def get_shared_lib_extension(is_python_ext=False):
"""Return the correct file extension for shared libraries.
Parameters
----------
is_python_ext : bool, optional
Whether the shared library is a Python extension. Default is False.
Returns
-------
so_ext : str
The shared library extension.
Notes
-----
For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X,
and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on
POSIX systems according to PEP 3149. For Python 3.2 this is implemented on
Linux, but not on OS X.
"""
confvars = distutils.sysconfig.get_config_vars()
# SO is deprecated in 3.3.1, use EXT_SUFFIX instead
so_ext = confvars.get('EXT_SUFFIX', None)
if so_ext is None:
so_ext = confvars.get('SO', '')
if not is_python_ext:
# hardcode known values, config vars (including SHLIB_SUFFIX) are
# unreliable (see #3182)
# darwin, windows and debug linux are wrong in 3.3.1 and older
if (sys.platform.startswith('linux') or
sys.platform.startswith('gnukfreebsd')):
so_ext = '.so'
elif sys.platform.startswith('darwin'):
so_ext = '.dylib'
elif sys.platform.startswith('win'):
so_ext = '.dll'
else:
# fall back to config vars for unknown platforms
# fix long extension for Python >=3.2, see PEP 3149.
if 'SOABI' in confvars:
# Does nothing unless SOABI config var exists
so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1)
return so_ext
def get_data_files(data):
if is_string(data):
return [data]
sources = data[1]
filenames = []
for s in sources:
if hasattr(s, '__call__'):
continue
if is_local_src_dir(s):
filenames.extend(list(general_source_files(s)))
elif is_string(s):
if os.path.isfile(s):
filenames.append(s)
else:
print('Not existing data file:', s)
else:
raise TypeError(repr(s))
return filenames
def dot_join(*args):
return '.'.join([a for a in args if a])
def get_frame(level=0):
"""Return frame object from call stack with given level.
"""
try:
return sys._getframe(level+1)
except AttributeError:
frame = sys.exc_info()[2].tb_frame
for _ in range(level+1):
frame = frame.f_back
return frame
######################
class Configuration(object):
_list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs',
'libraries', 'headers', 'scripts', 'py_modules',
'installed_libraries', 'define_macros']
_dict_keys = ['package_dir', 'installed_pkg_config']
_extra_keys = ['name', 'version']
numpy_include_dirs = []
def __init__(self,
package_name=None,
parent_name=None,
top_path=None,
package_path=None,
caller_level=1,
setup_name='setup.py',
**attrs):
"""Construct configuration instance of a package.
package_name -- name of the package
Ex.: 'distutils'
parent_name -- name of the parent package
Ex.: 'numpy'
top_path -- directory of the toplevel package
Ex.: the directory where the numpy package source sits
package_path -- directory of package. Will be computed by magic from the
directory of the caller module if not specified
Ex.: the directory where numpy.distutils is
caller_level -- frame level to caller namespace, internal parameter.
"""
self.name = dot_join(parent_name, package_name)
self.version = None
caller_frame = get_frame(caller_level)
self.local_path = get_path_from_frame(caller_frame, top_path)
# local_path -- directory of a file (usually setup.py) that
# defines a configuration() function.
# local_path -- directory of a file (usually setup.py) that
# defines a configuration() function.
if top_path is None:
top_path = self.local_path
self.local_path = ''
if package_path is None:
package_path = self.local_path
elif os.path.isdir(njoin(self.local_path, package_path)):
package_path = njoin(self.local_path, package_path)
if not os.path.isdir(package_path or '.'):
raise ValueError("%r is not a directory" % (package_path,))
self.top_path = top_path
self.package_path = package_path
# this is the relative path in the installed package
self.path_in_package = os.path.join(*self.name.split('.'))
self.list_keys = self._list_keys[:]
self.dict_keys = self._dict_keys[:]
for n in self.list_keys:
v = copy.copy(attrs.get(n, []))
setattr(self, n, as_list(v))
for n in self.dict_keys:
v = copy.copy(attrs.get(n, {}))
setattr(self, n, v)
known_keys = self.list_keys + self.dict_keys
self.extra_keys = self._extra_keys[:]
for n in attrs.keys():
if n in known_keys:
continue
a = attrs[n]
setattr(self, n, a)
if isinstance(a, list):
self.list_keys.append(n)
elif isinstance(a, dict):
self.dict_keys.append(n)
else:
self.extra_keys.append(n)
if os.path.exists(njoin(package_path, '__init__.py')):
self.packages.append(self.name)
self.package_dir[self.name] = package_path
self.options = dict(
ignore_setup_xxx_py = False,
assume_default_configuration = False,
delegate_options_to_subpackages = False,
quiet = False,
)
caller_instance = None
for i in range(1, 3):
try:
f = get_frame(i)
except ValueError:
break
try:
caller_instance = eval('self', f.f_globals, f.f_locals)
break
except NameError:
pass
if isinstance(caller_instance, self.__class__):
if caller_instance.options['delegate_options_to_subpackages']:
self.set_options(**caller_instance.options)
self.setup_name = setup_name
def todict(self):
"""
Return a dictionary compatible with the keyword arguments of distutils
setup function.
Examples
--------
>>> setup(**config.todict()) #doctest: +SKIP
"""
self._optimize_data_files()
d = {}
known_keys = self.list_keys + self.dict_keys + self.extra_keys
for n in known_keys:
a = getattr(self, n)
if a:
d[n] = a
return d
def info(self, message):
if not self.options['quiet']:
print(message)
def warn(self, message):
sys.stderr.write('Warning: %s' % (message,))
def set_options(self, **options):
"""
Configure Configuration instance.
The following options are available:
- ignore_setup_xxx_py
- assume_default_configuration
- delegate_options_to_subpackages
- quiet
"""
for key, value in options.items():
if key in self.options:
self.options[key] = value
else:
raise ValueError('Unknown option: '+key)
def get_distribution(self):
"""Return the distutils distribution object for self."""
from numpy.distutils.core import get_distribution
return get_distribution()
def _wildcard_get_subpackage(self, subpackage_name,
parent_name,
caller_level = 1):
l = subpackage_name.split('.')
subpackage_path = njoin([self.local_path]+l)
dirs = [_m for _m in glob.glob(subpackage_path) if os.path.isdir(_m)]
config_list = []
for d in dirs:
if not os.path.isfile(njoin(d, '__init__.py')):
continue
if 'build' in d.split(os.sep):
continue
n = '.'.join(d.split(os.sep)[-len(l):])
c = self.get_subpackage(n,
parent_name = parent_name,
caller_level = caller_level+1)
config_list.extend(c)
return config_list
def _get_configuration_from_setup_py(self, setup_py,
subpackage_name,
subpackage_path,
parent_name,
caller_level = 1):
# In case setup_py imports local modules:
sys.path.insert(0, os.path.dirname(setup_py))
try:
fo_setup_py = open(setup_py, 'U')
setup_name = os.path.splitext(os.path.basename(setup_py))[0]
n = dot_join(self.name, subpackage_name, setup_name)
setup_module = imp.load_module('_'.join(n.split('.')),
fo_setup_py,
setup_py,
('.py', 'U', 1))
fo_setup_py.close()
if not hasattr(setup_module, 'configuration'):
if not self.options['assume_default_configuration']:
self.warn('Assuming default configuration '\
'(%s does not define configuration())'\
% (setup_module))
config = Configuration(subpackage_name, parent_name,
self.top_path, subpackage_path,
caller_level = caller_level + 1)
else:
pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1]))
args = (pn,)
def fix_args_py2(args):
if setup_module.configuration.__code__.co_argcount > 1:
args = args + (self.top_path,)
return args
def fix_args_py3(args):
if setup_module.configuration.__code__.co_argcount > 1:
args = args + (self.top_path,)
return args
if sys.version_info[0] < 3:
args = fix_args_py2(args)
else:
args = fix_args_py3(args)
config = setup_module.configuration(*args)
if config.name!=dot_join(parent_name, subpackage_name):
self.warn('Subpackage %r configuration returned as %r' % \
(dot_join(parent_name, subpackage_name), config.name))
finally:
del sys.path[0]
return config
def get_subpackage(self,subpackage_name,
subpackage_path=None,
parent_name=None,
caller_level = 1):
"""Return list of subpackage configurations.
Parameters
----------
subpackage_name : str or None
Name of the subpackage to get the configuration. '*' in
subpackage_name is handled as a wildcard.
subpackage_path : str
If None, then the path is assumed to be the local path plus the
subpackage_name. If a setup.py file is not found in the
subpackage_path, then a default configuration is used.
parent_name : str
Parent name.
"""
if subpackage_name is None:
if subpackage_path is None:
raise ValueError(
"either subpackage_name or subpackage_path must be specified")
subpackage_name = os.path.basename(subpackage_path)
# handle wildcards
l = subpackage_name.split('.')
if subpackage_path is None and '*' in subpackage_name:
return self._wildcard_get_subpackage(subpackage_name,
parent_name,
caller_level = caller_level+1)
assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))
if subpackage_path is None:
subpackage_path = njoin([self.local_path] + l)
else:
subpackage_path = njoin([subpackage_path] + l[:-1])
subpackage_path = self.paths([subpackage_path])[0]
setup_py = njoin(subpackage_path, self.setup_name)
if not self.options['ignore_setup_xxx_py']:
if not os.path.isfile(setup_py):
setup_py = njoin(subpackage_path,
'setup_%s.py' % (subpackage_name))
if not os.path.isfile(setup_py):
if not self.options['assume_default_configuration']:
self.warn('Assuming default configuration '\
'(%s/{setup_%s,setup}.py was not found)' \
% (os.path.dirname(setup_py), subpackage_name))
config = Configuration(subpackage_name, parent_name,
self.top_path, subpackage_path,
caller_level = caller_level+1)
else:
config = self._get_configuration_from_setup_py(
setup_py,
subpackage_name,
subpackage_path,
parent_name,
caller_level = caller_level + 1)
if config:
return [config]
else:
return []
def add_subpackage(self,subpackage_name,
subpackage_path=None,
standalone = False):
"""Add a sub-package to the current Configuration instance.
This is useful in a setup.py script for adding sub-packages to a
package.
Parameters
----------
subpackage_name : str
name of the subpackage
subpackage_path : str
if given, the subpackage path such as the subpackage is in
subpackage_path / subpackage_name. If None,the subpackage is
assumed to be located in the local path / subpackage_name.
standalone : bool
"""
if standalone:
parent_name = None
else:
parent_name = self.name
config_list = self.get_subpackage(subpackage_name, subpackage_path,
parent_name = parent_name,
caller_level = 2)
if not config_list:
self.warn('No configuration returned, assuming unavailable.')
for config in config_list:
d = config
if isinstance(config, Configuration):
d = config.todict()
assert isinstance(d, dict), repr(type(d))
self.info('Appending %s configuration to %s' \
% (d.get('name'), self.name))
self.dict_append(**d)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add a subpackage '+ subpackage_name)
def add_data_dir(self, data_path):
"""Recursively add files under data_path to data_files list.
Recursively add files under data_path to the list of data_files to be
installed (and distributed). The data_path can be either a relative
path-name, or an absolute path-name, or a 2-tuple where the first
argument shows where in the install directory the data directory
should be installed to.
Parameters
----------
data_path : seq or str
Argument can be either
* 2-sequence (<datadir suffix>, <path to data directory>)
* path to data directory where python datadir suffix defaults
to package dir.
Notes
-----
Rules for installation paths:
foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
(gun, foo/bar) -> parent/gun
foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
(gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
(gun/*, foo/*) -> parent/gun/a, parent/gun/b
/foo/bar -> (bar, /foo/bar) -> parent/bar
(gun, /foo/bar) -> parent/gun
(fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
Examples
--------
For example suppose the source directory contains fun/foo.dat and
fun/bar/car.dat::
>>> self.add_data_dir('fun') #doctest: +SKIP
>>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP
>>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP
Will install data-files to the locations::
<package install directory>/
fun/
foo.dat
bar/
car.dat
sun/
foo.dat
bar/
car.dat
gun/
foo.dat
car.dat
"""
if is_sequence(data_path):
d, data_path = data_path
else:
d = None
if is_sequence(data_path):
[self.add_data_dir((d, p)) for p in data_path]
return
if not is_string(data_path):
raise TypeError("not a string: %r" % (data_path,))
if d is None:
if os.path.isabs(data_path):
return self.add_data_dir((os.path.basename(data_path), data_path))
return self.add_data_dir((data_path, data_path))
paths = self.paths(data_path, include_non_existing=False)
if is_glob_pattern(data_path):
if is_glob_pattern(d):
pattern_list = allpath(d).split(os.sep)
pattern_list.reverse()
# /a/*//b/ -> /a/*/b
rl = list(range(len(pattern_list)-1)); rl.reverse()
for i in rl:
if not pattern_list[i]:
del pattern_list[i]
#
for path in paths:
if not os.path.isdir(path):
print('Not a directory, skipping', path)
continue
rpath = rel_path(path, self.local_path)
path_list = rpath.split(os.sep)
path_list.reverse()
target_list = []
i = 0
for s in pattern_list:
if is_glob_pattern(s):
if i>=len(path_list):
raise ValueError('cannot fill pattern %r with %r' \
% (d, path))
target_list.append(path_list[i])
else:
assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath))
target_list.append(s)
i += 1
if path_list[i:]:
self.warn('mismatch of pattern_list=%s and path_list=%s'\
% (pattern_list, path_list))
target_list.reverse()
self.add_data_dir((os.sep.join(target_list), path))
else:
for path in paths:
self.add_data_dir((d, path))
return
assert not is_glob_pattern(d), repr(d)
dist = self.get_distribution()
if dist is not None and dist.data_files is not None:
data_files = dist.data_files
else:
data_files = self.data_files
for path in paths:
for d1, f in list(general_source_directories_files(path)):
target_path = os.path.join(self.path_in_package, d, d1)
data_files.append((target_path, f))
def _optimize_data_files(self):
data_dict = {}
for p, files in self.data_files:
if p not in data_dict:
data_dict[p] = set()
for f in files:
data_dict[p].add(f)
self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()]
def add_data_files(self,*files):
"""Add data files to configuration data_files.
Parameters
----------
files : sequence
Argument(s) can be either
* 2-sequence (<datadir prefix>,<path to data file(s)>)
* paths to data files where python datadir prefix defaults
to package dir.
Notes
-----
The form of each element of the files sequence is very flexible
allowing many combinations of where to get the files from the package
and where they should ultimately be installed on the system. The most
basic usage is for an element of the files argument sequence to be a
simple filename. This will cause that file from the local path to be
installed to the installation path of the self.name package (package
path). The file argument can also be a relative path in which case the
entire relative path will be installed into the package directory.
Finally, the file can be an absolute path name in which case the file
will be found at the absolute path name but installed to the package
path.
This basic behavior can be augmented by passing a 2-tuple in as the
file argument. The first element of the tuple should specify the
relative path (under the package install directory) where the
remaining sequence of files should be installed to (it has nothing to
do with the file-names in the source distribution). The second element
of the tuple is the sequence of files that should be installed. The
files in this sequence can be filenames, relative paths, or absolute
paths. For absolute paths the file will be installed in the top-level
package installation directory (regardless of the first argument).
Filenames and relative path names will be installed in the package
install directory under the path name given as the first element of
the tuple.
Rules for installation paths:
#. file.txt -> (., file.txt)-> parent/file.txt
#. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
#. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
#. *.txt -> parent/a.txt, parent/b.txt
#. foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt
#. */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt
#. (sun, file.txt) -> parent/sun/file.txt
#. (sun, bar/file.txt) -> parent/sun/file.txt
#. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
#. (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt
#. (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt
#. (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt
An additional feature is that the path to a data-file can actually be
a function that takes no arguments and returns the actual path(s) to
the data-files. This is useful when the data files are generated while
building the package.
Examples
--------
Add files to the list of data_files to be included with the package.
>>> self.add_data_files('foo.dat',
... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
... 'bar/cat.dat',
... '/full/path/to/can.dat') #doctest: +SKIP
will install these data files to::
<package install directory>/
foo.dat
fun/
gun.dat
nun/
pun.dat
sun.dat
bar/
car.dat
can.dat
where <package install directory> is the package (or sub-package)
directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
\\Python2.4 \\Lib \\site-packages \\mypackage') or
'/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:
\\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage').
"""
if len(files)>1:
for f in files:
self.add_data_files(f)
return
assert len(files)==1
if is_sequence(files[0]):
d, files = files[0]
else:
d = None
if is_string(files):
filepat = files
elif is_sequence(files):
if len(files)==1:
filepat = files[0]
else:
for f in files:
self.add_data_files((d, f))
return
else:
raise TypeError(repr(type(files)))
if d is None:
if hasattr(filepat, '__call__'):
d = ''
elif os.path.isabs(filepat):
d = ''
else:
d = os.path.dirname(filepat)
self.add_data_files((d, files))
return
paths = self.paths(filepat, include_non_existing=False)
if is_glob_pattern(filepat):
if is_glob_pattern(d):
pattern_list = d.split(os.sep)
pattern_list.reverse()
for path in paths:
path_list = path.split(os.sep)
path_list.reverse()
path_list.pop() # filename
target_list = []
i = 0
for s in pattern_list:
if is_glob_pattern(s):
target_list.append(path_list[i])
i += 1
else:
target_list.append(s)
target_list.reverse()
self.add_data_files((os.sep.join(target_list), path))
else:
self.add_data_files((d, paths))
return
assert not is_glob_pattern(d), repr((d, filepat))
dist = self.get_distribution()
if dist is not None and dist.data_files is not None:
data_files = dist.data_files
else:
data_files = self.data_files
data_files.append((os.path.join(self.path_in_package, d), paths))
### XXX Implement add_py_modules
def add_define_macros(self, macros):
"""Add define macros to configuration
Add the given sequence of macro name and value duples to the beginning
of the define_macros list This list will be visible to all extension
modules of the current package.
"""
dist = self.get_distribution()
if dist is not None:
if not hasattr(dist, 'define_macros'):
dist.define_macros = []
dist.define_macros.extend(macros)
else:
self.define_macros.extend(macros)
def add_include_dirs(self,*paths):
"""Add paths to configuration include directories.
Add the given sequence of paths to the beginning of the include_dirs
list. This list will be visible to all extension modules of the
current package.
"""
include_dirs = self.paths(paths)
dist = self.get_distribution()
if dist is not None:
if dist.include_dirs is None:
dist.include_dirs = []
dist.include_dirs.extend(include_dirs)
else:
self.include_dirs.extend(include_dirs)
def add_headers(self,*files):
"""Add installable headers to configuration.
Add the given sequence of files to the beginning of the headers list.
By default, headers will be installed under <python-
include>/<self.name.replace('.','/')>/ directory. If an item of files
is a tuple, then its first argument specifies the actual installation
location relative to the <python-include> path.
Parameters
----------
files : str or seq
Argument(s) can be either:
* 2-sequence (<includedir suffix>,<path to header file(s)>)
* path(s) to header file(s) where python includedir suffix will
default to package name.
"""
headers = []
for path in files:
if is_string(path):
[headers.append((self.name, p)) for p in self.paths(path)]
else:
if not isinstance(path, (tuple, list)) or len(path) != 2:
raise TypeError(repr(path))
[headers.append((path[0], p)) for p in self.paths(path[1])]
dist = self.get_distribution()
if dist is not None:
if dist.headers is None:
dist.headers = []
dist.headers.extend(headers)
else:
self.headers.extend(headers)
def paths(self,*paths,**kws):
"""Apply glob to paths and prepend local_path if needed.
Applies glob.glob(...) to each path in the sequence (if needed) and
pre-pends the local_path if needed. Because this is called on all
source lists, this allows wildcard characters to be specified in lists
of sources for extension modules and libraries and scripts and allows
path-names be relative to the source directory.
"""
include_non_existing = kws.get('include_non_existing', True)
return gpaths(paths,
local_path = self.local_path,
include_non_existing=include_non_existing)
def _fix_paths_dict(self, kw):
for k in kw.keys():
v = kw[k]
if k in ['sources', 'depends', 'include_dirs', 'library_dirs',
'module_dirs', 'extra_objects']:
new_v = self.paths(v)
kw[k] = new_v
def add_extension(self,name,sources,**kw):
"""Add extension to configuration.
Create and add an Extension instance to the ext_modules list. This
method also takes the following optional keyword arguments that are
passed on to the Extension constructor.
Parameters
----------
name : str
name of the extension
sources : seq
list of the sources. The list of sources may contain functions
(called source generators) which must take an extension instance
and a build directory as inputs and return a source file or list of
source files or None. If None is returned then no sources are
generated. If the Extension instance has no sources after
processing all source generators, then no extension module is
built.
include_dirs :
define_macros :
undef_macros :
library_dirs :
libraries :
runtime_library_dirs :
extra_objects :
extra_compile_args :
extra_link_args :
extra_f77_compile_args :
extra_f90_compile_args :
export_symbols :
swig_opts :
depends :
The depends list contains paths to files or directories that the
sources of the extension module depend on. If any path in the
depends list is newer than the extension module, then the module
will be rebuilt.
language :
f2py_options :
module_dirs :
extra_info : dict or list
dict or list of dict of keywords to be appended to keywords.
Notes
-----
The self.paths(...) method is applied to all lists that may contain
paths.
"""
ext_args = copy.copy(kw)
ext_args['name'] = dot_join(self.name, name)
ext_args['sources'] = sources
if 'extra_info' in ext_args:
extra_info = ext_args['extra_info']
del ext_args['extra_info']
if isinstance(extra_info, dict):
extra_info = [extra_info]
for info in extra_info:
assert isinstance(info, dict), repr(info)
dict_append(ext_args,**info)
self._fix_paths_dict(ext_args)
# Resolve out-of-tree dependencies
libraries = ext_args.get('libraries', [])
libnames = []
ext_args['libraries'] = []
for libname in libraries:
if isinstance(libname, tuple):
self._fix_paths_dict(libname[1])
# Handle library names of the form libname@relative/path/to/library
if '@' in libname:
lname, lpath = libname.split('@', 1)
lpath = os.path.abspath(njoin(self.local_path, lpath))
if os.path.isdir(lpath):
c = self.get_subpackage(None, lpath,
caller_level = 2)
if isinstance(c, Configuration):
c = c.todict()
for l in [l[0] for l in c.get('libraries', [])]:
llname = l.split('__OF__', 1)[0]
if llname == lname:
c.pop('name', None)
dict_append(ext_args,**c)
break
continue
libnames.append(libname)
ext_args['libraries'] = libnames + ext_args['libraries']
ext_args['define_macros'] = \
self.define_macros + ext_args.get('define_macros', [])
from numpy.distutils.core import Extension
ext = Extension(**ext_args)
self.ext_modules.append(ext)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add an extension '+name)
return ext
def add_library(self,name,sources,**build_info):
"""
Add library to configuration.
Parameters
----------
name : str
Name of the extension.
sources : sequence
List of the sources. The list of sources may contain functions
(called source generators) which must take an extension instance
and a build directory as inputs and return a source file or list of
source files or None. If None is returned then no sources are
generated. If the Extension instance has no sources after
processing all source generators, then no extension module is
built.
build_info : dict, optional
The following keys are allowed:
* depends
* macros
* include_dirs
* extra_compiler_args
* extra_f77_compiler_args
* extra_f90_compiler_args
* f2py_options
* language
"""
self._add_library(name, sources, None, build_info)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add a library '+ name)
def _add_library(self, name, sources, install_dir, build_info):
"""Common implementation for add_library and add_installed_library. Do
not use directly"""
build_info = copy.copy(build_info)
name = name #+ '__OF__' + self.name
build_info['sources'] = sources
# Sometimes, depends is not set up to an empty list by default, and if
# depends is not given to add_library, distutils barfs (#1134)
if not 'depends' in build_info:
build_info['depends'] = []
self._fix_paths_dict(build_info)
# Add to libraries list so that it is build with build_clib
self.libraries.append((name, build_info))
def add_installed_library(self, name, sources, install_dir, build_info=None):
"""
Similar to add_library, but the specified library is installed.
Most C libraries used with `distutils` are only used to build python
extensions, but libraries built through this method will be installed
so that they can be reused by third-party packages.
Parameters
----------
name : str
Name of the installed library.
sources : sequence
List of the library's source files. See `add_library` for details.
install_dir : str
Path to install the library, relative to the current sub-package.
build_info : dict, optional
The following keys are allowed:
* depends
* macros
* include_dirs
* extra_compiler_args
* extra_f77_compiler_args
* extra_f90_compiler_args
* f2py_options
* language
Returns
-------
None
See Also
--------
add_library, add_npy_pkg_config, get_info
Notes
-----
The best way to encode the options required to link against the specified
C libraries is to use a "libname.ini" file, and use `get_info` to
retrieve the required options (see `add_npy_pkg_config` for more
information).
"""
if not build_info:
build_info = {}
install_dir = os.path.join(self.package_path, install_dir)
self._add_library(name, sources, install_dir, build_info)
self.installed_libraries.append(InstallableLib(name, build_info, install_dir))
def add_npy_pkg_config(self, template, install_dir, subst_dict=None):
"""
Generate and install a npy-pkg config file from a template.
The config file generated from `template` is installed in the
given install directory, using `subst_dict` for variable substitution.
Parameters
----------
template : str
The path of the template, relatively to the current package path.
install_dir : str
Where to install the npy-pkg config file, relatively to the current
package path.
subst_dict : dict, optional
If given, any string of the form ``@key@`` will be replaced by
``subst_dict[key]`` in the template file when installed. The install
prefix is always available through the variable ``@prefix@``, since the
install prefix is not easy to get reliably from setup.py.
See also
--------
add_installed_library, get_info
Notes
-----
This works for both standard installs and in-place builds, i.e. the
``@prefix@`` refer to the source directory for in-place builds.
Examples
--------
::
config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})
Assuming the foo.ini.in file has the following content::
[meta]
Name=@foo@
Version=1.0
Description=dummy description
[default]
Cflags=-I@prefix@/include
Libs=
The generated file will have the following content::
[meta]
Name=bar
Version=1.0
Description=dummy description
[default]
Cflags=-Iprefix_dir/include
Libs=
and will be installed as foo.ini in the 'lib' subpath.
"""
if subst_dict is None:
subst_dict = {}
basename = os.path.splitext(template)[0]
template = os.path.join(self.package_path, template)
if self.name in self.installed_pkg_config:
self.installed_pkg_config[self.name].append((template, install_dir,
subst_dict))
else:
self.installed_pkg_config[self.name] = [(template, install_dir,
subst_dict)]
def add_scripts(self,*files):
"""Add scripts to configuration.
Add the sequence of files to the beginning of the scripts list.
Scripts will be installed under the <prefix>/bin/ directory.
"""
scripts = self.paths(files)
dist = self.get_distribution()
if dist is not None:
if dist.scripts is None:
dist.scripts = []
dist.scripts.extend(scripts)
else:
self.scripts.extend(scripts)
def dict_append(self,**dict):
for key in self.list_keys:
a = getattr(self, key)
a.extend(dict.get(key, []))
for key in self.dict_keys:
a = getattr(self, key)
a.update(dict.get(key, {}))
known_keys = self.list_keys + self.dict_keys + self.extra_keys
for key in dict.keys():
if key not in known_keys:
a = getattr(self, key, None)
if a and a==dict[key]: continue
self.warn('Inheriting attribute %r=%r from %r' \
% (key, dict[key], dict.get('name', '?')))
setattr(self, key, dict[key])
self.extra_keys.append(key)
elif key in self.extra_keys:
self.info('Ignoring attempt to set %r (from %r to %r)' \
% (key, getattr(self, key), dict[key]))
elif key in known_keys:
# key is already processed above
pass
else:
raise ValueError("Don't know about key=%r" % (key))
def __str__(self):
from pprint import pformat
known_keys = self.list_keys + self.dict_keys + self.extra_keys
s = '<'+5*'-' + '\n'
s += 'Configuration of '+self.name+':\n'
known_keys.sort()
for k in known_keys:
a = getattr(self, k, None)
if a:
s += '%s = %s\n' % (k, pformat(a))
s += 5*'-' + '>'
return s
def get_config_cmd(self):
"""
Returns the numpy.distutils config command instance.
"""
cmd = get_cmd('config')
cmd.ensure_finalized()
cmd.dump_source = 0
cmd.noisy = 0
old_path = os.environ.get('PATH')
if old_path:
path = os.pathsep.join(['.', old_path])
os.environ['PATH'] = path
return cmd
def get_build_temp_dir(self):
"""
Return a path to a temporary directory where temporary files should be
placed.
"""
cmd = get_cmd('build')
cmd.ensure_finalized()
return cmd.build_temp
def have_f77c(self):
"""Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully).
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
return flag
def have_f90c(self):
"""Check for availability of Fortran 90 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 90 compiler is available (because a simple Fortran
90 code was able to be compiled successfully)
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90')
return flag
def append_to(self, extlib):
"""Append libraries, include_dirs to extension or library item.
"""
if is_sequence(extlib):
lib_name, build_info = extlib
dict_append(build_info,
libraries=self.libraries,
include_dirs=self.include_dirs)
else:
from numpy.distutils.core import Extension
assert isinstance(extlib, Extension), repr(extlib)
extlib.libraries.extend(self.libraries)
extlib.include_dirs.extend(self.include_dirs)
def _get_svn_revision(self, path):
"""Return path's SVN revision number.
"""
revision = None
m = None
cwd = os.getcwd()
try:
os.chdir(path or '.')
p = subprocess.Popen(['svnversion'], shell=True,
stdout=subprocess.PIPE, stderr=None,
close_fds=True)
sout = p.stdout
m = re.match(r'(?P<revision>\d+)', sout.read())
except:
pass
os.chdir(cwd)
if m:
revision = int(m.group('revision'))
return revision
if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None):
entries = njoin(path, '_svn', 'entries')
else:
entries = njoin(path, '.svn', 'entries')
if os.path.isfile(entries):
f = open(entries)
fstr = f.read()
f.close()
if fstr[:5] == '<?xml': # pre 1.4
m = re.search(r'revision="(?P<revision>\d+)"', fstr)
if m:
revision = int(m.group('revision'))
else: # non-xml entries file --- check to be sure that
m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr)
if m:
revision = int(m.group('revision'))
return revision
def _get_hg_revision(self, path):
"""Return path's Mercurial revision number.
"""
revision = None
m = None
cwd = os.getcwd()
try:
os.chdir(path or '.')
p = subprocess.Popen(['hg identify --num'], shell=True,
stdout=subprocess.PIPE, stderr=None,
close_fds=True)
sout = p.stdout
m = re.match(r'(?P<revision>\d+)', sout.read())
except:
pass
os.chdir(cwd)
if m:
revision = int(m.group('revision'))
return revision
branch_fn = njoin(path, '.hg', 'branch')
branch_cache_fn = njoin(path, '.hg', 'branch.cache')
if os.path.isfile(branch_fn):
branch0 = None
f = open(branch_fn)
revision0 = f.read().strip()
f.close()
branch_map = {}
for line in file(branch_cache_fn, 'r'):
branch1, revision1 = line.split()[:2]
if revision1==revision0:
branch0 = branch1
try:
revision1 = int(revision1)
except ValueError:
continue
branch_map[branch1] = revision1
revision = branch_map.get(branch0)
return revision
def get_version(self, version_file=None, version_variable=None):
"""Try to get version string of a package.
Return a version string of the current package or None if the version
information could not be detected.
Notes
-----
This method scans files named
__version__.py, <packagename>_version.py, version.py, and
__svn_version__.py for string variables version, __version\__, and
<packagename>_version, until a version number is found.
"""
version = getattr(self, 'version', None)
if version is not None:
return version
# Get version from version file.
if version_file is None:
files = ['__version__.py',
self.name.split('.')[-1]+'_version.py',
'version.py',
'__svn_version__.py',
'__hg_version__.py']
else:
files = [version_file]
if version_variable is None:
version_vars = ['version',
'__version__',
self.name.split('.')[-1]+'_version']
else:
version_vars = [version_variable]
for f in files:
fn = njoin(self.local_path, f)
if os.path.isfile(fn):
info = (open(fn), fn, ('.py', 'U', 1))
name = os.path.splitext(os.path.basename(fn))[0]
n = dot_join(self.name, name)
try:
version_module = imp.load_module('_'.join(n.split('.')),*info)
except ImportError:
msg = get_exception()
self.warn(str(msg))
version_module = None
if version_module is None:
continue
for a in version_vars:
version = getattr(version_module, a, None)
if version is not None:
break
if version is not None:
break
if version is not None:
self.version = version
return version
# Get version as SVN or Mercurial revision number
revision = self._get_svn_revision(self.local_path)
if revision is None:
revision = self._get_hg_revision(self.local_path)
if revision is not None:
version = str(revision)
self.version = version
return version
def make_svn_version_py(self, delete=True):
"""Appends a data function to the data_files list that will generate
__svn_version__.py file to the current package directory.
Generate package __svn_version__.py file from SVN revision number,
it will be removed after python exits but will be available
when sdist, etc commands are executed.
Notes
-----
If __svn_version__.py existed before, nothing is done.
This is
intended for working with source directories that are in an SVN
repository.
"""
target = njoin(self.local_path, '__svn_version__.py')
revision = self._get_svn_revision(self.local_path)
if os.path.isfile(target) or revision is None:
return
else:
def generate_svn_version_py():
if not os.path.isfile(target):
version = str(revision)
self.info('Creating %s (version=%r)' % (target, version))
f = open(target, 'w')
f.write('version = %r\n' % (version))
f.close()
import atexit
def rm_file(f=target,p=self.info):
if delete:
try: os.remove(f); p('removed '+f)
except OSError: pass
try: os.remove(f+'c'); p('removed '+f+'c')
except OSError: pass
atexit.register(rm_file)
return target
self.add_data_files(('', generate_svn_version_py()))
def make_hg_version_py(self, delete=True):
"""Appends a data function to the data_files list that will generate
__hg_version__.py file to the current package directory.
Generate package __hg_version__.py file from Mercurial revision,
it will be removed after python exits but will be available
when sdist, etc commands are executed.
Notes
-----
If __hg_version__.py existed before, nothing is done.
This is intended for working with source directories that are
in an Mercurial repository.
"""
target = njoin(self.local_path, '__hg_version__.py')
revision = self._get_hg_revision(self.local_path)
if os.path.isfile(target) or revision is None:
return
else:
def generate_hg_version_py():
if not os.path.isfile(target):
version = str(revision)
self.info('Creating %s (version=%r)' % (target, version))
f = open(target, 'w')
f.write('version = %r\n' % (version))
f.close()
import atexit
def rm_file(f=target,p=self.info):
if delete:
try: os.remove(f); p('removed '+f)
except OSError: pass
try: os.remove(f+'c'); p('removed '+f+'c')
except OSError: pass
atexit.register(rm_file)
return target
self.add_data_files(('', generate_hg_version_py()))
def make_config_py(self,name='__config__'):
"""Generate package __config__.py file containing system_info
information used during building the package.
This file is installed to the
package installation directory.
"""
self.py_modules.append((self.name, name, generate_config_py))
def get_info(self,*names):
"""Get resources information.
Return information (from system_info.get_info) for all of the names in
the argument list in a single dictionary.
"""
from .system_info import get_info, dict_append
info_dict = {}
for a in names:
dict_append(info_dict,**get_info(a))
return info_dict
def get_cmd(cmdname, _cache={}):
if cmdname not in _cache:
import distutils.core
dist = distutils.core._setup_distribution
if dist is None:
from distutils.errors import DistutilsInternalError
raise DistutilsInternalError(
'setup distribution instance not initialized')
cmd = dist.get_command_obj(cmdname)
_cache[cmdname] = cmd
return _cache[cmdname]
def get_numpy_include_dirs():
# numpy_include_dirs are set by numpy/core/setup.py, otherwise []
include_dirs = Configuration.numpy_include_dirs[:]
if not include_dirs:
import numpy
include_dirs = [ numpy.get_include() ]
# else running numpy/core/setup.py
return include_dirs
def get_npy_pkg_dir():
"""Return the path where to find the npy-pkg-config directory."""
# XXX: import here for bootstrapping reasons
import numpy
d = os.path.join(os.path.dirname(numpy.__file__),
'core', 'lib', 'npy-pkg-config')
return d
def get_pkg_info(pkgname, dirs=None):
"""
Return library info for the given package.
Parameters
----------
pkgname : str
Name of the package (should match the name of the .ini file, without
the extension, e.g. foo for the file foo.ini).
dirs : sequence, optional
If given, should be a sequence of additional directories where to look
for npy-pkg-config files. Those directories are searched prior to the
NumPy directory.
Returns
-------
pkginfo : class instance
The `LibraryInfo` instance containing the build information.
Raises
------
PkgNotFound
If the package is not found.
See Also
--------
Configuration.add_npy_pkg_config, Configuration.add_installed_library,
get_info
"""
from numpy.distutils.npy_pkg_config import read_config
if dirs:
dirs.append(get_npy_pkg_dir())
else:
dirs = [get_npy_pkg_dir()]
return read_config(pkgname, dirs)
def get_info(pkgname, dirs=None):
"""
Return an info dict for a given C library.
The info dict contains the necessary options to use the C library.
Parameters
----------
pkgname : str
Name of the package (should match the name of the .ini file, without
the extension, e.g. foo for the file foo.ini).
dirs : sequence, optional
If given, should be a sequence of additional directories where to look
for npy-pkg-config files. Those directories are searched prior to the
NumPy directory.
Returns
-------
info : dict
The dictionary with build information.
Raises
------
PkgNotFound
If the package is not found.
See Also
--------
Configuration.add_npy_pkg_config, Configuration.add_installed_library,
get_pkg_info
Examples
--------
To get the necessary information for the npymath library from NumPy:
>>> npymath_info = np.distutils.misc_util.get_info('npymath')
>>> npymath_info #doctest: +SKIP
{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}
This info dict can then be used as input to a `Configuration` instance::
config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)
"""
from numpy.distutils.npy_pkg_config import parse_flags
pkg_info = get_pkg_info(pkgname, dirs)
# Translate LibraryInfo instance into a build_info dict
info = parse_flags(pkg_info.cflags())
for k, v in parse_flags(pkg_info.libs()).items():
info[k].extend(v)
# add_extension extra_info argument is ANAL
info['define_macros'] = info['macros']
del info['macros']
del info['ignored']
return info
def is_bootstrapping():
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
try:
builtins.__NUMPY_SETUP__
return True
except AttributeError:
return False
__NUMPY_SETUP__ = False
#########################
def default_config_dict(name = None, parent_name = None, local_path=None):
"""Return a configuration dictionary for usage in
configuration() function defined in file setup_<name>.py.
"""
import warnings
warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\
'deprecated default_config_dict(%r,%r,%r)'
% (name, parent_name, local_path,
name, parent_name, local_path,
))
c = Configuration(name, parent_name, local_path)
return c.todict()
def dict_append(d, **kws):
for k, v in kws.items():
if k in d:
ov = d[k]
if isinstance(ov, str):
d[k] = v
else:
d[k].extend(v)
else:
d[k] = v
def appendpath(prefix, path):
if os.path.sep != '/':
prefix = prefix.replace('/', os.path.sep)
path = path.replace('/', os.path.sep)
drive = ''
if os.path.isabs(path):
drive = os.path.splitdrive(prefix)[0]
absprefix = os.path.splitdrive(os.path.abspath(prefix))[1]
pathdrive, path = os.path.splitdrive(path)
d = os.path.commonprefix([absprefix, path])
if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \
or os.path.join(path[:len(d)], path[len(d):]) != path:
# Handle invalid paths
d = os.path.dirname(d)
subpath = path[len(d):]
if os.path.isabs(subpath):
subpath = subpath[1:]
else:
subpath = path
return os.path.normpath(njoin(drive + prefix, subpath))
def generate_config_py(target):
"""Generate config.py file containing system_info information
used during building the package.
Usage:
config['py_modules'].append((packagename, '__config__',generate_config_py))
"""
from numpy.distutils.system_info import system_info
from distutils.dir_util import mkpath
mkpath(os.path.dirname(target))
f = open(target, 'w')
f.write('# This file is generated by %s\n' % (os.path.abspath(sys.argv[0])))
f.write('# It contains system_info results at the time of building this package.\n')
f.write('__all__ = ["get_info","show"]\n\n')
for k, i in system_info.saved_results.items():
f.write('%s=%r\n' % (k, i))
f.write(r'''
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
''')
f.close()
return target
def msvc_version(compiler):
"""Return version major and minor of compiler instance if it is
MSVC, raise an exception otherwise."""
if not compiler.compiler_type == "msvc":
raise ValueError("Compiler instance is not msvc (%s)"\
% compiler.compiler_type)
return compiler._MSVCCompiler__version
if sys.version[:3] >= '2.5':
def get_build_architecture():
from distutils.msvccompiler import get_build_architecture
return get_build_architecture()
else:
#copied from python 2.5.1 distutils/msvccompiler.py
def get_build_architecture():
"""Return the processor architecture.
Possible results are "Intel", "Itanium", or "AMD64".
"""
prefix = " bit ("
i = sys.version.find(prefix)
if i == -1:
return "Intel"
j = sys.version.find(")", i)
return sys.version[i+len(prefix):j]
| mit |
scottcunningham/ansible | test/units/mock/loader.py | 50 | 2876 | # (c) 2012-2014, 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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleParserError
from ansible.parsing import DataLoader
class DictDataLoader(DataLoader):
def __init__(self, file_mapping=dict()):
assert type(file_mapping) == dict
self._file_mapping = file_mapping
self._build_known_directories()
super(DictDataLoader, self).__init__()
def load_from_file(self, path):
if path in self._file_mapping:
return self.load(self._file_mapping[path], path)
return None
def _get_file_contents(self, path):
if path in self._file_mapping:
return (self._file_mapping[path], False)
else:
raise AnsibleParserError("file not found: %s" % path)
def path_exists(self, path):
return path in self._file_mapping or path in self._known_directories
def is_file(self, path):
return path in self._file_mapping
def is_directory(self, path):
return path in self._known_directories
def list_directory(self, path):
return [x for x in self._known_directories]
def _add_known_directory(self, directory):
if directory not in self._known_directories:
self._known_directories.append(directory)
def _build_known_directories(self):
self._known_directories = []
for path in self._file_mapping:
dirname = os.path.dirname(path)
while dirname not in ('/', ''):
self._add_known_directory(dirname)
dirname = os.path.dirname(dirname)
def push(self, path, content):
rebuild_dirs = False
if path not in self._file_mapping:
rebuild_dirs = True
self._file_mapping[path] = content
if rebuild_dirs:
self._build_known_directories()
def pop(self, path):
if path in self._file_mapping:
del self._file_mapping[path]
self._build_known_directories()
def clear(self):
self._file_mapping = dict()
self._known_directories = []
| gpl-3.0 |
LUTAN/tensorflow | tensorflow/contrib/cloud/python/ops/bigquery_reader_ops_test.py | 26 | 9667 | # 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 BigQueryReader Op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import re
import socket
import threading
from six.moves import SimpleHTTPServer
from six.moves import socketserver
from tensorflow.contrib.cloud.python.ops import bigquery_reader_ops as cloud
from tensorflow.core.example import example_pb2
from tensorflow.core.framework import types_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
_PROJECT = "test-project"
_DATASET = "test-dataset"
_TABLE = "test-table"
# List representation of the test rows in the 'test-table' in BigQuery.
# The schema for each row is: [int64, string, float].
# The values for rows are generated such that some columns have null values. The
# general formula here is:
# - The int64 column is present in every row.
# - The string column is only avaiable in even rows.
# - The float column is only available in every third row.
_ROWS = [[0, "s_0", 0.1], [1, None, None], [2, "s_2", None], [3, None, 3.1],
[4, "s_4", None], [5, None, None], [6, "s_6", 6.1], [7, None, None],
[8, "s_8", None], [9, None, 9.1]]
# Schema for 'test-table'.
# The schema currently has three columns: int64, string, and float
_SCHEMA = {
"kind": "bigquery#table",
"id": "test-project:test-dataset.test-table",
"schema": {
"fields": [{
"name": "int64_col",
"type": "INTEGER",
"mode": "NULLABLE"
}, {
"name": "string_col",
"type": "STRING",
"mode": "NULLABLE"
}, {
"name": "float_col",
"type": "FLOAT",
"mode": "NULLABLE"
}]
}
}
def _ConvertRowToExampleProto(row):
"""Converts the input row to an Example proto.
Args:
row: Input Row instance.
Returns:
An Example proto initialized with row values.
"""
example = example_pb2.Example()
example.features.feature["int64_col"].int64_list.value.append(row[0])
if row[1] is not None:
example.features.feature["string_col"].bytes_list.value.append(
compat.as_bytes(row[1]))
if row[2] is not None:
example.features.feature["float_col"].float_list.value.append(row[2])
return example
class IPv6TCPServer(socketserver.TCPServer):
address_family = socket.AF_INET6
class FakeBigQueryServer(threading.Thread):
"""Fake http server to return schema and data for sample table."""
def __init__(self, address, port):
"""Creates a FakeBigQueryServer.
Args:
address: Server address
port: Server port. Pass 0 to automatically pick an empty port.
"""
threading.Thread.__init__(self)
self.handler = BigQueryRequestHandler
try:
self.httpd = socketserver.TCPServer((address, port), self.handler)
self.host_port = "{}:{}".format(*self.httpd.server_address)
except IOError:
self.httpd = IPv6TCPServer((address, port), self.handler)
self.host_port = "[{}]:{}".format(*self.httpd.server_address)
def run(self):
self.httpd.serve_forever()
def shutdown(self):
self.httpd.shutdown()
self.httpd.socket.close()
class BigQueryRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""Responds to BigQuery HTTP requests.
Attributes:
num_rows: num_rows in the underlying table served by this class.
"""
num_rows = 0
def do_GET(self):
if "data?maxResults=" not in self.path:
# This is a schema request.
_SCHEMA["numRows"] = self.num_rows
response = json.dumps(_SCHEMA)
else:
# This is a data request.
#
# Extract max results and start index.
max_results = int(re.findall(r"maxResults=(\d+)", self.path)[0])
start_index = int(re.findall(r"startIndex=(\d+)", self.path)[0])
# Send the rows as JSON.
rows = []
for row in _ROWS[start_index:start_index + max_results]:
row_json = {
"f": [{
"v": str(row[0])
}, {
"v": str(row[1]) if row[1] is not None else None
}, {
"v": str(row[2]) if row[2] is not None else None
}]
}
rows.append(row_json)
response = json.dumps({
"kind": "bigquery#table",
"id": "test-project:test-dataset.test-table",
"rows": rows
})
self.send_response(200)
self.end_headers()
self.wfile.write(compat.as_bytes(response))
def _SetUpQueue(reader):
"""Sets up a queue for a reader."""
queue = data_flow_ops.FIFOQueue(8, [types_pb2.DT_STRING], shapes=())
key, value = reader.read(queue)
queue.enqueue_many(reader.partitions()).run()
queue.close().run()
return key, value
class BigQueryReaderOpsTest(test.TestCase):
def setUp(self):
super(BigQueryReaderOpsTest, self).setUp()
self.server = FakeBigQueryServer("localhost", 0)
self.server.start()
logging.info("server address is %s", self.server.host_port)
# An override to bypass the GCP auth token retrieval logic
# in google_auth_provider.cc.
os.environ["GOOGLE_AUTH_TOKEN_FOR_TESTING"] = "not-used"
def tearDown(self):
self.server.shutdown()
super(BigQueryReaderOpsTest, self).tearDown()
def _ReadAndCheckRowsUsingFeatures(self, num_rows):
self.server.handler.num_rows = num_rows
with self.test_session() as sess:
feature_configs = {
"int64_col":
parsing_ops.FixedLenFeature(
[1], dtype=dtypes.int64),
"string_col":
parsing_ops.FixedLenFeature(
[1], dtype=dtypes.string, default_value="s_default"),
}
reader = cloud.BigQueryReader(
project_id=_PROJECT,
dataset_id=_DATASET,
table_id=_TABLE,
num_partitions=4,
features=feature_configs,
timestamp_millis=1,
test_end_point=self.server.host_port)
key, value = _SetUpQueue(reader)
seen_rows = []
features = parsing_ops.parse_example(
array_ops.reshape(value, [1]), feature_configs)
for _ in range(num_rows):
int_value, str_value = sess.run(
[features["int64_col"], features["string_col"]])
# Parse values returned from the session.
self.assertEqual(int_value.shape, (1, 1))
self.assertEqual(str_value.shape, (1, 1))
int64_col = int_value[0][0]
string_col = str_value[0][0]
seen_rows.append(int64_col)
# Compare.
expected_row = _ROWS[int64_col]
self.assertEqual(int64_col, expected_row[0])
self.assertEqual(
compat.as_str(string_col), ("s_%d" % int64_col) if expected_row[1]
else "s_default")
self.assertItemsEqual(seen_rows, range(num_rows))
with self.assertRaisesOpError("is closed and has insufficient elements "
"\\(requested 1, current size 0\\)"):
sess.run([key, value])
def testReadingSingleRowUsingFeatures(self):
self._ReadAndCheckRowsUsingFeatures(1)
def testReadingMultipleRowsUsingFeatures(self):
self._ReadAndCheckRowsUsingFeatures(10)
def testReadingMultipleRowsUsingColumns(self):
num_rows = 10
self.server.handler.num_rows = num_rows
with self.test_session() as sess:
reader = cloud.BigQueryReader(
project_id=_PROJECT,
dataset_id=_DATASET,
table_id=_TABLE,
num_partitions=4,
columns=["int64_col", "float_col", "string_col"],
timestamp_millis=1,
test_end_point=self.server.host_port)
key, value = _SetUpQueue(reader)
seen_rows = []
for row_index in range(num_rows):
returned_row_id, example_proto = sess.run([key, value])
example = example_pb2.Example()
example.ParseFromString(example_proto)
self.assertIn("int64_col", example.features.feature)
feature = example.features.feature["int64_col"]
self.assertEqual(len(feature.int64_list.value), 1)
int64_col = feature.int64_list.value[0]
seen_rows.append(int64_col)
# Create our expected Example.
expected_example = example_pb2.Example()
expected_example = _ConvertRowToExampleProto(_ROWS[int64_col])
# Compare.
self.assertProtoEquals(example, expected_example)
self.assertEqual(row_index, int(returned_row_id))
self.assertItemsEqual(seen_rows, range(num_rows))
with self.assertRaisesOpError("is closed and has insufficient elements "
"\\(requested 1, current size 0\\)"):
sess.run([key, value])
if __name__ == "__main__":
test.main()
| apache-2.0 |
legnaleurc/kczzz | util.sikuli/util.py | 1 | 1841 | """
Copyright (c) 2013 Wei-Cheng Pan <legnaleurc@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import logging
class Logger(object):
def __init__(self):
self._logger = logging.getLogger(__name__)
self._fh = logging.FileHandler(u'/tmp/kczzz.log')
fmt = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
self._fh.setFormatter(fmt)
self._logger.setLevel(logging.DEBUG)
self._logger.addHandler(self._fh)
def debug(self, msg):
self._logger.debug(msg)
self._flush()
def info(self, msg):
self._logger.info(msg)
self._flush()
def warn(self, msg):
self._logger.warn(msg)
self._flush()
def error(self, msg):
self._logger.error(msg)
self._flush()
def _flush(self):
self._fh.flush()
| mit |
kirangonella/BuildingMachineLearningSystemsWithPython | ch02/figure1.py | 22 | 1199 | # This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
from matplotlib import pyplot as plt
# We load the data with load_iris from sklearn
from sklearn.datasets import load_iris
# load_iris returns an object with several fields
data = load_iris()
features = data.data
feature_names = data.feature_names
target = data.target
target_names = data.target_names
fig,axes = plt.subplots(2, 3)
pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
# Set up 3 different pairs of (color, marker)
color_markers = [
('r', '>'),
('g', 'o'),
('b', 'x'),
]
for i, (p0, p1) in enumerate(pairs):
ax = axes.flat[i]
for t in range(3):
# Use a different color/marker for each class `t`
c,marker = color_markers[t]
ax.scatter(features[target == t, p0], features[
target == t, p1], marker=marker, c=c)
ax.set_xlabel(feature_names[p0])
ax.set_ylabel(feature_names[p1])
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
fig.savefig('figure1.png')
| mit |
takeshineshiro/cinder | cinder/tests/unit/scheduler/test_filter_scheduler.py | 5 | 20105 | # Copyright 2011 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.
"""
Tests For Filter Scheduler.
"""
import mock
from cinder import context
from cinder import exception
from cinder.scheduler import filter_scheduler
from cinder.scheduler import host_manager
from cinder.tests.unit.scheduler import fakes
from cinder.tests.unit.scheduler import test_scheduler
from cinder.volume import utils
class FilterSchedulerTestCase(test_scheduler.SchedulerTestCase):
"""Test case for Filter Scheduler."""
driver_cls = filter_scheduler.FilterScheduler
def test_create_consistencygroup_no_hosts(self):
# Ensure empty hosts result in NoValidHosts exception.
sched = fakes.FakeFilterScheduler()
fake_context = context.RequestContext('user', 'project')
request_spec = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type1',
'extra_specs': {}}}
request_spec2 = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type2',
'extra_specs': {}}}
request_spec_list = [request_spec, request_spec2]
self.assertRaises(exception.NoValidHost,
sched.schedule_create_consistencygroup,
fake_context, 'faki-id1', request_spec_list, {})
@mock.patch('cinder.db.service_get_all_by_topic')
def test_schedule_consistencygroup(self,
_mock_service_get_all_by_topic):
# Make sure _schedule_group() can find host successfully.
sched = fakes.FakeFilterScheduler()
sched.host_manager = fakes.FakeHostManager()
fake_context = context.RequestContext('user', 'project',
is_admin=True)
fakes.mock_host_manager_db_calls(_mock_service_get_all_by_topic)
specs = {'capabilities:consistencygroup_support': '<is> True'}
request_spec = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type1',
'extra_specs': specs}}
request_spec2 = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type2',
'extra_specs': specs}}
request_spec_list = [request_spec, request_spec2]
weighed_host = sched._schedule_group(fake_context,
request_spec_list,
{})
self.assertIsNotNone(weighed_host.obj)
self.assertTrue(_mock_service_get_all_by_topic.called)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_schedule_consistencygroup_no_cg_support_in_extra_specs(
self,
_mock_service_get_all_by_topic):
# Make sure _schedule_group() can find host successfully even
# when consistencygroup_support is not specified in volume type's
# extra specs
sched = fakes.FakeFilterScheduler()
sched.host_manager = fakes.FakeHostManager()
fake_context = context.RequestContext('user', 'project',
is_admin=True)
fakes.mock_host_manager_db_calls(_mock_service_get_all_by_topic)
request_spec = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type1',
'extra_specs': {}}}
request_spec2 = {'volume_properties': {'project_id': 1,
'size': 0},
'volume_type': {'name': 'Type2',
'extra_specs': {}}}
request_spec_list = [request_spec, request_spec2]
weighed_host = sched._schedule_group(fake_context,
request_spec_list,
{})
self.assertIsNotNone(weighed_host.obj)
self.assertTrue(_mock_service_get_all_by_topic.called)
def test_create_volume_no_hosts(self):
# Ensure empty hosts/child_zones result in NoValidHosts exception.
sched = fakes.FakeFilterScheduler()
fake_context = context.RequestContext('user', 'project')
request_spec = {'volume_properties': {'project_id': 1,
'size': 1},
'volume_type': {'name': 'LVM_iSCSI'},
'volume_id': ['fake-id1']}
self.assertRaises(exception.NoValidHost, sched.schedule_create_volume,
fake_context, request_spec, {})
def test_create_volume_no_hosts_invalid_req(self):
sched = fakes.FakeFilterScheduler()
fake_context = context.RequestContext('user', 'project')
# request_spec is missing 'volume_id'
request_spec = {'volume_properties': {'project_id': 1,
'size': 1},
'volume_type': {'name': 'LVM_iSCSI'}}
self.assertRaises(exception.NoValidHost,
sched.schedule_create_volume,
fake_context,
request_spec,
{})
@mock.patch('cinder.scheduler.host_manager.HostManager.'
'get_all_host_states')
def test_create_volume_non_admin(self, _mock_get_all_host_states):
# Test creating a volume locally using create_volume, passing
# a non-admin context. DB actions should work.
self.was_admin = False
def fake_get(ctxt):
# Make sure this is called with admin context, even though
# we're using user context below.
self.was_admin = ctxt.is_admin
return {}
sched = fakes.FakeFilterScheduler()
_mock_get_all_host_states.side_effect = fake_get
fake_context = context.RequestContext('user', 'project')
request_spec = {'volume_properties': {'project_id': 1,
'size': 1},
'volume_type': {'name': 'LVM_iSCSI'},
'volume_id': ['fake-id1']}
self.assertRaises(exception.NoValidHost, sched.schedule_create_volume,
fake_context, request_spec, {})
self.assertTrue(self.was_admin)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_schedule_happy_day(self, _mock_service_get_all_by_topic):
# Make sure there's nothing glaringly wrong with _schedule()
# by doing a happy day pass through.
sched = fakes.FakeFilterScheduler()
sched.host_manager = fakes.FakeHostManager()
fake_context = context.RequestContext('user', 'project',
is_admin=True)
fakes.mock_host_manager_db_calls(_mock_service_get_all_by_topic)
request_spec = {'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
weighed_host = sched._schedule(fake_context, request_spec, {})
self.assertIsNotNone(weighed_host.obj)
self.assertTrue(_mock_service_get_all_by_topic.called)
def test_max_attempts(self):
self.flags(scheduler_max_attempts=4)
sched = fakes.FakeFilterScheduler()
self.assertEqual(4, sched._max_attempts())
def test_invalid_max_attempts(self):
self.flags(scheduler_max_attempts=0)
self.assertRaises(exception.InvalidParameterValue,
fakes.FakeFilterScheduler)
def test_retry_disabled(self):
# Retry info should not get populated when re-scheduling is off.
self.flags(scheduler_max_attempts=1)
sched = fakes.FakeFilterScheduler()
request_spec = {'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
filter_properties = {}
sched._schedule(self.context, request_spec,
filter_properties=filter_properties)
# Should not have retry info in the populated filter properties.
self.assertNotIn("retry", filter_properties)
def test_retry_attempt_one(self):
# Test retry logic on initial scheduling attempt.
self.flags(scheduler_max_attempts=2)
sched = fakes.FakeFilterScheduler()
request_spec = {'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
filter_properties = {}
sched._schedule(self.context, request_spec,
filter_properties=filter_properties)
num_attempts = filter_properties['retry']['num_attempts']
self.assertEqual(1, num_attempts)
def test_retry_attempt_two(self):
# Test retry logic when re-scheduling.
self.flags(scheduler_max_attempts=2)
sched = fakes.FakeFilterScheduler()
request_spec = {'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
retry = dict(num_attempts=1)
filter_properties = dict(retry=retry)
sched._schedule(self.context, request_spec,
filter_properties=filter_properties)
num_attempts = filter_properties['retry']['num_attempts']
self.assertEqual(2, num_attempts)
def test_retry_exceeded_max_attempts(self):
# Test for necessary explosion when max retries is exceeded.
self.flags(scheduler_max_attempts=2)
sched = fakes.FakeFilterScheduler()
request_spec = {'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
retry = dict(num_attempts=2)
filter_properties = dict(retry=retry)
self.assertRaises(exception.NoValidHost, sched._schedule, self.context,
request_spec, filter_properties=filter_properties)
def test_add_retry_host(self):
retry = dict(num_attempts=1, hosts=[])
filter_properties = dict(retry=retry)
host = "fakehost"
sched = fakes.FakeFilterScheduler()
sched._add_retry_host(filter_properties, host)
hosts = filter_properties['retry']['hosts']
self.assertEqual(1, len(hosts))
self.assertEqual(host, hosts[0])
def test_post_select_populate(self):
# Test addition of certain filter props after a node is selected.
retry = {'hosts': [], 'num_attempts': 1}
filter_properties = {'retry': retry}
sched = fakes.FakeFilterScheduler()
host_state = host_manager.HostState('host')
host_state.total_capacity_gb = 1024
sched._post_select_populate_filter_properties(filter_properties,
host_state)
self.assertEqual('host',
filter_properties['retry']['hosts'][0])
self.assertEqual(1024, host_state.total_capacity_gb)
def _host_passes_filters_setup(self, mock_obj):
sched = fakes.FakeFilterScheduler()
sched.host_manager = fakes.FakeHostManager()
fake_context = context.RequestContext('user', 'project',
is_admin=True)
fakes.mock_host_manager_db_calls(mock_obj)
return (sched, fake_context)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_host_passes_filters_happy_day(self, _mock_service_get_topic):
"""Do a successful pass through of with host_passes_filters()."""
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
ret_host = sched.host_passes_filters(ctx, 'host1#lvm1',
request_spec, {})
self.assertEqual('host1', utils.extract_host(ret_host.host))
self.assertTrue(_mock_service_get_topic.called)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_host_passes_filters_default_pool_happy_day(
self, _mock_service_get_topic):
"""Do a successful pass through of with host_passes_filters()."""
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1}}
ret_host = sched.host_passes_filters(ctx, 'host5#_pool0',
request_spec, {})
self.assertEqual('host5', utils.extract_host(ret_host.host))
self.assertTrue(_mock_service_get_topic.called)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_host_passes_filters_no_capacity(self, _mock_service_get_topic):
"""Fail the host due to insufficient capacity."""
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI'},
'volume_properties': {'project_id': 1,
'size': 1024}}
self.assertRaises(exception.NoValidHost,
sched.host_passes_filters,
ctx, 'host1#lvm1', request_spec, {})
self.assertTrue(_mock_service_get_topic.called)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_retype_policy_never_migrate_pass(self, _mock_service_get_topic):
# Retype should pass if current host passes filters and
# policy=never. host4 doesn't have enough space to hold an additional
# 200GB, but it is already the host of this volume and should not be
# counted twice.
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
extra_specs = {'volume_backend_name': 'lvm4'}
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI',
'extra_specs': extra_specs},
'volume_properties': {'project_id': 1,
'size': 200,
'host': 'host4#lvm4'}}
host_state = sched.find_retype_host(ctx, request_spec,
filter_properties={},
migration_policy='never')
self.assertEqual('host4', utils.extract_host(host_state.host))
@mock.patch('cinder.db.service_get_all_by_topic')
def test_retype_with_pool_policy_never_migrate_pass(
self, _mock_service_get_topic):
# Retype should pass if current host passes filters and
# policy=never. host4 doesn't have enough space to hold an additional
# 200GB, but it is already the host of this volume and should not be
# counted twice.
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
extra_specs = {'volume_backend_name': 'lvm3'}
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI',
'extra_specs': extra_specs},
'volume_properties': {'project_id': 1,
'size': 200,
'host': 'host3#lvm3'}}
host_state = sched.find_retype_host(ctx, request_spec,
filter_properties={},
migration_policy='never')
self.assertEqual('host3#lvm3', host_state.host)
@mock.patch('cinder.db.service_get_all_by_topic')
def test_retype_policy_never_migrate_fail(self, _mock_service_get_topic):
# Retype should fail if current host doesn't pass filters and
# policy=never.
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
extra_specs = {'volume_backend_name': 'lvm1'}
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI',
'extra_specs': extra_specs},
'volume_properties': {'project_id': 1,
'size': 200,
'host': 'host4'}}
self.assertRaises(exception.NoValidHost, sched.find_retype_host, ctx,
request_spec, filter_properties={},
migration_policy='never')
@mock.patch('cinder.db.service_get_all_by_topic')
def test_retype_policy_demand_migrate_pass(self, _mock_service_get_topic):
# Retype should pass if current host fails filters but another host
# is suitable when policy=on-demand.
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
extra_specs = {'volume_backend_name': 'lvm1'}
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI',
'extra_specs': extra_specs},
'volume_properties': {'project_id': 1,
'size': 200,
'host': 'host4'}}
host_state = sched.find_retype_host(ctx, request_spec,
filter_properties={},
migration_policy='on-demand')
self.assertEqual('host1', utils.extract_host(host_state.host))
@mock.patch('cinder.db.service_get_all_by_topic')
def test_retype_policy_demand_migrate_fail(self, _mock_service_get_topic):
# Retype should fail if current host doesn't pass filters and
# no other suitable candidates exist even if policy=on-demand.
sched, ctx = self._host_passes_filters_setup(
_mock_service_get_topic)
extra_specs = {'volume_backend_name': 'lvm1'}
request_spec = {'volume_id': 1,
'volume_type': {'name': 'LVM_iSCSI',
'extra_specs': extra_specs},
'volume_properties': {'project_id': 1,
'size': 2048,
'host': 'host4'}}
self.assertRaises(exception.NoValidHost, sched.find_retype_host, ctx,
request_spec, filter_properties={},
migration_policy='on-demand')
| apache-2.0 |
sumedhasingla/VTK | Filters/Modeling/Testing/Python/subDivideTetra.py | 20 | 1544 | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
tetraPoints = vtk.vtkPoints()
tetraPoints.SetNumberOfPoints(4)
tetraPoints.InsertPoint(0,0,0,0)
tetraPoints.InsertPoint(1,1,0,0)
tetraPoints.InsertPoint(2,.5,1,0)
tetraPoints.InsertPoint(3,.5,.5,1)
aTetra = vtk.vtkTetra()
aTetra.GetPointIds().SetId(0,0)
aTetra.GetPointIds().SetId(1,1)
aTetra.GetPointIds().SetId(2,2)
aTetra.GetPointIds().SetId(3,3)
aTetraGrid = vtk.vtkUnstructuredGrid()
aTetraGrid.Allocate(1,1)
aTetraGrid.InsertNextCell(aTetra.GetCellType(),aTetra.GetPointIds())
aTetraGrid.SetPoints(tetraPoints)
sub = vtk.vtkSubdivideTetra()
sub.SetInputData(aTetraGrid)
shrinker = vtk.vtkShrinkFilter()
shrinker.SetInputConnection(sub.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(shrinker.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(0.7400,0.9900,0.7900)
# define graphics stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
ren1.AddActor(actor)
ren1.SetBackground(0.1,0.2,0.4)
renWin.SetSize(300,300)
cam1 = ren1.GetActiveCamera()
cam1.SetClippingRange(0.183196,9.15979)
cam1.SetFocalPoint(0.579471,0.462507,0.283392)
cam1.SetPosition(-1.04453,0.345281,-0.556222)
cam1.SetViewUp(0.197321,0.843578,-0.499441)
ren1.ResetCameraClippingRange()
renWin.Render()
# render the image
#
iren.Initialize()
# --- end of script --
| bsd-3-clause |
nippoo/phy | phy/traces/tests/test_detect.py | 2 | 8735 | # -*- coding: utf-8 -*-
"""Tests of spike detection routines."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import numpy as np
from numpy.testing import assert_array_equal as ae
from numpy.testing import assert_allclose as ac
from ..detect import (compute_threshold,
Thresholder,
connected_components,
FloodFillDetector,
)
from ...io.mock import artificial_traces
#------------------------------------------------------------------------------
# Test thresholder
#------------------------------------------------------------------------------
def test_compute_threshold():
n_samples, n_channels = 100, 10
data = artificial_traces(n_samples, n_channels)
# Single threshold.
threshold = compute_threshold(data, std_factor=1.)
assert threshold.shape == (2,)
assert threshold[0] > 0
assert threshold[0] == threshold[1]
threshold = compute_threshold(data, std_factor=[1., 2.])
assert threshold.shape == (2,)
assert threshold[1] == 2 * threshold[0]
# Multiple threshold.
threshold = compute_threshold(data, single_threshold=False, std_factor=2.)
assert threshold.shape == (2, n_channels)
threshold = compute_threshold(data,
single_threshold=False,
std_factor=(1., 2.))
assert threshold.shape == (2, n_channels)
ac(threshold[1], 2 * threshold[0])
def test_thresholder():
n_samples, n_channels = 100, 12
strong, weak = .1, .2
data = artificial_traces(n_samples, n_channels)
# Positive and strong.
thresholder = Thresholder(mode='positive',
thresholds=strong)
ae(thresholder(data), data > strong)
# Negative and weak.
thresholder = Thresholder(mode='negative',
thresholds={'weak': weak})
ae(thresholder(data), data < -weak)
# Both and strong+weak.
thresholder = Thresholder(mode='both',
thresholds={'weak': weak,
'strong': strong,
})
ae(thresholder(data, 'weak'), np.abs(data) > weak)
ae(thresholder(data, threshold='strong'), np.abs(data) > strong)
# Multiple thresholds.
t = thresholder(data, ('weak', 'strong'))
ae(t['weak'], np.abs(data) > weak)
ae(t['strong'], np.abs(data) > strong)
# Array threshold.
thre = np.linspace(weak - .05, strong + .05, n_channels)
thresholder = Thresholder(mode='positive', thresholds=thre)
t = thresholder(data)
assert t.shape == data.shape
ae(t, data > thre)
#------------------------------------------------------------------------------
# Test connected components
#------------------------------------------------------------------------------
def _as_set(c):
if isinstance(c, np.ndarray):
c = c.tolist()
c = [tuple(_) for _ in c]
return set(c)
def _assert_components_equal(cc1, cc2):
assert len(cc1) == len(cc2)
for c1, c2 in zip(cc1, cc2):
assert _as_set(c1) == _as_set(c2)
def _test_components(chunk=None, components=None, **kwargs):
def _clip(x, m, M):
return [_ for _ in x if m <= _ < M]
n = 5
probe_adjacency_list = {i: set(_clip([i - 1, i + 1], 0, n))
for i in range(n)}
if chunk is None:
chunk = [[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 1, 0],
[1, 0, 0, 1, 0],
[0, 1, 0, 1, 1],
]
if components is None:
components = []
if not isinstance(chunk, np.ndarray):
chunk = np.array(chunk)
strong_crossings = kwargs.pop('strong_crossings', None)
if (strong_crossings is not None and
not isinstance(strong_crossings, np.ndarray)):
strong_crossings = np.array(strong_crossings)
comp = connected_components(chunk,
probe_adjacency_list=probe_adjacency_list,
strong_crossings=strong_crossings,
**kwargs)
_assert_components_equal(comp, components)
def test_components():
# 1 time step, 1 element
_test_components([[0, 0, 0, 0, 0]], [])
_test_components([[1, 0, 0, 0, 0]], [[(0, 0)]])
_test_components([[0, 1, 0, 0, 0]], [[(0, 1)]])
_test_components([[0, 0, 0, 1, 0]], [[(0, 3)]])
_test_components([[0, 0, 0, 0, 1]], [[(0, 4)]])
# 1 time step, 2 elements
_test_components([[1, 1, 0, 0, 0]], [[(0, 0), (0, 1)]])
_test_components([[1, 0, 1, 0, 0]], [[(0, 0)], [(0, 2)]])
_test_components([[1, 0, 0, 0, 1]], [[(0, 0)], [(0, 4)]])
_test_components([[0, 1, 0, 1, 0]], [[(0, 1)], [(0, 3)]])
# 1 time step, 3 elements
_test_components([[1, 1, 1, 0, 0]], [[(0, 0), (0, 1), (0, 2)]])
_test_components([[1, 1, 0, 1, 0]], [[(0, 0), (0, 1)], [(0, 3)]])
_test_components([[1, 0, 1, 1, 0]], [[(0, 0)], [(0, 2), (0, 3)]])
_test_components([[0, 1, 1, 1, 0]], [[(0, 1), (0, 2), (0, 3)]])
_test_components([[0, 1, 1, 0, 1]], [[(0, 1), (0, 2)], [(0, 4)]])
# 5 time steps, varying join_size
_test_components([
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 1, 0],
[1, 0, 0, 1, 0],
[0, 1, 0, 1, 1],
], [[(1, 2)],
[(2, 0)],
[(2, 2), (2, 3)],
[(3, 0)],
[(3, 3)],
[(4, 1)],
[(4, 3), (4, 4)],
])
_test_components([
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 1, 0],
[1, 0, 0, 1, 0],
[0, 1, 0, 1, 1],
], [[(1, 2), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4)],
[(2, 0), (3, 0), (4, 1)]], join_size=1)
_test_components(
components=[[(1, 2), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4),
(2, 0), (3, 0), (4, 1)]], join_size=2)
# 5 time steps, strong != weak
_test_components(join_size=0,
strong_crossings=[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
_test_components(components=[[(1, 2)]],
join_size=0,
strong_crossings=[
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
_test_components(
components=[[(1, 2), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4)]],
join_size=1,
strong_crossings=[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]])
_test_components(
components=[[(1, 2), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4),
(2, 0), (3, 0), (4, 1)]],
join_size=2,
strong_crossings=[
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
_test_components(
components=[[(1, 2), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4),
(2, 0), (3, 0), (4, 1)]],
join_size=2,
strong_crossings=[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0]])
def test_flood_fill():
graph = {0: [1, 2], 1: [0, 2], 2: [0, 1], 3: []}
ff = FloodFillDetector(probe_adjacency_list=graph,
join_size=1,
)
weak = [[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
]
# Weak - weak
comps = [[(1, 1), (1, 2)],
[(3, 2), (4, 2)],
[(4, 3)],
[(6, 3)],
]
cc = ff(weak, weak)
_assert_components_equal(cc, comps)
# Weak and strong
strong = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
]
comps = [[(3, 2), (4, 2)],
[(4, 3)],
[(6, 3)],
]
cc = ff(weak, strong)
_assert_components_equal(cc, comps)
| bsd-3-clause |
jjgomera/pychemqt | tools/costIndex.py | 1 | 13635 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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/>.'''
###############################################################################
# Library with costindex functionality
# -UI_CostIndex: Dialog to configure costindex values
# -CostData: Common widget to equipment with cost section
###############################################################################
from functools import partial
import os
from PyQt5 import QtCore, QtWidgets
from UI.widgets import Entrada_con_unidades
from lib import config
indiceBase = ["Jan-1982", 313.95, 336.19, 326.01, 312.03, 383.18, 297.63,
421.1, 235.42, 338.2, 263.92, 290.13, 303.26]
# Load data from config file
indiceActual = []
with open(config.conf_dir+"CostIndex.dat", "r") as archivo:
indiceActual.append(archivo.readline()[:-1])
while True:
data = archivo.readline().rstrip("\n")
if data:
indiceActual.append(float(data))
if len(indiceActual) == 13:
break
class Ui_CostIndex(QtWidgets.QDialog):
"""Dialog to show/configure costIndex"""
def __init__(self, parent=None):
super(Ui_CostIndex, self).__init__(parent)
self.setWindowTitle(
QtWidgets.QApplication.translate("pychemqt", "Cost Index"))
self.custom = True
layout = QtWidgets.QGridLayout(self)
self.fecha = QtWidgets.QComboBox()
layout.addWidget(self.fecha, 1, 1, 1, 3)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "CE INDEX")), 2, 1, 1, 2)
self.index = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.index, 2, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Equipments")), 3, 1, 1, 2)
self.equipos = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.equipos, 3, 3, 1, 1)
layout.addItem(QtWidgets.QSpacerItem(
30, 0, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed),
4, 1, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Heat exchangers & Tanks")), 4, 2, 1, 1)
self.cambiadores_calor = Entrada_con_unidades(
float, width=70, decimales=1)
layout.addWidget(self.cambiadores_calor, 4, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Process machinery")), 5, 2, 1, 1)
self.maquinaria = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.maquinaria, 5, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Pipe, valves & fittings")), 6, 2, 1, 1)
self.tuberias = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.tuberias, 6, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Process instruments")), 7, 2, 1, 1)
self.instrumentos = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.instrumentos, 7, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Pumps & compressors")), 8, 2, 1, 1)
self.bombas = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.bombas, 8, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Electrical equipments")), 9, 2, 1, 1)
self.equipos_electricos = Entrada_con_unidades(
float, width=70, decimales=1)
layout.addWidget(self.equipos_electricos, 9, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Structural supports & misc")), 10, 2, 1, 1)
self.soportes = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.soportes, 10, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Construction labor")), 11, 1, 1, 2)
self.construccion = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.construccion, 11, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Buildings")), 12, 1, 1, 2)
self.edificios = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.edificios, 12, 3, 1, 1)
layout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Engineering & supervision")), 13, 1, 1, 2)
self.ingenieria = Entrada_con_unidades(float, width=70, decimales=1)
layout.addWidget(self.ingenieria, 13, 3, 1, 1)
self.buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
layout.addWidget(self.buttonBox, 14, 1, 1, 3)
# Fill all widget data
self.indices = []
with open(os.environ["pychemqt"] + "dat/costindex.dat") as archivo:
texto = archivo.readlines()
for txt in texto:
dato = txt.split()
self.fecha.addItem(dato[0])
self.indices.append(dato[1:])
fecha = indiceActual[0]
self.index.setValue(indiceActual[1])
self.equipos.setValue(indiceActual[2])
self.cambiadores_calor.setValue(indiceActual[3])
self.maquinaria.setValue(indiceActual[4])
self.tuberias.setValue(indiceActual[5])
self.instrumentos.setValue(indiceActual[6])
self.bombas.setValue(indiceActual[7])
self.equipos_electricos.setValue(indiceActual[8])
self.soportes.setValue(indiceActual[9])
self.construccion.setValue(indiceActual[10])
self.edificios.setValue(indiceActual[11])
self.ingenieria.setValue(indiceActual[12])
if fecha:
self.fecha.setCurrentIndex(self.fecha.findText(fecha))
else:
self.fecha.setCurrentIndex(-1)
self.fecha.currentIndexChanged.connect(self.loadData)
def setCustom(self):
"""Set custom currentIndex"""
self.fecha.setCurrentIndex(-1)
self.custom = True
def loadData(self, int):
"""Load costIndex data from file"""
self.index.setValue(float(self.indices[int][0]))
self.equipos.setValue(float(self.indices[int][1]))
self.cambiadores_calor.setValue(float(self.indices[int][2]))
self.maquinaria.setValue(float(self.indices[int][3]))
self.tuberias.setValue(float(self.indices[int][4]))
self.instrumentos.setValue(float(self.indices[int][5]))
self.bombas.setValue(float(self.indices[int][6]))
self.equipos_electricos.setValue(float(self.indices[int][7]))
self.soportes.setValue(float(self.indices[int][8]))
self.construccion.setValue(float(self.indices[int][9]))
self.edificios.setValue(float(self.indices[int][10]))
self.ingenieria.setValue(float(self.indices[int][11]))
self.custom = False
def closeEvent(self, event):
"""Override close event to ask data changes"""
dialog = QtWidgets.QMessageBox.question(
self,
QtWidgets.QApplication.translate("pychemqt", "Unsaved changes"),
QtWidgets.QApplication.translate("pychemqt",
"Save unsaved changes?"),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.Yes)
if dialog == QtWidgets.QMessageBox.Yes:
self.accept()
else:
event.accept()
def accept(self):
"""Overwrite accept signal to save changes"""
with open(config.conf_dir+"CostIndex.dat", "w") as archivo:
if self.custom:
archivo.write("custom\n")
else:
archivo.write(self.fecha.currentText()+"\n")
archivo.write(str(self.index.value)+"\n")
archivo.write(str(self.equipos.value)+"\n")
archivo.write(str(self.cambiadores_calor.value)+"\n")
archivo.write(str(self.maquinaria.value)+"\n")
archivo.write(str(self.tuberias.value)+"\n")
archivo.write(str(self.instrumentos.value)+"\n")
archivo.write(str(self.bombas.value)+"\n")
archivo.write(str(self.equipos_electricos.value)+"\n")
archivo.write(str(self.soportes.value)+"\n")
archivo.write(str(self.construccion.value)+"\n")
archivo.write(str(self.edificios.value)+"\n")
archivo.write(str(self.ingenieria.value)+"\n")
QtWidgets.QDialog.accept(self)
class CostData(QtWidgets.QWidget):
"""Common widget to equipment with cost section
It have property to easy access to properties:
factor: install factor
base: base index (January 1982)
actual: current index
values: a tuple with all properties, (factor, base,actual)
"""
valueChanged = QtCore.pyqtSignal(str, float)
def __init__(self, equipment, parent=None):
"""constructor
equipment: equipment class where the widget have to be put, define
indiceCostos as a index in costIndex"""
super(CostData, self).__init__(parent)
self.indice = equipment.indiceCostos
factor = equipment.kwargs["f_install"]
gridLayout = QtWidgets.QGridLayout(self)
gridLayout.addItem(QtWidgets.QSpacerItem(
20, 20, QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding), 1, 0, 1, 7)
gridLayout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Instalation factor:")), 2, 0, 1, 1)
self.factorInstalacion = Entrada_con_unidades(
float, spinbox=True, decimales=1, step=0.1, width=50, value=factor)
self.factorInstalacion.valueChanged.connect(partial(
self.valueChanged.emit, "f_install"))
gridLayout.addWidget(self.factorInstalacion, 2, 1, 1, 1)
gridLayout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Base index:")), 2, 4, 1, 1)
self.indiceBase = Entrada_con_unidades(
float, readOnly=True, value=indiceBase[self.indice], decimales=1)
gridLayout.addWidget(self.indiceBase, 2, 5, 1, 1)
gridLayout.addWidget(QtWidgets.QLabel(QtWidgets.QApplication.translate(
"pychemqt", "Current index:")), 3, 4, 1, 1)
self.indiceActual = Entrada_con_unidades(
float, readOnly=True, colorReadOnly="white",
value=indiceActual[self.indice], decimales=1)
gridLayout.addWidget(self.indiceActual, 3, 5, 1, 1)
self.costIndex = QtWidgets.QToolButton()
self.costIndex.setFixedSize(QtCore.QSize(24, 24))
self.costIndex.clicked.connect(self.on_costIndex_clicked)
self.costIndex.setText("...")
self.costIndex.setVisible(False)
gridLayout.addWidget(self.costIndex, 3, 5, 1, 1)
gridLayout.addItem(QtWidgets.QSpacerItem(
20, 20, QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding), 4, 0, 1, 7)
def on_costIndex_clicked(self):
"""Show costIndes dialog to show/change"""
dialog = Ui_CostIndex()
if dialog.exec_():
with open(config.conf_dir+"CostIndex.dat", "r") as archivo:
self.indiceActual.setValue(
float(archivo.readlines()[self.indice][:-1]))
self.valueChanged.emit("Current_index", self.indiceActual.value)
def enterEvent(self, event):
self.costIndex.setVisible(True)
def leaveEvent(self, event):
self.costIndex.setVisible(False)
@property
def factor(self):
return self.factorInstalacion.value
@property
def base(self):
return self.indiceBase.value
@property
def actual(self):
return self.indiceActual.value
@property
def values(self):
return self.factorInstalacion.value, self.indiceBase.value,\
self.indiceActual.value
def setFactor(self, value):
self.factorInstalacion.setValue(value)
def setBase(self, value):
self.indiceBase.setValue(value)
def setActual(self, value):
self.indiceActual.setValue(value)
def setValues(self, factor, base, actual):
self.factorInstalacion.setValue(factor)
self.indiceBase.setValue(base)
self.indiceActual.setValue(actual)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
CostIndex = Ui_CostIndex()
CostIndex.show()
sys.exit(app.exec_())
| gpl-3.0 |
CameronLonsdale/sec-tools | letsjusthackshit/lib/python3.5/site-packages/pip/_vendor/progress/__init__.py | 916 | 3023 | # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import division
from collections import deque
from datetime import timedelta
from math import ceil
from sys import stderr
from time import time
__version__ = '1.2'
class Infinite(object):
file = stderr
sma_window = 10
def __init__(self, *args, **kwargs):
self.index = 0
self.start_ts = time()
self._ts = self.start_ts
self._dt = deque(maxlen=self.sma_window)
for key, val in kwargs.items():
setattr(self, key, val)
def __getitem__(self, key):
if key.startswith('_'):
return None
return getattr(self, key, None)
@property
def avg(self):
return sum(self._dt) / len(self._dt) if self._dt else 0
@property
def elapsed(self):
return int(time() - self.start_ts)
@property
def elapsed_td(self):
return timedelta(seconds=self.elapsed)
def update(self):
pass
def start(self):
pass
def finish(self):
pass
def next(self, n=1):
if n > 0:
now = time()
dt = (now - self._ts) / n
self._dt.append(dt)
self._ts = now
self.index = self.index + n
self.update()
def iter(self, it):
for x in it:
yield x
self.next()
self.finish()
class Progress(Infinite):
def __init__(self, *args, **kwargs):
super(Progress, self).__init__(*args, **kwargs)
self.max = kwargs.get('max', 100)
@property
def eta(self):
return int(ceil(self.avg * self.remaining))
@property
def eta_td(self):
return timedelta(seconds=self.eta)
@property
def percent(self):
return self.progress * 100
@property
def progress(self):
return min(1, self.index / self.max)
@property
def remaining(self):
return max(self.max - self.index, 0)
def start(self):
self.update()
def goto(self, index):
incr = index - self.index
self.next(incr)
def iter(self, it):
try:
self.max = len(it)
except TypeError:
pass
for x in it:
yield x
self.next()
self.finish()
| mit |
damocles972/Sick-Beard | cherrypy/lib/auth_digest.py | 35 | 14117 | # This file is part of CherryPy <http://www.cherrypy.org/>
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
__doc__ = """An implementation of the server-side of HTTP Digest Access
Authentication, which is described in RFC 2617.
Example usage, using the built-in get_ha1_dict_plain function which uses a dict
of plaintext passwords as the credentials store:
userpassdict = {'alice' : '4x5istwelve'}
get_ha1 = cherrypy.lib.auth_digest.get_ha1_dict_plain(userpassdict)
digest_auth = {'tools.auth_digest.on': True,
'tools.auth_digest.realm': 'wonderland',
'tools.auth_digest.get_ha1': get_ha1,
'tools.auth_digest.key': 'a565c27146791cfb',
}
app_config = { '/' : digest_auth }
"""
__author__ = 'visteya'
__date__ = 'April 2009'
try:
from hashlib import md5
except ImportError:
# Python 2.4 and earlier
from md5 import new as md5
md5_hex = lambda s: md5(s).hexdigest()
import time
import base64
from urllib2 import parse_http_list, parse_keqv_list
import cherrypy
qop_auth = 'auth'
qop_auth_int = 'auth-int'
valid_qops = (qop_auth, qop_auth_int)
valid_algorithms = ('MD5', 'MD5-sess')
def TRACE(msg):
cherrypy.log(msg, context='TOOLS.AUTH_DIGEST')
# Three helper functions for users of the tool, providing three variants
# of get_ha1() functions for three different kinds of credential stores.
def get_ha1_dict_plain(user_password_dict):
"""Returns a get_ha1 function which obtains a plaintext password from a
dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, with plaintext
passwords, use get_ha1_dict_plain(my_userpass_dict) as the value for the
get_ha1 argument to digest_auth().
"""
def get_ha1(realm, username):
password = user_password_dict.get(username)
if password:
return md5_hex('%s:%s:%s' % (username, realm, password))
return None
return get_ha1
def get_ha1_dict(user_ha1_dict):
"""Returns a get_ha1 function which obtains a HA1 password hash from a
dictionary of the form: {username : HA1}.
If you want a dictionary-based authentication scheme, but with
pre-computed HA1 hashes instead of plain-text passwords, use
get_ha1_dict(my_userha1_dict) as the value for the get_ha1
argument to digest_auth().
"""
def get_ha1(realm, username):
return user_ha1_dict.get(user)
return get_ha1
def get_ha1_file_htdigest(filename):
"""Returns a get_ha1 function which obtains a HA1 password hash from a
flat file with lines of the same format as that produced by the Apache
htdigest utility. For example, for realm 'wonderland', username 'alice',
and password '4x5istwelve', the htdigest line would be:
alice:wonderland:3238cdfe91a8b2ed8e39646921a02d4c
If you want to use an Apache htdigest file as the credentials store,
then use get_ha1_file_htdigest(my_htdigest_file) as the value for the
get_ha1 argument to digest_auth(). It is recommended that the filename
argument be an absolute path, to avoid problems.
"""
def get_ha1(realm, username):
result = None
f = open(filename, 'r')
for line in f:
u, r, ha1 = line.rstrip().split(':')
if u == username and r == realm:
result = ha1
break
f.close()
return result
return get_ha1
def synthesize_nonce(s, key, timestamp=None):
"""Synthesize a nonce value which resists spoofing and can be checked for staleness.
Returns a string suitable as the value for 'nonce' in the www-authenticate header.
Args:
s: a string related to the resource, such as the hostname of the server.
key: a secret string known only to the server.
timestamp: an integer seconds-since-the-epoch timestamp
"""
if timestamp is None:
timestamp = int(time.time())
h = md5_hex('%s:%s:%s' % (timestamp, s, key))
nonce = '%s:%s' % (timestamp, h)
return nonce
def H(s):
"""The hash function H"""
return md5_hex(s)
class HttpDigestAuthorization (object):
"""Class to parse a Digest Authorization header and perform re-calculation
of the digest.
"""
def errmsg(self, s):
return 'Digest Authorization header: %s' % s
def __init__(self, auth_header, http_method, debug=False):
self.http_method = http_method
self.debug = debug
scheme, params = auth_header.split(" ", 1)
self.scheme = scheme.lower()
if self.scheme != 'digest':
raise ValueError('Authorization scheme is not "Digest"')
self.auth_header = auth_header
# make a dict of the params
items = parse_http_list(params)
paramsd = parse_keqv_list(items)
self.realm = paramsd.get('realm')
self.username = paramsd.get('username')
self.nonce = paramsd.get('nonce')
self.uri = paramsd.get('uri')
self.method = paramsd.get('method')
self.response = paramsd.get('response') # the response digest
self.algorithm = paramsd.get('algorithm', 'MD5')
self.cnonce = paramsd.get('cnonce')
self.opaque = paramsd.get('opaque')
self.qop = paramsd.get('qop') # qop
self.nc = paramsd.get('nc') # nonce count
# perform some correctness checks
if self.algorithm not in valid_algorithms:
raise ValueError(self.errmsg("Unsupported value for algorithm: '%s'" % self.algorithm))
has_reqd = self.username and \
self.realm and \
self.nonce and \
self.uri and \
self.response
if not has_reqd:
raise ValueError(self.errmsg("Not all required parameters are present."))
if self.qop:
if self.qop not in valid_qops:
raise ValueError(self.errmsg("Unsupported value for qop: '%s'" % self.qop))
if not (self.cnonce and self.nc):
raise ValueError(self.errmsg("If qop is sent then cnonce and nc MUST be present"))
else:
if self.cnonce or self.nc:
raise ValueError(self.errmsg("If qop is not sent, neither cnonce nor nc can be present"))
def __str__(self):
return 'authorization : %s' % self.auth_header
def validate_nonce(self, s, key):
"""Validate the nonce.
Returns True if nonce was generated by synthesize_nonce() and the timestamp
is not spoofed, else returns False.
Args:
s: a string related to the resource, such as the hostname of the server.
key: a secret string known only to the server.
Both s and key must be the same values which were used to synthesize the nonce
we are trying to validate.
"""
try:
timestamp, hashpart = self.nonce.split(':', 1)
s_timestamp, s_hashpart = synthesize_nonce(s, key, timestamp).split(':', 1)
is_valid = s_hashpart == hashpart
if self.debug:
TRACE('validate_nonce: %s' % is_valid)
return is_valid
except ValueError: # split() error
pass
return False
def is_nonce_stale(self, max_age_seconds=600):
"""Returns True if a validated nonce is stale. The nonce contains a
timestamp in plaintext and also a secure hash of the timestamp. You should
first validate the nonce to ensure the plaintext timestamp is not spoofed.
"""
try:
timestamp, hashpart = self.nonce.split(':', 1)
if int(timestamp) + max_age_seconds > int(time.time()):
return False
except ValueError: # int() error
pass
if self.debug:
TRACE("nonce is stale")
return True
def HA2(self, entity_body=''):
"""Returns the H(A2) string. See RFC 2617 3.2.2.3."""
# RFC 2617 3.2.2.3
# If the "qop" directive's value is "auth" or is unspecified, then A2 is:
# A2 = method ":" digest-uri-value
#
# If the "qop" value is "auth-int", then A2 is:
# A2 = method ":" digest-uri-value ":" H(entity-body)
if self.qop is None or self.qop == "auth":
a2 = '%s:%s' % (self.http_method, self.uri)
elif self.qop == "auth-int":
a2 = "%s:%s:%s" % (self.http_method, self.uri, H(entity_body))
else:
# in theory, this should never happen, since I validate qop in __init__()
raise ValueError(self.errmsg("Unrecognized value for qop!"))
return H(a2)
def request_digest(self, ha1, entity_body=''):
"""Calculates the Request-Digest. See RFC 2617 3.2.2.1.
Arguments:
ha1 : the HA1 string obtained from the credentials store.
entity_body : if 'qop' is set to 'auth-int', then A2 includes a hash
of the "entity body". The entity body is the part of the
message which follows the HTTP headers. See RFC 2617 section
4.3. This refers to the entity the user agent sent in the request which
has the Authorization header. Typically GET requests don't have an entity,
and POST requests do.
"""
ha2 = self.HA2(entity_body)
# Request-Digest -- RFC 2617 3.2.2.1
if self.qop:
req = "%s:%s:%s:%s:%s" % (self.nonce, self.nc, self.cnonce, self.qop, ha2)
else:
req = "%s:%s" % (self.nonce, ha2)
# RFC 2617 3.2.2.2
#
# If the "algorithm" directive's value is "MD5" or is unspecified, then A1 is:
# A1 = unq(username-value) ":" unq(realm-value) ":" passwd
#
# If the "algorithm" directive's value is "MD5-sess", then A1 is
# calculated only once - on the first request by the client following
# receipt of a WWW-Authenticate challenge from the server.
# A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
# ":" unq(nonce-value) ":" unq(cnonce-value)
if self.algorithm == 'MD5-sess':
ha1 = H('%s:%s:%s' % (ha1, self.nonce, self.cnonce))
digest = H('%s:%s' % (ha1, req))
return digest
def www_authenticate(realm, key, algorithm='MD5', nonce=None, qop=qop_auth, stale=False):
"""Constructs a WWW-Authenticate header for Digest authentication."""
if qop not in valid_qops:
raise ValueError("Unsupported value for qop: '%s'" % qop)
if algorithm not in valid_algorithms:
raise ValueError("Unsupported value for algorithm: '%s'" % algorithm)
if nonce is None:
nonce = synthesize_nonce(realm, key)
s = 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"' % (
realm, nonce, algorithm, qop)
if stale:
s += ', stale="true"'
return s
def digest_auth(realm, get_ha1, key, debug=False):
"""digest_auth is a CherryPy tool which hooks at before_handler to perform
HTTP Digest Access Authentication, as specified in RFC 2617.
If the request has an 'authorization' header with a 'Digest' scheme, this
tool authenticates the credentials supplied in that header. If
the request has no 'authorization' header, or if it does but the scheme is
not "Digest", or if authentication fails, the tool sends a 401 response with
a 'WWW-Authenticate' Digest header.
Arguments:
realm: a string containing the authentication realm.
get_ha1: a callable which looks up a username in a credentials store
and returns the HA1 string, which is defined in the RFC to be
MD5(username : realm : password). The function's signature is:
get_ha1(realm, username)
where username is obtained from the request's 'authorization' header.
If username is not found in the credentials store, get_ha1() returns
None.
key: a secret string known only to the server, used in the synthesis of nonces.
"""
request = cherrypy.serving.request
auth_header = request.headers.get('authorization')
nonce_is_stale = False
if auth_header is not None:
try:
auth = HttpDigestAuthorization(auth_header, request.method, debug=debug)
except ValueError, e:
raise cherrypy.HTTPError(400, 'Bad Request: %s' % e)
if debug:
TRACE(str(auth))
if auth.validate_nonce(realm, key):
ha1 = get_ha1(realm, auth.username)
if ha1 is not None:
# note that for request.body to be available we need to hook in at
# before_handler, not on_start_resource like 3.1.x digest_auth does.
digest = auth.request_digest(ha1, entity_body=request.body)
if digest == auth.response: # authenticated
if debug:
TRACE("digest matches auth.response")
# Now check if nonce is stale.
# The choice of ten minutes' lifetime for nonce is somewhat arbitrary
nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600)
if not nonce_is_stale:
request.login = auth.username
if debug:
TRACE("authentication of %s successful" % auth.username)
return
# Respond with 401 status and a WWW-Authenticate header
header = www_authenticate(realm, key, stale=nonce_is_stale)
if debug:
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
raise cherrypy.HTTPError(401, "You are not authorized to access that resource")
| gpl-3.0 |
jagill/treeano | treeano/sandbox/nodes/irregular_length.py | 1 | 4325 | import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
import treeano.theano_extensions.irregular_length as il
@treeano.register_node("ungroup_irregular_length_tensors")
class UngroupIrregularLengthTensorsNode(treeano.NodeImpl):
hyperparameter_names = ("lengths_reference",)
input_keys = ("default", "lengths")
def init_long_range_dependencies(self, network):
network.take_output_from(
network.find_hyperparameter(["lengths_reference"]),
to_key="lengths")
def compute_output(self, network, in_vw, lengths_vw):
network.create_vw(
"default",
variable=il.ungroup_irregular_length_tensors(in_vw.variable,
lengths_vw.variable),
shape=(None, None) + in_vw.shape[1:],
tags={"output"},
)
@treeano.register_node("irregular_length_mean")
class IrregularLengthMeanNode(treeano.NodeImpl):
"""
meant to take in input from UngroupIrregularLengthTensorsNode
"""
hyperparameter_names = ("lengths_reference",)
input_keys = ("default", "lengths")
def init_long_range_dependencies(self, network):
network.take_output_from(
network.find_hyperparameter(["lengths_reference"]),
to_key="lengths")
def compute_output(self, network, in_vw, lengths_vw):
lengths = lengths_vw.variable.dimshuffle([0] + ["x"] * (in_vw.ndim - 2))
network.create_vw(
"default",
variable=in_vw.variable.sum(axis=1) / lengths,
# drop axis 1
shape=in_vw.shape[0:1] + in_vw.shape[2:],
tags={"output"},
)
@treeano.register_node("_irregular_length_attention_softmax")
class _IrregularLengthAttentionSoftmaxNode(treeano.NodeImpl):
"""
performs a softmax over irregular length, but takes into account
the padding created by ungrouping by removing the contribution
of those 0's to the denominator of a softmax
"""
hyperparameter_names = ("lengths_reference",)
input_keys = ("default", "lengths")
def init_long_range_dependencies(self, network):
network.take_output_from(
network.find_hyperparameter(["lengths_reference"]),
to_key="lengths")
def compute_output(self, network, in_vw, lengths_vw):
x = in_vw.variable
x_max = x.max(axis=1, keepdims=True)
e_x = T.exp(x - x_max)
e_x_max_inv = T.exp(-x_max)
lengths = lengths_vw.variable
max_len = lengths.max()
num_zeros = max_len - lengths
num_zeros = num_zeros.dimshuffle([0, "x", "x"])
denom = e_x.sum(axis=1, keepdims=True) - num_zeros * e_x_max_inv
out_var = e_x / denom
network.create_vw(
"default",
variable=out_var,
shape=in_vw.shape,
tags={"output"},
)
def irregular_length_attention_node(name,
lengths_reference,
num_units,
output_units=None):
"""
NOTE: if output_units is not None, this should be the number
of input units
"""
value_branch = UngroupIrregularLengthTensorsNode(
name + "_ungroup_values",
lengths_reference=lengths_reference)
fc2_units = 1 if output_units is None else output_units
attention_nodes = [
tn.DenseNode(name + "_fc1", num_units=num_units),
tn.ScaledTanhNode(name + "_tanh"),
tn.DenseNode(name + "_fc2", num_units=fc2_units),
UngroupIrregularLengthTensorsNode(
name + "_ungroup_attention",
lengths_reference=lengths_reference),
_IrregularLengthAttentionSoftmaxNode(
name + "_softmax",
lengths_reference=lengths_reference),
]
if output_units is None:
attention_nodes += [
tn.AddBroadcastNode(name + "_bcast", axes=(2,)),
]
attention_branch = tn.SequentialNode(
name + "_attention",
attention_nodes)
return tn.SequentialNode(
name,
[tn.ElementwiseProductNode(
name + "_prod",
[value_branch,
attention_branch]),
tn.SumNode(name + "_sum", axis=1)])
| apache-2.0 |
wrigri/libcloud | libcloud/test/common/test_aws.py | 28 | 13462 | # 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 unittest
from datetime import datetime
import mock
from libcloud.common.aws import AWSRequestSignerAlgorithmV4
from libcloud.common.aws import SignedAWSConnection
from libcloud.common.aws import UNSIGNED_PAYLOAD
from libcloud.test import LibcloudTestCase
class EC2MockDriver(object):
region_name = 'my_region'
class AWSRequestSignerAlgorithmV4TestCase(LibcloudTestCase):
def setUp(self):
SignedAWSConnection.driver = EC2MockDriver()
SignedAWSConnection.service_name = 'my_service'
SignedAWSConnection.version = '2013-10-15'
self.connection = SignedAWSConnection('my_key', 'my_secret')
self.signer = AWSRequestSignerAlgorithmV4(access_key='my_key',
access_secret='my_secret',
version='2013-10-15',
connection=self.connection)
SignedAWSConnection.action = '/my_action/'
SignedAWSConnection.driver = EC2MockDriver()
self.now = datetime(2015, 3, 4, hour=17, minute=34, second=52)
def test_v4_signature(self):
params = {
'Action': 'DescribeInstances',
'Version': '2013-10-15'
}
headers = {
'Host': 'ec2.eu-west-1.amazonaws.com',
'Accept-Encoding': 'gzip,deflate',
'X-AMZ-Date': '20150304T173452Z',
'User-Agent': 'libcloud/0.17.0 (Amazon EC2 (eu-central-1)) '
}
dt = self.now
sig = self.signer._get_authorization_v4_header(params=params,
headers=headers,
dt=dt,
method='GET',
path='/my_action/')
self.assertEqual(sig, 'AWS4-HMAC-SHA256 '
'Credential=my_key/20150304/my_region/my_service/aws4_request, '
'SignedHeaders=accept-encoding;host;user-agent;x-amz-date, '
'Signature=f9868f8414b3c3f856c7955019cc1691265541f5162b9b772d26044280d39bd3')
def test_v4_signature_contains_user_id(self):
sig = self.signer._get_authorization_v4_header(params={}, headers={},
dt=self.now)
self.assertIn('Credential=my_key/', sig)
def test_v4_signature_contains_credential_scope(self):
with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_credential_scope') as mock_get_creds:
mock_get_creds.return_value = 'my_credential_scope'
sig = self.signer._get_authorization_v4_header(params={}, headers={}, dt=self.now)
self.assertIn('Credential=my_key/my_credential_scope, ', sig)
def test_v4_signature_contains_signed_headers(self):
with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_signed_headers') as mock_get_headers:
mock_get_headers.return_value = 'my_signed_headers'
sig = self.signer._get_authorization_v4_header({}, {}, self.now,
method='GET',
path='/')
self.assertIn('SignedHeaders=my_signed_headers, ', sig)
def test_v4_signature_contains_signature(self):
with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_signature') as mock_get_signature:
mock_get_signature.return_value = 'my_signature'
sig = self.signer._get_authorization_v4_header({}, {}, self.now)
self.assertIn('Signature=my_signature', sig)
def test_get_signature_(self):
def _sign(key, msg, hex=False):
if hex:
return 'H|%s|%s' % (key, msg)
else:
return '%s|%s' % (key, msg)
with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_key_to_sign_with') as mock_get_key:
with mock.patch('libcloud.common.aws.AWSRequestSignerAlgorithmV4._get_string_to_sign') as mock_get_string:
with mock.patch('libcloud.common.aws._sign', new=_sign):
mock_get_key.return_value = 'my_signing_key'
mock_get_string.return_value = 'my_string_to_sign'
sig = self.signer._get_signature({}, {}, self.now,
method='GET', path='/', data=None)
self.assertEqual(sig, 'H|my_signing_key|my_string_to_sign')
def test_get_string_to_sign(self):
with mock.patch('hashlib.sha256') as mock_sha256:
mock_sha256.return_value.hexdigest.return_value = 'chksum_of_canonical_request'
to_sign = self.signer._get_string_to_sign({}, {}, self.now,
method='GET', path='/', data=None)
self.assertEqual(to_sign,
'AWS4-HMAC-SHA256\n'
'20150304T173452Z\n'
'20150304/my_region/my_service/aws4_request\n'
'chksum_of_canonical_request')
def test_get_key_to_sign_with(self):
def _sign(key, msg, hex=False):
return '%s|%s' % (key, msg)
with mock.patch('libcloud.common.aws._sign', new=_sign):
key = self.signer._get_key_to_sign_with(self.now)
self.assertEqual(key, 'AWS4my_secret|20150304|my_region|my_service|aws4_request')
def test_get_signed_headers_contains_all_headers_lowercased(self):
headers = {'Content-Type': 'text/plain', 'Host': 'my_host', 'X-Special-Header': ''}
signed_headers = self.signer._get_signed_headers(headers)
self.assertIn('content-type', signed_headers)
self.assertIn('host', signed_headers)
self.assertIn('x-special-header', signed_headers)
def test_get_signed_headers_concats_headers_sorted_lexically(self):
headers = {'Host': 'my_host', 'X-Special-Header': '', '1St-Header': '2', 'Content-Type': 'text/plain'}
signed_headers = self.signer._get_signed_headers(headers)
self.assertEqual(signed_headers, '1st-header;content-type;host;x-special-header')
def test_get_credential_scope(self):
scope = self.signer._get_credential_scope(self.now)
self.assertEqual(scope, '20150304/my_region/my_service/aws4_request')
def test_get_canonical_headers_joins_all_headers(self):
headers = {
'accept-encoding': 'gzip,deflate',
'host': 'my_host',
}
self.assertEqual(self.signer._get_canonical_headers(headers),
'accept-encoding:gzip,deflate\n'
'host:my_host\n')
def test_get_canonical_headers_sorts_headers_lexically(self):
headers = {
'accept-encoding': 'gzip,deflate',
'host': 'my_host',
'1st-header': '2',
'x-amz-date': '20150304T173452Z',
'user-agent': 'my-ua'
}
self.assertEqual(self.signer._get_canonical_headers(headers),
'1st-header:2\n'
'accept-encoding:gzip,deflate\n'
'host:my_host\n'
'user-agent:my-ua\n'
'x-amz-date:20150304T173452Z\n')
def test_get_canonical_headers_lowercases_headers_names(self):
headers = {
'Accept-Encoding': 'GZIP,DEFLATE',
'User-Agent': 'My-UA'
}
self.assertEqual(self.signer._get_canonical_headers(headers),
'accept-encoding:GZIP,DEFLATE\n'
'user-agent:My-UA\n')
def test_get_canonical_headers_trims_header_values(self):
# TODO: according to AWS spec (and RFC 2616 Section 4.2.) excess whitespace
# from inside non-quoted strings should be stripped. Now we only strip the
# start and end of the string. See
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
headers = {
'accept-encoding': ' gzip,deflate',
'user-agent': 'libcloud/0.17.0 '
}
self.assertEqual(self.signer._get_canonical_headers(headers),
'accept-encoding:gzip,deflate\n'
'user-agent:libcloud/0.17.0\n')
def test_get_request_params_joins_params_sorted_lexically(self):
self.assertEqual(self.signer._get_request_params({
'Action': 'DescribeInstances',
'Filter.1.Name': 'state',
'Version': '2013-10-15'
}),
'Action=DescribeInstances&Filter.1.Name=state&Version=2013-10-15')
def test_get_canonical_headers_allow_numeric_header_value(self):
headers = {
'Accept-Encoding': 'gzip,deflate',
'Content-Length': 314
}
self.assertEqual(self.signer._get_canonical_headers(headers),
'accept-encoding:gzip,deflate\n'
'content-length:314\n')
def test_get_request_params_allows_integers_as_value(self):
self.assertEqual(self.signer._get_request_params({'Action': 'DescribeInstances', 'Port': 22}),
'Action=DescribeInstances&Port=22')
def test_get_request_params_urlquotes_params_keys(self):
self.assertEqual(self.signer._get_request_params({'Action+Reaction': 'DescribeInstances'}),
'Action%2BReaction=DescribeInstances')
def test_get_request_params_urlquotes_params_values(self):
self.assertEqual(self.signer._get_request_params({
'Action': 'DescribeInstances&Addresses',
'Port-Range': '2000 3000'
}),
'Action=DescribeInstances%26Addresses&Port-Range=2000%203000')
def test_get_request_params_urlquotes_params_values_allows_safe_chars_in_value(self):
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
self.assertEqual('Action=a~b.c_d-e',
self.signer._get_request_params({'Action': 'a~b.c_d-e'}))
def test_get_payload_hash_returns_digest_of_empty_string_for_GET_requests(self):
SignedAWSConnection.method = 'GET'
self.assertEqual(self.signer._get_payload_hash(method='GET'),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
def test_get_payload_hash_with_data_for_PUT_requests(self):
SignedAWSConnection.method = 'PUT'
self.assertEqual(self.signer._get_payload_hash(method='PUT', data='DUMMY'),
'ceec12762e66397b56dad64fd270bb3d694c78fb9cd665354383c0626dbab013')
def test_get_payload_hash_with_empty_data_for_POST_requests(self):
SignedAWSConnection.method = 'POST'
self.assertEqual(self.signer._get_payload_hash(method='POST'),
UNSIGNED_PAYLOAD)
def test_get_canonical_request(self):
req = self.signer._get_canonical_request(
{'Action': 'DescribeInstances', 'Version': '2013-10-15'},
{'Accept-Encoding': 'gzip,deflate', 'User-Agent': 'My-UA'},
method='GET',
path='/my_action/',
data=None
)
self.assertEqual(req, 'GET\n'
'/my_action/\n'
'Action=DescribeInstances&Version=2013-10-15\n'
'accept-encoding:gzip,deflate\n'
'user-agent:My-UA\n'
'\n'
'accept-encoding;user-agent\n'
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
def test_post_canonical_request(self):
req = self.signer._get_canonical_request(
{'Action': 'DescribeInstances', 'Version': '2013-10-15'},
{'Accept-Encoding': 'gzip,deflate', 'User-Agent': 'My-UA'},
method='POST',
path='/my_action/',
data='{}'
)
self.assertEqual(req, 'POST\n'
'/my_action/\n'
'Action=DescribeInstances&Version=2013-10-15\n'
'accept-encoding:gzip,deflate\n'
'user-agent:My-UA\n'
'\n'
'accept-encoding;user-agent\n'
'44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a')
if __name__ == '__main__':
sys.exit(unittest.main())
| apache-2.0 |
gusai-francelabs/datafari | windows/python/Lib/site-packages/pip/_vendor/distlib/wheel.py | 202 | 39035 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2014 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import base64
import codecs
import datetime
import distutils.util
from email import message_from_file
import hashlib
import imp
import json
import logging
import os
import posixpath
import re
import shutil
import sys
import tempfile
import zipfile
from . import __version__, DistlibException
from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
from .database import InstalledDistribution
from .metadata import Metadata, METADATA_FILENAME
from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,
cached_property, get_cache_base, read_exports, tempdir)
from .version import NormalizedVersion, UnsupportedVersionError
logger = logging.getLogger(__name__)
cache = None # created when needed
if hasattr(sys, 'pypy_version_info'):
IMP_PREFIX = 'pp'
elif sys.platform.startswith('java'):
IMP_PREFIX = 'jy'
elif sys.platform == 'cli':
IMP_PREFIX = 'ip'
else:
IMP_PREFIX = 'cp'
VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
if not VER_SUFFIX: # pragma: no cover
VER_SUFFIX = '%s%s' % sys.version_info[:2]
PYVER = 'py' + VER_SUFFIX
IMPVER = IMP_PREFIX + VER_SUFFIX
ARCH = distutils.util.get_platform().replace('-', '_').replace('.', '_')
ABI = sysconfig.get_config_var('SOABI')
if ABI and ABI.startswith('cpython-'):
ABI = ABI.replace('cpython-', 'cp')
else:
def _derive_abi():
parts = ['cp', VER_SUFFIX]
if sysconfig.get_config_var('Py_DEBUG'):
parts.append('d')
if sysconfig.get_config_var('WITH_PYMALLOC'):
parts.append('m')
if sysconfig.get_config_var('Py_UNICODE_SIZE') == 4:
parts.append('u')
return ''.join(parts)
ABI = _derive_abi()
del _derive_abi
FILENAME_RE = re.compile(r'''
(?P<nm>[^-]+)
-(?P<vn>\d+[^-]*)
(-(?P<bn>\d+[^-]*))?
-(?P<py>\w+\d+(\.\w+\d+)*)
-(?P<bi>\w+)
-(?P<ar>\w+)
\.whl$
''', re.IGNORECASE | re.VERBOSE)
NAME_VERSION_RE = re.compile(r'''
(?P<nm>[^-]+)
-(?P<vn>\d+[^-]*)
(-(?P<bn>\d+[^-]*))?$
''', re.IGNORECASE | re.VERBOSE)
SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
SHEBANG_PYTHON = b'#!python'
SHEBANG_PYTHONW = b'#!pythonw'
if os.sep == '/':
to_posix = lambda o: o
else:
to_posix = lambda o: o.replace(os.sep, '/')
class Mounter(object):
def __init__(self):
self.impure_wheels = {}
self.libs = {}
def add(self, pathname, extensions):
self.impure_wheels[pathname] = extensions
self.libs.update(extensions)
def remove(self, pathname):
extensions = self.impure_wheels.pop(pathname)
for k, v in extensions:
if k in self.libs:
del self.libs[k]
def find_module(self, fullname, path=None):
if fullname in self.libs:
result = self
else:
result = None
return result
def load_module(self, fullname):
if fullname in sys.modules:
result = sys.modules[fullname]
else:
if fullname not in self.libs:
raise ImportError('unable to find extension for %s' % fullname)
result = imp.load_dynamic(fullname, self.libs[fullname])
result.__loader__ = self
parts = fullname.rsplit('.', 1)
if len(parts) > 1:
result.__package__ = parts[0]
return result
_hook = Mounter()
class Wheel(object):
"""
Class to build and install from Wheel files (PEP 427).
"""
wheel_version = (1, 1)
hash_kind = 'sha256'
def __init__(self, filename=None, sign=False, verify=False):
"""
Initialise an instance using a (valid) filename.
"""
self.sign = sign
self.should_verify = verify
self.buildver = ''
self.pyver = [PYVER]
self.abi = ['none']
self.arch = ['any']
self.dirname = os.getcwd()
if filename is None:
self.name = 'dummy'
self.version = '0.1'
self._filename = self.filename
else:
m = NAME_VERSION_RE.match(filename)
if m:
info = m.groupdict('')
self.name = info['nm']
# Reinstate the local version separator
self.version = info['vn'].replace('_', '-')
self.buildver = info['bn']
self._filename = self.filename
else:
dirname, filename = os.path.split(filename)
m = FILENAME_RE.match(filename)
if not m:
raise DistlibException('Invalid name or '
'filename: %r' % filename)
if dirname:
self.dirname = os.path.abspath(dirname)
self._filename = filename
info = m.groupdict('')
self.name = info['nm']
self.version = info['vn']
self.buildver = info['bn']
self.pyver = info['py'].split('.')
self.abi = info['bi'].split('.')
self.arch = info['ar'].split('.')
@property
def filename(self):
"""
Build and return a filename from the various components.
"""
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arch)
# replace - with _ as a local version separator
version = self.version.replace('-', '_')
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
pyver, abi, arch)
@property
def exists(self):
path = os.path.join(self.dirname, self.filename)
return os.path.isfile(path)
@property
def tags(self):
for pyver in self.pyver:
for abi in self.abi:
for arch in self.arch:
yield pyver, abi, arch
@cached_property
def metadata(self):
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
wrapper = codecs.getreader('utf-8')
with ZipFile(pathname, 'r') as zf:
wheel_metadata = self.get_wheel_metadata(zf)
wv = wheel_metadata['Wheel-Version'].split('.', 1)
file_version = tuple([int(i) for i in wv])
if file_version < (1, 1):
fn = 'METADATA'
else:
fn = METADATA_FILENAME
try:
metadata_filename = posixpath.join(info_dir, fn)
with zf.open(metadata_filename) as bf:
wf = wrapper(bf)
result = Metadata(fileobj=wf)
except KeyError:
raise ValueError('Invalid wheel, because %s is '
'missing' % fn)
return result
def get_wheel_metadata(self, zf):
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
metadata_filename = posixpath.join(info_dir, 'WHEEL')
with zf.open(metadata_filename) as bf:
wf = codecs.getreader('utf-8')(bf)
message = message_from_file(wf)
return dict(message)
@cached_property
def info(self):
pathname = os.path.join(self.dirname, self.filename)
with ZipFile(pathname, 'r') as zf:
result = self.get_wheel_metadata(zf)
return result
def process_shebang(self, data):
m = SHEBANG_RE.match(data)
if m:
end = m.end()
shebang, data_after_shebang = data[:end], data[end:]
# Preserve any arguments after the interpreter
if b'pythonw' in shebang.lower():
shebang_python = SHEBANG_PYTHONW
else:
shebang_python = SHEBANG_PYTHON
m = SHEBANG_DETAIL_RE.match(shebang)
if m:
args = b' ' + m.groups()[-1]
else:
args = b''
shebang = shebang_python + args
data = shebang + data_after_shebang
else:
cr = data.find(b'\r')
lf = data.find(b'\n')
if cr < 0 or cr > lf:
term = b'\n'
else:
if data[cr:cr + 2] == b'\r\n':
term = b'\r\n'
else:
term = b'\r'
data = SHEBANG_PYTHON + term + data
return data
def get_hash(self, data, hash_kind=None):
if hash_kind is None:
hash_kind = self.hash_kind
try:
hasher = getattr(hashlib, hash_kind)
except AttributeError:
raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
result = hasher(data).digest()
result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
return hash_kind, result
def write_record(self, records, record_path, base):
with CSVWriter(record_path) as writer:
for row in records:
writer.writerow(row)
p = to_posix(os.path.relpath(record_path, base))
writer.writerow((p, '', ''))
def write_records(self, info, libdir, archive_paths):
records = []
distinfo, info_dir = info
hasher = getattr(hashlib, self.hash_kind)
for ap, p in archive_paths:
with open(p, 'rb') as f:
data = f.read()
digest = '%s=%s' % self.get_hash(data)
size = os.path.getsize(p)
records.append((ap, digest, size))
p = os.path.join(distinfo, 'RECORD')
self.write_record(records, p, libdir)
ap = to_posix(os.path.join(info_dir, 'RECORD'))
archive_paths.append((ap, p))
def build_zip(self, pathname, archive_paths):
with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
for ap, p in archive_paths:
logger.debug('Wrote %s to %s in wheel', p, ap)
zf.write(p, ap)
def build(self, paths, tags=None, wheel_version=None):
"""
Build a wheel from files in specified paths, and use any specified tags
when determining the name of the wheel.
"""
if tags is None:
tags = {}
libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
if libkey == 'platlib':
is_pure = 'false'
default_pyver = [IMPVER]
default_abi = [ABI]
default_arch = [ARCH]
else:
is_pure = 'true'
default_pyver = [PYVER]
default_abi = ['none']
default_arch = ['any']
self.pyver = tags.get('pyver', default_pyver)
self.abi = tags.get('abi', default_abi)
self.arch = tags.get('arch', default_arch)
libdir = paths[libkey]
name_ver = '%s-%s' % (self.name, self.version)
data_dir = '%s.data' % name_ver
info_dir = '%s.dist-info' % name_ver
archive_paths = []
# First, stuff which is not in site-packages
for key in ('data', 'headers', 'scripts'):
if key not in paths:
continue
path = paths[key]
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for fn in files:
p = fsdecode(os.path.join(root, fn))
rp = os.path.relpath(p, path)
ap = to_posix(os.path.join(data_dir, key, rp))
archive_paths.append((ap, p))
if key == 'scripts' and not p.endswith('.exe'):
with open(p, 'rb') as f:
data = f.read()
data = self.process_shebang(data)
with open(p, 'wb') as f:
f.write(data)
# Now, stuff which is in site-packages, other than the
# distinfo stuff.
path = libdir
distinfo = None
for root, dirs, files in os.walk(path):
if root == path:
# At the top level only, save distinfo for later
# and skip it for now
for i, dn in enumerate(dirs):
dn = fsdecode(dn)
if dn.endswith('.dist-info'):
distinfo = os.path.join(root, dn)
del dirs[i]
break
assert distinfo, '.dist-info directory expected, not found'
for fn in files:
# comment out next suite to leave .pyc files in
if fsdecode(fn).endswith(('.pyc', '.pyo')):
continue
p = os.path.join(root, fn)
rp = to_posix(os.path.relpath(p, path))
archive_paths.append((rp, p))
# Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
files = os.listdir(distinfo)
for fn in files:
if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
p = fsdecode(os.path.join(distinfo, fn))
ap = to_posix(os.path.join(info_dir, fn))
archive_paths.append((ap, p))
wheel_metadata = [
'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
'Generator: distlib %s' % __version__,
'Root-Is-Purelib: %s' % is_pure,
]
for pyver, abi, arch in self.tags:
wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
p = os.path.join(distinfo, 'WHEEL')
with open(p, 'w') as f:
f.write('\n'.join(wheel_metadata))
ap = to_posix(os.path.join(info_dir, 'WHEEL'))
archive_paths.append((ap, p))
# Now, at last, RECORD.
# Paths in here are archive paths - nothing else makes sense.
self.write_records((distinfo, info_dir), libdir, archive_paths)
# Now, ready to build the zip file
pathname = os.path.join(self.dirname, self.filename)
self.build_zip(pathname, archive_paths)
return pathname
def install(self, paths, maker, **kwargs):
"""
Install a wheel to the specified paths. If kwarg ``warner`` is
specified, it should be a callable, which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file, if there is a discrepancy in the versions.
This can be used to issue any warnings to raise any exceptions.
If kwarg ``lib_only`` is True, only the purelib/platlib files are
installed, and the headers, scripts, data and dist-info metadata are
not written.
The return value is a :class:`InstalledDistribution` instance unless
``options.lib_only`` is True, in which case the return value is ``None``.
"""
dry_run = maker.dry_run
warner = kwargs.get('warner')
lib_only = kwargs.get('lib_only', False)
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
data_dir = '%s.data' % name_ver
info_dir = '%s.dist-info' % name_ver
metadata_name = posixpath.join(info_dir, METADATA_FILENAME)
wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
record_name = posixpath.join(info_dir, 'RECORD')
wrapper = codecs.getreader('utf-8')
with ZipFile(pathname, 'r') as zf:
with zf.open(wheel_metadata_name) as bwf:
wf = wrapper(bwf)
message = message_from_file(wf)
wv = message['Wheel-Version'].split('.', 1)
file_version = tuple([int(i) for i in wv])
if (file_version != self.wheel_version) and warner:
warner(self.wheel_version, file_version)
if message['Root-Is-Purelib'] == 'true':
libdir = paths['purelib']
else:
libdir = paths['platlib']
records = {}
with zf.open(record_name) as bf:
with CSVReader(stream=bf) as reader:
for row in reader:
p = row[0]
records[p] = row
data_pfx = posixpath.join(data_dir, '')
info_pfx = posixpath.join(info_dir, '')
script_pfx = posixpath.join(data_dir, 'scripts', '')
# make a new instance rather than a copy of maker's,
# as we mutate it
fileop = FileOperator(dry_run=dry_run)
fileop.record = True # so we can rollback if needed
bc = not sys.dont_write_bytecode # Double negatives. Lovely!
outfiles = [] # for RECORD writing
# for script copying/shebang processing
workdir = tempfile.mkdtemp()
# set target dir later
# we default add_launchers to False, as the
# Python Launcher should be used instead
maker.source_dir = workdir
maker.target_dir = None
try:
for zinfo in zf.infolist():
arcname = zinfo.filename
if isinstance(arcname, text_type):
u_arcname = arcname
else:
u_arcname = arcname.decode('utf-8')
# The signature file won't be in RECORD,
# and we don't currently don't do anything with it
if u_arcname.endswith('/RECORD.jws'):
continue
row = records[u_arcname]
if row[2] and str(zinfo.file_size) != row[2]:
raise DistlibException('size mismatch for '
'%s' % u_arcname)
if row[1]:
kind, value = row[1].split('=', 1)
with zf.open(arcname) as bf:
data = bf.read()
_, digest = self.get_hash(data, kind)
if digest != value:
raise DistlibException('digest mismatch for '
'%s' % arcname)
if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
logger.debug('lib_only: skipping %s', u_arcname)
continue
is_script = (u_arcname.startswith(script_pfx)
and not u_arcname.endswith('.exe'))
if u_arcname.startswith(data_pfx):
_, where, rp = u_arcname.split('/', 2)
outfile = os.path.join(paths[where], convert_path(rp))
else:
# meant for site-packages.
if u_arcname in (wheel_metadata_name, record_name):
continue
outfile = os.path.join(libdir, convert_path(u_arcname))
if not is_script:
with zf.open(arcname) as bf:
fileop.copy_stream(bf, outfile)
outfiles.append(outfile)
# Double check the digest of the written file
if not dry_run and row[1]:
with open(outfile, 'rb') as bf:
data = bf.read()
_, newdigest = self.get_hash(data, kind)
if newdigest != digest:
raise DistlibException('digest mismatch '
'on write for '
'%s' % outfile)
if bc and outfile.endswith('.py'):
try:
pyc = fileop.byte_compile(outfile)
outfiles.append(pyc)
except Exception:
# Don't give up if byte-compilation fails,
# but log it and perhaps warn the user
logger.warning('Byte-compilation failed',
exc_info=True)
else:
fn = os.path.basename(convert_path(arcname))
workname = os.path.join(workdir, fn)
with zf.open(arcname) as bf:
fileop.copy_stream(bf, workname)
dn, fn = os.path.split(outfile)
maker.target_dir = dn
filenames = maker.make(fn)
fileop.set_executable_mode(filenames)
outfiles.extend(filenames)
if lib_only:
logger.debug('lib_only: returning None')
dist = None
else:
# Generate scripts
# Try to get pydist.json so we can see if there are
# any commands to generate. If this fails (e.g. because
# of a legacy wheel), log a warning but don't give up.
commands = None
file_version = self.info['Wheel-Version']
if file_version == '1.0':
# Use legacy info
ep = posixpath.join(info_dir, 'entry_points.txt')
try:
with zf.open(ep) as bwf:
epdata = read_exports(bwf)
commands = {}
for key in ('console', 'gui'):
k = '%s_scripts' % key
if k in epdata:
commands['wrap_%s' % key] = d = {}
for v in epdata[k].values():
s = '%s:%s' % (v.prefix, v.suffix)
if v.flags:
s += ' %s' % v.flags
d[v.name] = s
except Exception:
logger.warning('Unable to read legacy script '
'metadata, so cannot generate '
'scripts')
else:
try:
with zf.open(metadata_name) as bwf:
wf = wrapper(bwf)
commands = json.load(wf).get('extensions')
if commands:
commands = commands.get('python.commands')
except Exception:
logger.warning('Unable to read JSON metadata, so '
'cannot generate scripts')
if commands:
console_scripts = commands.get('wrap_console', {})
gui_scripts = commands.get('wrap_gui', {})
if console_scripts or gui_scripts:
script_dir = paths.get('scripts', '')
if not os.path.isdir(script_dir):
raise ValueError('Valid script path not '
'specified')
maker.target_dir = script_dir
for k, v in console_scripts.items():
script = '%s = %s' % (k, v)
filenames = maker.make(script)
fileop.set_executable_mode(filenames)
if gui_scripts:
options = {'gui': True }
for k, v in gui_scripts.items():
script = '%s = %s' % (k, v)
filenames = maker.make(script, options)
fileop.set_executable_mode(filenames)
p = os.path.join(libdir, info_dir)
dist = InstalledDistribution(p)
# Write SHARED
paths = dict(paths) # don't change passed in dict
del paths['purelib']
del paths['platlib']
paths['lib'] = libdir
p = dist.write_shared_locations(paths, dry_run)
if p:
outfiles.append(p)
# Write RECORD
dist.write_installed_files(outfiles, paths['prefix'],
dry_run)
return dist
except Exception: # pragma: no cover
logger.exception('installation failed.')
fileop.rollback()
raise
finally:
shutil.rmtree(workdir)
def _get_dylib_cache(self):
global cache
if cache is None:
# Use native string to avoid issues on 2.x: see Python #20140.
base = os.path.join(get_cache_base(), str('dylib-cache'),
sys.version[:3])
cache = Cache(base)
return cache
def _get_extensions(self):
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
arcname = posixpath.join(info_dir, 'EXTENSIONS')
wrapper = codecs.getreader('utf-8')
result = []
with ZipFile(pathname, 'r') as zf:
try:
with zf.open(arcname) as bf:
wf = wrapper(bf)
extensions = json.load(wf)
cache = self._get_dylib_cache()
prefix = cache.prefix_to_dir(pathname)
cache_base = os.path.join(cache.base, prefix)
if not os.path.isdir(cache_base):
os.makedirs(cache_base)
for name, relpath in extensions.items():
dest = os.path.join(cache_base, convert_path(relpath))
if not os.path.exists(dest):
extract = True
else:
file_time = os.stat(dest).st_mtime
file_time = datetime.datetime.fromtimestamp(file_time)
info = zf.getinfo(relpath)
wheel_time = datetime.datetime(*info.date_time)
extract = wheel_time > file_time
if extract:
zf.extract(relpath, cache_base)
result.append((name, dest))
except KeyError:
pass
return result
def is_compatible(self):
"""
Determine if a wheel is compatible with the running system.
"""
return is_compatible(self)
def is_mountable(self):
"""
Determine if a wheel is asserted as mountable by its metadata.
"""
return True # for now - metadata details TBD
def mount(self, append=False):
pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
if not self.is_compatible():
msg = 'Wheel %s not compatible with this Python.' % pathname
raise DistlibException(msg)
if not self.is_mountable():
msg = 'Wheel %s is marked as not mountable.' % pathname
raise DistlibException(msg)
if pathname in sys.path:
logger.debug('%s already in path', pathname)
else:
if append:
sys.path.append(pathname)
else:
sys.path.insert(0, pathname)
extensions = self._get_extensions()
if extensions:
if _hook not in sys.meta_path:
sys.meta_path.append(_hook)
_hook.add(pathname, extensions)
def unmount(self):
pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
if pathname not in sys.path:
logger.debug('%s not in path', pathname)
else:
sys.path.remove(pathname)
if pathname in _hook.impure_wheels:
_hook.remove(pathname)
if not _hook.impure_wheels:
if _hook in sys.meta_path:
sys.meta_path.remove(_hook)
def verify(self):
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
data_dir = '%s.data' % name_ver
info_dir = '%s.dist-info' % name_ver
metadata_name = posixpath.join(info_dir, METADATA_FILENAME)
wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
record_name = posixpath.join(info_dir, 'RECORD')
wrapper = codecs.getreader('utf-8')
with ZipFile(pathname, 'r') as zf:
with zf.open(wheel_metadata_name) as bwf:
wf = wrapper(bwf)
message = message_from_file(wf)
wv = message['Wheel-Version'].split('.', 1)
file_version = tuple([int(i) for i in wv])
# TODO version verification
records = {}
with zf.open(record_name) as bf:
with CSVReader(stream=bf) as reader:
for row in reader:
p = row[0]
records[p] = row
for zinfo in zf.infolist():
arcname = zinfo.filename
if isinstance(arcname, text_type):
u_arcname = arcname
else:
u_arcname = arcname.decode('utf-8')
if '..' in u_arcname:
raise DistlibException('invalid entry in '
'wheel: %r' % u_arcname)
# The signature file won't be in RECORD,
# and we don't currently don't do anything with it
if u_arcname.endswith('/RECORD.jws'):
continue
row = records[u_arcname]
if row[2] and str(zinfo.file_size) != row[2]:
raise DistlibException('size mismatch for '
'%s' % u_arcname)
if row[1]:
kind, value = row[1].split('=', 1)
with zf.open(arcname) as bf:
data = bf.read()
_, digest = self.get_hash(data, kind)
if digest != value:
raise DistlibException('digest mismatch for '
'%s' % arcname)
def update(self, modifier, dest_dir=None, **kwargs):
"""
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier is free to change the contents of the files pointed to, add
new entries and remove entries, before returning. This method will
extract the entire contents of the wheel to a temporary location, call
the modifier, and then use the passed (and possibly updated)
dictionary to write a new wheel. If ``dest_dir`` is specified, the new
wheel is written there -- otherwise, the original wheel is overwritten.
The modifier should return True if it updated the wheel, else False.
This method returns the same value the modifier returns.
"""
def get_version(path_map, info_dir):
version = path = None
key = '%s/%s' % (info_dir, METADATA_FILENAME)
if key not in path_map:
key = '%s/PKG-INFO' % info_dir
if key in path_map:
path = path_map[key]
version = Metadata(path=path).version
return version, path
def update_version(version, path):
updated = None
try:
v = NormalizedVersion(version)
i = version.find('-')
if i < 0:
updated = '%s+1' % version
else:
parts = [int(s) for s in version[i + 1:].split('.')]
parts[-1] += 1
updated = '%s+%s' % (version[:i],
'.'.join(str(i) for i in parts))
except UnsupportedVersionError:
logger.debug('Cannot update non-compliant (PEP-440) '
'version %r', version)
if updated:
md = Metadata(path=path)
md.version = updated
legacy = not path.endswith(METADATA_FILENAME)
md.write(path=path, legacy=legacy)
logger.debug('Version updated from %r to %r', version,
updated)
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
record_name = posixpath.join(info_dir, 'RECORD')
with tempdir() as workdir:
with ZipFile(pathname, 'r') as zf:
path_map = {}
for zinfo in zf.infolist():
arcname = zinfo.filename
if isinstance(arcname, text_type):
u_arcname = arcname
else:
u_arcname = arcname.decode('utf-8')
if u_arcname == record_name:
continue
if '..' in u_arcname:
raise DistlibException('invalid entry in '
'wheel: %r' % u_arcname)
zf.extract(zinfo, workdir)
path = os.path.join(workdir, convert_path(u_arcname))
path_map[u_arcname] = path
# Remember the version.
original_version, _ = get_version(path_map, info_dir)
# Files extracted. Call the modifier.
modified = modifier(path_map, **kwargs)
if modified:
# Something changed - need to build a new wheel.
current_version, path = get_version(path_map, info_dir)
if current_version and (current_version == original_version):
# Add or update local version to signify changes.
update_version(current_version, path)
# Decide where the new wheel goes.
if dest_dir is None:
fd, newpath = tempfile.mkstemp(suffix='.whl',
prefix='wheel-update-',
dir=workdir)
os.close(fd)
else:
if not os.path.isdir(dest_dir):
raise DistlibException('Not a directory: %r' % dest_dir)
newpath = os.path.join(dest_dir, self.filename)
archive_paths = list(path_map.items())
distinfo = os.path.join(workdir, info_dir)
info = distinfo, info_dir
self.write_records(info, workdir, archive_paths)
self.build_zip(newpath, archive_paths)
if dest_dir is None:
shutil.copyfile(newpath, pathname)
return modified
def compatible_tags():
"""
Return (pyver, abi, arch) tuples compatible with this Python.
"""
versions = [VER_SUFFIX]
major = VER_SUFFIX[0]
for minor in range(sys.version_info[1] - 1, - 1, -1):
versions.append(''.join([major, str(minor)]))
abis = []
for suffix, _, _ in imp.get_suffixes():
if suffix.startswith('.abi'):
abis.append(suffix.split('.', 2)[1])
abis.sort()
if ABI != 'none':
abis.insert(0, ABI)
abis.append('none')
result = []
arches = [ARCH]
if sys.platform == 'darwin':
m = re.match('(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
if m:
name, major, minor, arch = m.groups()
minor = int(minor)
matches = [arch]
if arch in ('i386', 'ppc'):
matches.append('fat')
if arch in ('i386', 'ppc', 'x86_64'):
matches.append('fat3')
if arch in ('ppc64', 'x86_64'):
matches.append('fat64')
if arch in ('i386', 'x86_64'):
matches.append('intel')
if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
matches.append('universal')
while minor >= 0:
for match in matches:
s = '%s_%s_%s_%s' % (name, major, minor, match)
if s != ARCH: # already there
arches.append(s)
minor -= 1
# Most specific - our Python version, ABI and arch
for abi in abis:
for arch in arches:
result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
# where no ABI / arch dependency, but IMP_PREFIX dependency
for i, version in enumerate(versions):
result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
if i == 0:
result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
# no IMP_PREFIX, ABI or arch dependency
for i, version in enumerate(versions):
result.append((''.join(('py', version)), 'none', 'any'))
if i == 0:
result.append((''.join(('py', version[0])), 'none', 'any'))
return set(result)
COMPATIBLE_TAGS = compatible_tags()
del compatible_tags
def is_compatible(wheel, tags=None):
if not isinstance(wheel, Wheel):
wheel = Wheel(wheel) # assume it's a filename
result = False
if tags is None:
tags = COMPATIBLE_TAGS
for ver, abi, arch in tags:
if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
result = True
break
return result
| apache-2.0 |
tvibliani/odoo | addons/account_budget/wizard/account_budget_crossovered_summary_report.py | 373 | 2191 | # -*- 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/>.
#
##############################################################################
import time
from openerp.osv import fields, osv
class account_budget_crossvered_summary_report(osv.osv_memory):
"""
This wizard provides the crossovered budget summary report'
"""
_name = 'account.budget.crossvered.summary.report'
_description = 'Account Budget crossvered summary report'
_columns = {
'date_from': fields.date('Start of period', required=True),
'date_to': fields.date('End of period', required=True),
}
_defaults = {
'date_from': lambda *a: time.strftime('%Y-01-01'),
'date_to': lambda *a: time.strftime('%Y-%m-%d'),
}
def check_report(self, cr, uid, ids, context=None):
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
datas = {
'ids': context.get('active_ids',[]),
'model': 'crossovered.budget',
'form': data
}
datas['form']['ids'] = datas['ids']
datas['form']['report'] = 'analytic-one'
return self.pool['report'].get_action(cr, uid, [], 'account_budget.report_crossoveredbudget', data=datas, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
vitan/hue | apps/impala/src/impala/views.py | 22 | 1651 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
## Main views are inherited from Beeswax.
import logging
import json
from desktop.lib.django_util import JsonResponse
from desktop.context_processors import get_app_name
from beeswax.server import dbms
from beeswax.server.dbms import get_query_server_config
LOG = logging.getLogger(__name__)
def refresh_tables(request):
app_name = get_app_name(request)
query_server = get_query_server_config(app_name)
db = dbms.get(request.user, query_server=query_server)
response = {'status': 0, 'message': ''}
if request.method == "POST":
try:
database = json.loads(request.POST['database'])
added = json.loads(request.POST['added'])
removed = json.loads(request.POST['removed'])
db.invalidate_tables(database, added + removed)
except Exception, e:
response['message'] = str(e)
return JsonResponse(response)
| apache-2.0 |
blacklin/kbengine | kbe/src/lib/python/Lib/distutils/tests/test_install_headers.py | 147 | 1264 | """Tests for distutils.command.install_headers."""
import sys
import os
import unittest
import getpass
from distutils.command.install_headers import install_headers
from distutils.tests import support
from test.support import run_unittest
class InstallHeadersTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
unittest.TestCase):
def test_simple_run(self):
# we have two headers
header_list = self.mkdtemp()
header1 = os.path.join(header_list, 'header1')
header2 = os.path.join(header_list, 'header2')
self.write_file(header1)
self.write_file(header2)
headers = [header1, header2]
pkg_dir, dist = self.create_dist(headers=headers)
cmd = install_headers(dist)
self.assertEqual(cmd.get_inputs(), headers)
# let's run the command
cmd.install_dir = os.path.join(pkg_dir, 'inst')
cmd.ensure_finalized()
cmd.run()
# let's check the results
self.assertEqual(len(cmd.get_outputs()), 2)
def test_suite():
return unittest.makeSuite(InstallHeadersTestCase)
if __name__ == "__main__":
run_unittest(test_suite())
| lgpl-3.0 |
yeahmike/sec4qgis | import_cartography.py | 1 | 42284 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
SEC4QGIS v1.0.5
-------------------
(A QGIS plugin)
-------------------
Funciones relativas a la Sede Electrónica del Catastro (SEC) para QGIS.
Functions related to Spanish Cadastral Electronic Site (SEC) for QGIS.
-------------------
begin : 2016-06-30
copyright : (C) 2016 by Andrés V. O.
website : http://sec4qgis.tk
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import datetime
import hashlib
import os
import codecs
import re
import zipfile
import shutil
import time
from random import randint
from import_cartography_dialog import ImportCartographyDialog
###########################################################################################################################
###########################################################################################################################
def run_script(self):
""" Put your code here and remove the pass statement"""
set_project_options(self)
project_file_info = QFileInfo(QgsProject.instance().fileName())
if project_file_info.absolutePath() == "":
if QSettings().value('SEC4QGIS/last_folder_project') is None:
last_folder_project = ""
else:
last_folder_project = QSettings().value('SEC4QGIS/last_folder_project')
QMessageBox.warning(None, _translate("import_cartography", "WARNING"), _translate("import_cartography", "<b>You have to save your project before importing any cartography.</b><br/><br/>Please, select the name and path for your project on the next window."))
project_file_name = QFileDialog.getSaveFileName(None, _translate("import_cartography", "Save project as"), last_folder_project, "*.qgs")
if len(project_file_name)>0:
if project_file_name[-4:].upper() != ".QGS":
project_file_name = project_file_name+".qgs"
last_folder_project = os.path.split(project_file_name)[0]
QSettings().setValue('SEC4QGIS/last_folder_project', last_folder_project)
project_saved_ok = QgsProject.instance().write(QFileInfo(project_file_name))
else:
QMessageBox.warning(None, _translate("import_cartography", "WARNING"), _translate("import_cartography", "The project has not been saved, ")+_translate("import_cartography", "so you cannot to import the cartography."))
return
if not project_saved_ok:
QMessageBox.critical(None, "ERROR: SIC-0901: ", _translate("import_cartography", "The plugin could not save the project, ")+_translate("import_cartography", "so you cannot to import the cartography."))
return
self.import_cartography_dialog = ImportCartographyDialog()
self.import_cartography_dialog.lineEdit_file_name.clear()
current_project = QgsProject.instance()
sequential_layer_number = current_project.readNumEntry('SEC4QGIS', 'sequential_layer_number')[0]
sequential_layer_name = "CAPA_%04d"%(sequential_layer_number+1,)
self.import_cartography_dialog.lineEdit_new_layer.setPlaceholderText(sequential_layer_name)
project_file_info = QFileInfo(QgsProject.instance().fileName())
project_file_name_without_extension = os.path.splitext(project_file_info.fileName())[0]
directory_1 = project_file_info.absolutePath()+"/"+project_file_name_without_extension+"_CAPAS/"
if (os.path.exists(directory_1)) and (len(self.iface.legendInterface().layers()) == 0):
shutil.rmtree(directory_1, ignore_errors=True)
time.sleep(0.1)
if not os.path.exists(directory_1):
for loop_1 in range(1, 100):
try:
os.makedirs(directory_1)
break
except OSError:
time.sleep(0.1)
if not os.path.exists(directory_1):
self.show_and_log("EC", "ERROR: SIC-0903: "+_translate("import_cartography", "Could not create directory '")+directory_1+"'.")
try:
output_file = codecs.open(directory_1+"test_rw.txt", encoding='utf-8', mode='w')
except IOError:
self.show_and_log ("EC", "ERROR: SIC-0902: "+_translate("import_cartography", "Please, create a new project and try to import the cartography again, because the plugin could not write into this project's layer folder '")+directory_1+"'.")
return
output_file.close()
os.remove(directory_1+"test_rw.txt")
layers_list = self.iface.legendInterface().layers()
layers_names_list = []
polygon_layers_list = []
active_layer_index = -1
index_1 = -1
self.import_cartography_dialog.comboBox_crs.clear()
for layer_1 in layers_list:
if (layer_1.type() == QgsMapLayer.VectorLayer) and (layer_1.geometryType() == 2) and (layer_1.dataProvider().capabilities() & QgsVectorDataProvider.AddFeatures):
layers_names_list.append(layer_1.name())
polygon_layers_list.append(layer_1)
index_1 += 1
if (self.iface.activeLayer() != None) and (layer_1.id() == self.iface.activeLayer().id()):
active_layer_index = index_1
self.import_cartography_dialog.comboBox_existing_layers.addItems(layers_names_list)
if active_layer_index != -1:
self.import_cartography_dialog.comboBox_existing_layers.setCurrentIndex(active_layer_index)
if QSettings().value('SEC4QGIS/default_import_to_new_layer') is None:
default_import_to_new_layer = False
else:
default_import_to_new_layer = QSettings().value('SEC4QGIS/default_import_to_new_layer')
if (len(polygon_layers_list)>0) and (default_import_to_new_layer != 1):
self.import_cartography_dialog.radioButton_new_layer.setEnabled(True)
self.import_cartography_dialog.lineEdit_new_layer.setEnabled(False)
self.import_cartography_dialog.comboBox_crs.setEnabled(False)
self.import_cartography_dialog.radioButton_existing_layers.setChecked(True)
self.import_cartography_dialog.comboBox_existing_layers.setEnabled(True)
else:
self.import_cartography_dialog.radioButton_new_layer.setEnabled(True)
self.import_cartography_dialog.comboBox_crs.setEnabled(True)
self.import_cartography_dialog.radioButton_new_layer.setChecked(True)
self.import_cartography_dialog.lineEdit_new_layer.setEnabled(True)
if (len(polygon_layers_list) == 0):
self.import_cartography_dialog.radioButton_existing_layers.setEnabled(False)
self.import_cartography_dialog.comboBox_existing_layers.setEnabled(False)
for valid_sec_crs in sorted(self.valid_sec_crs_list.keys()):
self.import_cartography_dialog.comboBox_crs.addItem(valid_sec_crs+" = "+self.valid_sec_crs_list[valid_sec_crs])
self.import_cartography_dialog.comboBox_crs.setCurrentIndex(1)
self.import_cartography_dialog.show()
result = self.import_cartography_dialog.exec_()
if not result:
return
files_names_string = self.import_cartography_dialog.lineEdit_file_name.text()
if self.import_cartography_dialog.radioButton_new_layer.isChecked():
selected_crs = sorted(self.valid_sec_crs_list.keys())[self.import_cartography_dialog.comboBox_crs.currentIndex()]
if self.import_cartography_dialog.lineEdit_new_layer.text() == '':
new_layer_name = sequential_layer_name
else:
new_layer_name = self.import_cartography_dialog.lineEdit_new_layer.text()
memory_layer_1 = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", new_layer_name, "memory")
if not memory_layer_1.isValid():
self.show_and_log("EC", "SIC-0201: "+_translate("import_cartography", "The memory layer '")+new_layer_name+_translate("import_cartography", "' could NOT be created with CRS '")+selected_crs+"'.")
return
shapefile_name = directory_1+self.fix_characters(new_layer_name)+"_"+self.fix_characters(str(datetime.datetime.now().isoformat())[:-7])+".shp"
writer_1 = QgsVectorFileWriter.writeAsVectorFormat(memory_layer_1, shapefile_name, "UTF-8", QgsCoordinateReferenceSystem(int(selected_crs[5:]), QgsCoordinateReferenceSystem.EpsgCrsId), "ESRI Shapefile")
destination_layer = QgsVectorLayer(shapefile_name, new_layer_name, "ogr")
if not destination_layer.isValid():
self.show_and_log("EC", "SIC-0202: "+_translate("import_cartography", "The Shapefile layer '")+new_layer_name+_translate("import_cartography", "' could NOT be created with CRS '")+selected_crs+"'.")
return
set_layer_options(self, destination_layer)
elif self.import_cartography_dialog.radioButton_existing_layers.isChecked():
selected_layer_index = self.import_cartography_dialog.comboBox_existing_layers.currentIndex()
destination_layer = polygon_layers_list[selected_layer_index]
selected_crs = destination_layer.crs().authid()
else:
self.show_and_log("EC", "SIC-0203: "+_translate("import_cartography", "You have not selected the layer type."))
return
import_files(self, files_names_string, destination_layer, selected_crs, current_project)
###########################################################################################################################
###########################################################################################################################
def import_files(self, files_names_string, destination_layer, selected_crs, current_project):
number_of_parcels_imported = 0
files_names_list = re.findall(r'"(.+?)"', files_names_string)
if len(files_names_list) == 0:
files_names_list = [files_names_string]
for file_name in files_names_list:
if not os.path.isfile(file_name):
self.show_and_log ("EC", "ERROR: SIC-0204: "+_translate("import_cartography", "File '")+file_name+_translate("import_cartography", "' does not exists."))
return
file_extension = os.path.splitext(file_name)[1].upper()
if file_extension == ".DXF":
import_result = import_dxf(self, file_name, selected_crs, destination_layer)
if import_result == -1:
number_of_parcels_imported = -1
break
number_of_parcels_imported += import_result
elif file_extension in [".GML", ".SHP"]:
import_result = import_gml_and_shp(self, file_name, selected_crs, destination_layer)
if import_result == -1:
number_of_parcels_imported = -1
break
number_of_parcels_imported += import_result
elif file_extension == ".ZIP":
import_result = import_zip(self, file_name, selected_crs, destination_layer)
if import_result == -1:
number_of_parcels_imported = -1
break
number_of_parcels_imported += import_result
else:
self.show_and_log("EC", "SIC-0205: "+_translate("import_cartography", "File extension unknown '")+file_name+"'")
return
if number_of_parcels_imported == -1:
return
elif number_of_parcels_imported == 0:
self.show_and_log("EC", "SIC-0206: "+_translate("import_cartography", "The cartography has NOT been imported to layer '")+destination_layer.name()+_translate("import_cartography","'. No cadastral parcels have been created."), 10)
return
elif number_of_parcels_imported == 1:
self.show_and_log("I", _translate("import_cartography", "The cartography has been successfully imported to layer '")+destination_layer.name()+_translate("import_cartography","'. The plugin has created 1 cadastral parcel."), 10)
elif number_of_parcels_imported > 1:
self.show_and_log("I", _translate("import_cartography", "The cartography has been successfully imported to layer '")+destination_layer.name()+_translate("import_cartography", "'. The plugin has created ")+str(number_of_parcels_imported)+_translate("import_cartography", " cadastral parcels."), 10)
else:
self.show_and_log("EC", "SIC-0207: "+_translate("import_cartography", "The cartography has NOT been imported to layer '")+destination_layer.name()+_translate("import_cartography","'. Unknown number of cadastral parcels."), 10)
return
if self.import_cartography_dialog.radioButton_new_layer.isChecked():
QgsMapLayerRegistry.instance().addMapLayer(destination_layer, 0)
layers_root_node = QgsProject.instance().layerTreeRoot()
destination_layer_node = QgsLayerTreeLayer(destination_layer)
layers_root_node.insertChildNode(0, destination_layer_node)
sequential_layer_number = current_project.readNumEntry('SEC4QGIS', 'sequential_layer_number')[0]
current_project.writeEntry('SEC4QGIS', 'sequential_layer_number', sequential_layer_number+1)
canvas_1 = self.iface.mapCanvas()
destination_layer.updateExtents()
destination_layer_extent = destination_layer.extent()
canvas_1.setExtent(destination_layer_extent)
self.iface.mapCanvas().refresh()
self.iface.mapCanvas().refresh()
###########################################################################################################################
###########################################################################################################################
def import_zip(self, file_name, selected_crs, destination_layer):
unzip_directory = unzip_cartography(self, file_name)
if unzip_directory == "":
return -1
number_of_parcels_imported = 0
for root_1, dirs_names, files_names_list in os.walk(unzip_directory):
for file_name in files_names_list:
file_extension = os.path.splitext(file_name)[1].upper()
if file_extension == ".DXF":
number_of_parcels_imported += import_dxf(self, unzip_directory+'/'+file_name, selected_crs, destination_layer)
elif file_extension in [".GML", ".SHP"]:
number_of_parcels_imported += import_gml_and_shp(self, unzip_directory+'/'+file_name, selected_crs, destination_layer)
else:
pass
return number_of_parcels_imported
###########################################################################################################################
###########################################################################################################################
def import_gml_and_shp(self, file_name, selected_crs, destination_layer):
source_layer = QgsVectorLayer(file_name, "source_layer", "ogr")
file_crs = ""
if not source_layer.isValid():
self.show_and_log("EC", "SIC-1001: "+_translate("import_cartography", "The file '")+file_name+_translate("import_cartography", "' has NOT been imported."), 10)
return -1
self.iface.messageBar().clearWidgets()
file_extension = (os.path.splitext(file_name)[1].upper())[1:]
if file_extension == "GML":
localId_file_field = ['inspireId_localId', 'localId']
nameSpace_file_field = ['inspireId_namespace', 'namespace']
for line_1 in open(file_name):
if "EPSG:" in line_1:
file_crs = "EPSG:"+re.findall(r'EPSG:+(\d+)', line_1)[0]
break
elif file_extension == "SHP":
localId_file_field = 'localId'
nameSpace_file_field = 'namespace'
file_crs = source_layer.crs().authid()
if selected_crs != file_crs:
self.show_and_log("EC", "SIC-1002: "+_translate("import_cartography", "The CRS of the file '")+file_crs+_translate("import_cartography", "' does NOT match the CRS of destination layer '")+selected_crs+_translate("import_cartography", "'. File '")+file_name+_translate("import_cartography", "' has NOT been imported."), 10)
return -1
start_time = datetime.datetime.now()
number_of_parcels_imported = 0
destination_parcel = QgsFeature()
for source_parcel in source_layer.getFeatures():
if source_parcel.geometry() is None:
continue
if (source_parcel.geometry().wkbType() != 3) and (source_parcel.geometry().wkbType() != 6):
continue
destination_parcel.setGeometry(source_parcel.geometry())
destination_parcel.initAttributes(2)
if file_extension == "GML":
if source_parcel.fieldNameIndex(localId_file_field[0]) != -1:
destination_parcel.setAttribute(0, source_parcel[localId_file_field[0]])
elif source_parcel.fieldNameIndex(localId_file_field[1]) != -1:
destination_parcel.setAttribute(0, source_parcel[localId_file_field[1]])
if source_parcel.fieldNameIndex(nameSpace_file_field[0]) != -1:
if source_parcel[nameSpace_file_field[0]].upper() == "ES.SDGC.CP":
destination_parcel.setAttribute(1, self.valid_dgc_nameSpace_list[0])
else:
destination_parcel.setAttribute(1, source_parcel[nameSpace_file_field[0]])
elif source_parcel.fieldNameIndex(nameSpace_file_field[1]) != -1:
if source_parcel[nameSpace_file_field[1]].upper() == "ES.SDGC.CP":
destination_parcel.setAttribute(1, self.valid_dgc_nameSpace_list[0])
else:
destination_parcel.setAttribute(1, source_parcel[nameSpace_file_field[1]])
elif file_extension == "SHP":
if source_parcel.fieldNameIndex(localId_file_field) != -1:
destination_parcel.setAttribute(0, source_parcel[localId_file_field])
if source_parcel.fieldNameIndex(nameSpace_file_field) != -1:
if source_parcel[nameSpace_file_field].upper() == self.valid_dgc_nameSpace_list[0]:
destination_parcel.setAttribute(1, self.valid_dgc_nameSpace_list[0])
else:
destination_parcel.setAttribute(1, source_parcel[nameSpace_file_field])
destination_layer.dataProvider().addFeatures([destination_parcel])
number_of_parcels_imported += 1
stop_time = datetime.datetime.now()
return number_of_parcels_imported
###########################################################################################################################
###########################################################################################################################
def import_dxf(self, file_name, selected_crs, destination_layer):
number_of_parcels_imported = 0
file_hash_127 = dxf_header_hash(self, file_name, 127)
file_hash_009 = dxf_header_hash(self, file_name, 9)
if file_hash_127 == -1:
return -1
elif file_hash_127 == "305b2eb973210df65e34488b08cca09e0b39772c2bdf0bb35848bc35e6f4c103":
number_of_parcels_imported += import_dxf_sec_zone(self, file_name, selected_crs, destination_layer)
elif file_hash_009 == "da1a135bf425e97b727b79f639d6d8a22a21e40e171f7785704fcf6cd4196a78":
number_of_parcels_imported += import_dxf_sec_parcel(self, file_name, selected_crs, destination_layer)
else:
self.show_and_log("EC", "SIC-0301: "+_translate("import_cartography", "File format unknown for '")+file_name+_translate("import_cartography", "'. No cadastral parcels have been created."))
return -1
return number_of_parcels_imported
###########################################################################################################################
###########################################################################################################################
def import_dxf_sec_zone(self, file_name, selected_crs, destination_layer):
layer_dxf_lines = QgsVectorLayer(file_name+"|layername=entities|geometrytype=LineString", "layer_dxf_lines", "ogr")
if not layer_dxf_lines.isValid():
self.show_and_log("EC", "SIC-0401: "+_translate("import_cartography", "Could NOT load the DXF lines layer from '")+file_name+"'.")
return -1
layer_dxf_points = QgsVectorLayer(file_name+"|layername=entities|geometrytype=Point", "layer_dxf_points", "ogr")
if not layer_dxf_points.isValid():
self.show_and_log("EC", "SIC-0402: "+_translate("import_cartography", "Could NOT load the DXF points layer from '")+file_name+"'.")
return -1
self.iface.messageBar().clearWidgets()
start_time = datetime.datetime.now()
layer_dxf_polygon = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFpoligonos", "memory")
if not layer_dxf_polygon.isValid():
self.show_and_log("EC", "SIC-0403: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFpoligonos'")
return -1
in_feat = QgsFeature()
out_feat = QgsFeature()
layer_dxf_polygon_provider = layer_dxf_polygon.dataProvider()
layer_dxf_lines_features = layer_dxf_lines.getFeatures()
while layer_dxf_lines_features.nextFeature(in_feat):
out_geom_list = []
if in_feat.geometry().isMultipart():
out_geom_list = in_feat.geometry().asMultiPolyline()
else:
out_geom_list.append(in_feat.geometry().asPolyline())
poly_geom = trash_wrong_lines(self, out_geom_list)
if (len(poly_geom) != 0) and (in_feat['Layer'] == 'Parcela'):
out_feat.setGeometry(QgsGeometry.fromPolygon(poly_geom))
in_feat_attributes = in_feat.attributes()
out_feat.setAttributes(in_feat_attributes)
layer_dxf_polygon_provider.addFeatures([out_feat])
layer_dxf_polygon_unique = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFsinDup", "memory")
if not layer_dxf_polygon_unique.isValid():
self.show_and_log("EC", "SIC-0404: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFsinDup'")
return -1
for poligono_1 in layer_dxf_polygon.getFeatures():
duplicated_1 = False
for poligono_2 in layer_dxf_polygon.getFeatures():
if poligono_1.id() == poligono_2.id():
continue
if (abs(poligono_1.geometry().intersection(poligono_2.geometry()).area() - poligono_1.geometry().area()) < 0.01) and (poligono_1.id() < poligono_2.id()):
duplicated_1 = True
break
if not duplicated_1:
layer_dxf_polygon_unique.dataProvider().addFeatures([poligono_1])
layer_dxf_polygon_holes = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFhuecos", "memory")
if not layer_dxf_polygon_holes.isValid():
self.show_and_log("EC", "SIC-0405: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFhuecos'")
return -1
for parcel_1 in layer_dxf_polygon_unique.getFeatures():
parcel_temp = QgsFeature()
geometry_temp = QgsGeometry()
modified_1 = False
for parcel_2 in layer_dxf_polygon_unique.getFeatures():
if parcel_1.id() == parcel_2.id():
continue
if parcel_2.geometry().within(parcel_1.geometry()):
if not modified_1:
pass
if geometry_temp.area() <= 0.01:
geometry_temp = QgsGeometry(parcel_1.geometry().difference(parcel_2.geometry()))
else:
geometry_temp = QgsGeometry(geometry_temp.difference(parcel_2.geometry()))
parcel_temp.setGeometry(geometry_temp)
modified_1 = True
if modified_1:
parcel_temp.setAttributes(parcel_1.attributes())
if geometry_temp.area() > 0.01:
layer_dxf_polygon_holes.dataProvider().addFeatures([parcel_temp])
else:
layer_dxf_polygon_holes.dataProvider().addFeatures([parcel_1])
stop_time = datetime.datetime.now()
start_time = datetime.datetime.now()
points_list = layer_dxf_points.getFeatures()
points_rc_list = []
for point_1 in points_list:
if point_1['Layer'] == 'RefCatastral':
points_rc_list.append(point_1)
parcels_list = layer_dxf_polygon_holes.getFeatures()
for parcela_1 in parcels_list:
for point_1 in points_rc_list:
if point_1.geometry().within(parcela_1.geometry()):
cadastral_reference = point_1['Text']
attributes_1 = { 0 : cadastral_reference, 1 : self.valid_dgc_nameSpace_list[0] }
layer_dxf_polygon_holes.dataProvider().changeAttributeValues({ parcela_1.id() : attributes_1 })
points_rc_list.remove(point_1)
break
stop_time = datetime.datetime.now()
number_of_parcels_imported = 0
parcels_list = []
for parcel_1 in layer_dxf_polygon_holes.getFeatures():
parcels_list.append(parcel_1)
for index_1, parcel_1 in enumerate(parcels_list):
parcel_temp = QgsFeature()
duplicates_indexes_list = []
for index_2, parcel_2 in enumerate(parcels_list):
if index_2<=index_1:
continue
if parcel_1[0] == parcel_2[0]:
duplicates_indexes_list.append(index_2)
geometry_temp = parcel_1.geometry()
for duplicates_index in duplicates_indexes_list:
geometry_temp = geometry_temp.combine(parcels_list[duplicates_index].geometry())
parcel_temp.setGeometry(geometry_temp)
duplicates_indexes_list.reverse()
for duplicates_index in duplicates_indexes_list:
del parcels_list[duplicates_index]
parcel_temp.setGeometry(geometry_temp)
parcel_temp.setAttributes(parcel_1.attributes())
number_of_parcels_imported += 1
destination_layer.dataProvider().addFeatures([parcel_temp])
return number_of_parcels_imported
###########################################################################################################################
###########################################################################################################################
def import_dxf_sec_parcel(self, file_name, selected_crs, destination_layer):
fragments_list = []
if "Fragment".upper() in file_name.upper():
if "Fragment0001".upper() in file_name.upper():
(fragments_directory, file_name_only) = os.path.split(file_name)
for root_1, dirs_names, files_names_list in os.walk(fragments_directory):
for file_name in files_names_list:
if (file_name[:14] == file_name_only[:14]) and (file_name[-4:].upper() == '.DXF'):
fragments_list.append(fragments_directory+'/'+file_name)
else:
return 0
else:
fragments_list = [file_name]
start_time = datetime.datetime.now()
layer_dxf_polyline = QgsVectorLayer("MultiLineString?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFpolilinea", "memory")
if not layer_dxf_polyline.isValid():
self.show_and_log("EC", "SIC-0501: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFpolilinea'")
return -1
lines_list=[]
geometry_temp1 = QgsGeometry()
object_temp1 = QgsFeature()
for file_name in fragments_list:
layer_dxf_lines = QgsVectorLayer(file_name+"|layername=entities|geometrytype=LineString", "layer_dxf_lines", "ogr")
if not layer_dxf_lines.isValid():
self.show_and_log("EC", "SIC-0502: "+_translate("import_cartography", "Could NOT load the DXF lines layer from '")+file_name+"'.")
return -1
layer_dxf_points = QgsVectorLayer(file_name+"|layername=entities|geometrytype=Point", "layer_dxf_points", "ogr")
if not layer_dxf_points.isValid():
self.show_and_log("EC", "SIC-0503: "+_translate("import_cartography", "Could NOT load the DXF points layer from '")+file_name+"'.")
return -1
self.iface.messageBar().clearWidgets()
for line_1 in layer_dxf_lines.getFeatures():
if line_1['Layer'] == 'PG-LP':
lines_list.append(line_1)
geometry_temp1 = lines_list[0].geometry()
for line_1 in lines_list[1:]:
geometry_temp1 = geometry_temp1.combine(line_1.geometry())
object_temp1.setGeometry(geometry_temp1)
layer_dxf_polyline.dataProvider().addFeatures([object_temp1])
layer_dxf_polygon = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFpoligonos", "memory")
if not layer_dxf_polyline.isValid():
self.show_and_log("EC", "SIC-0504: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFpoligonos'")
return -1
lines_list = re.findall(r'\(([^\(\)]+)\)', geometry_temp1.exportToWkt())
for line_1 in lines_list:
line_coordinates_array = re.findall(r'^([^,]+?), ((.+), )*([^,]+)$', line_1)
if line_coordinates_array[0][0] == line_coordinates_array[0][3]:
polygon_coordinates_string = line_coordinates_array[0][0]+', '+line_coordinates_array[0][2]+', '+line_coordinates_array[0][3]
else:
polygon_coordinates_string = line_coordinates_array[0][0]+', '+line_coordinates_array[0][2]+', '+line_coordinates_array[0][3]+', '+line_coordinates_array[0][0]
object_temp2 = QgsFeature()
object_temp2.setGeometry(QgsGeometry.fromWkt('Polygon (('+polygon_coordinates_string+'))'))
layer_dxf_polygon.dataProvider().addFeatures([object_temp2])
layer_dxf_polygon_holes = QgsVectorLayer("MultiPolygon?crs="+selected_crs+"&field="+self.field_localId+":string(14)&field="+self.field_nameSpace+":string(11)", destination_layer.name()+"-DXFpoligonosHuecos", "memory")
if not layer_dxf_polyline.isValid():
self.show_and_log("EC", "SIC-0505: "+_translate("import_cartography", "Could NOT create the layer '")+destination_layer.name()+"-DXFpoligonosHuecos'")
return -1
polygons_holes_list = []
for parcel_1 in layer_dxf_polygon.getFeatures():
parcel_temp = QgsFeature()
geometry_temp = QgsGeometry()
is_a_hole = False
modified_1 = False
for parcel_2 in layer_dxf_polygon.getFeatures():
if parcel_1.id() == parcel_2.id():
continue
if parcel_1.geometry().within(parcel_2.geometry()):
is_a_hole = True
break
if parcel_2.geometry().within(parcel_1.geometry()):
if not modified_1:
pass
if geometry_temp.area() <= 0.01:
geometry_temp = QgsGeometry(parcel_1.geometry().difference(parcel_2.geometry()))
else:
geometry_temp = QgsGeometry(geometry_temp.difference(parcel_2.geometry()))
parcel_temp.setGeometry(geometry_temp)
modified_1 = True
if modified_1:
parcel_temp.setAttributes(parcel_1.attributes())
if geometry_temp.area() > 0.01:
layer_dxf_polygon_holes.dataProvider().addFeatures([parcel_temp])
polygons_holes_list.append(parcel_temp)
elif not is_a_hole:
layer_dxf_polygon_holes.dataProvider().addFeatures([parcel_1])
polygons_holes_list.append(parcel_1)
object_temp4 = QgsFeature()
geometry_temp4 = polygons_holes_list[0].geometry()
for poligono4 in polygons_holes_list[1:]:
geometry_temp4 = geometry_temp4.combine(poligono4.geometry())
object_temp4.setGeometry(geometry_temp4)
cadastral_reference = os.path.split(file_name)[1][:14]
object_temp4.initAttributes(2)
object_temp4.setAttribute(0, cadastral_reference)
object_temp4.setAttribute(1, self.valid_dgc_nameSpace_list[0])
destination_layer.dataProvider().addFeatures([object_temp4])
stop_time = datetime.datetime.now()
return 1
###########################################################################################################################
###########################################################################################################################
def trash_wrong_lines(self, lines_list):
geometry_temp1 = []
if len(lines_list) == 1:
if len(lines_list[0]) > 2:
geometry_temp1 = lines_list
else:
geometry_temp1 = []
else:
geometry_temp1 = [line_1 for line_1 in lines_list if len(line_1) > 2]
return geometry_temp1
###########################################################################################################################
###########################################################################################################################
def get_map_layer_by_name(layer_name):
layer_map = QgsMapLayerRegistry.instance().mapLayers()
for name_1, layer_1 in layer_map.iteritems():
if layer_1.name().upper() == layer_name.upper():
if layer_1.isValid():
return layer_1
else:
return None
###########################################################################################################################
###########################################################################################################################
def dxf_header_hash(self, file_name, lines_number=127):
try:
file_1 = open(file_name, "rU")
except IOError:
self.show_and_log("EC", "SIC-0601: "+_translate("import_cartography", "Error opening file '")+file_name+"'.", 10)
return -1
dxf_header_hash = hashlib.sha256()
for loop_1 in range(1, lines_number):
dxf_header_hash.update(file_1.readline())
file_1.close()
return dxf_header_hash.hexdigest()
###########################################################################################################################
###########################################################################################################################
def set_layer_options(self, layer_1):
current_project = QgsProject.instance()
layer_options_new = dict ([
('active', True),
('mode', 0),
('units', 1),
('tolerance', 10.0),
('avoid_intersections', False)
])
layer_options_new_list=(layer_options_new['active'], layer_options_new['mode'], layer_options_new['units'], layer_options_new['tolerance'], layer_options_new['avoid_intersections'])
layer_options_current_list=current_project.snapSettingsForLayer(layer_1.id())[1:]
if layer_options_current_list != layer_options_new_list:
current_project.setSnapSettingsForLayer(layer_1.id(), layer_options_new['active'], layer_options_new['mode'], layer_options_new['units'], layer_options_new['tolerance'], layer_options_new['avoid_intersections'])
###########################################################################################################################
###########################################################################################################################
def set_project_options(self):
current_project = QgsProject.instance()
project_parameters_new = dict([
('Digitizing|DefaultSnapToleranceUnit|Num', 1),
('Digitizing|DefaultSnapType|String', 'to_vertex'),
('Digitizing|DefaultSnapTolerance|Num', 10),
('Digitizing|IntersectionSnapping|Bool', True),
('Digitizing|TopologicalEditing|Num', 1),
('Digitizing|SnappingMode|String', 'advanced'),
('PositionPrecision|DecimalPlaces|Num', 3),
('PositionPrecision|Automatic|Bool', False)
])
project_parameters_changed = []
for project_parameters_key in sorted(project_parameters_new.keys()):
[project_parameter_plugin, project_parameter_section, project_parameter_type] = project_parameters_key.split("|")
if project_parameter_type == "Bool":
project_parameter_current_value = current_project.readBoolEntry(project_parameter_plugin, project_parameter_section)[0]
elif project_parameter_type == "Num":
project_parameter_current_value = current_project.readNumEntry(project_parameter_plugin, project_parameter_section)[0]
elif project_parameter_type == "String":
project_parameter_current_value = current_project.readEntry(project_parameter_plugin, project_parameter_section)[0]
else:
self.show_and_log("E", "SIC-0701: "+_translate("import_cartography", "Project parameter type unknown: ")+str(project_parameters_key), 0)
return
project_parameter_new_value = project_parameters_new[project_parameters_key]
if project_parameter_current_value != project_parameter_new_value:
current_project.writeEntry(project_parameter_plugin, project_parameter_section, project_parameter_new_value)
project_parameters_changed.append(project_parameters_key+"="+str(project_parameter_new_value))
else:
pass
if len(project_parameters_changed) > 0:
pass
###########################################################################################################################
###########################################################################################################################
def round_geometry (feature_input, decimal_digits=2):
feature_rounded = feature_input
feature_rounded.setGeometry(QgsGeometry.fromWkt(feature_input.geometry().exportToWkt(decimal_digits)))
return feature_rounded
###########################################################################################################################
###########################################################################################################################
def unzip_cartography (self, zip_file_name):
extracted_files_number = 0
timestamp_unzip = str(datetime.datetime.now().isoformat())[:-3]+("%04d" % randint(1,9999))
year_1 = timestamp_unzip[:4]
month_1 = timestamp_unzip[5:7]
day_1 = timestamp_unzip[8:10]
base_directory_name_1 = os.path.dirname(os.path.abspath(__file__))+"/tmp/"
unzip_directory = base_directory_name_1+self.fix_characters(timestamp_unzip)+"/"
if not os.path.exists(unzip_directory):
os.makedirs(unzip_directory)
try:
zip_file = zipfile.ZipFile(zip_file_name)
except IOError:
self.show_and_log ("E", "SIC-0801: "+_translate("import_cartography", "Error opening file '")+zip_file_name+"'", 10)
return ""
except zipfile.BadZipfile:
self.show_and_log ("E", "SIC-0802: "+_translate("import_cartography", "ZIP file corrupted: '")+zip_file_name+"'", 10)
return ""
zip_info = zip_file.infolist()
for zip_object in zip_info:
source_name = unzip_directory+zip_object.filename
(base_directory_name_1, file_1) = os.path.split(source_name)
extension_1 = os.path.splitext(file_1)[1].upper()
try:
zip_file.extract(zip_object, unzip_directory)
except IOError:
self.show_and_log ("E", "SIC-0803: "+_translate("import_cartography", "ZIP file corrupted: '")+zip_file_name+"'", 10)
return ""
if extension_1 not in ['.DXF', '.GML']:
continue
extracted_files_number += 1
for loop_1 in range(1,9999):
suffix_1 = "_Fragment%04d" % loop_1
destination_name = unzip_directory+file_1[:-4].replace("\\", "/")+suffix_1+extension_1
(base_directory_name_2, file_2) = os.path.split(destination_name)
if not os.path.exists(base_directory_name_2):
os.makedirs(base_directory_name_2)
if not os.path.exists(unzip_directory+file_2):
shutil.move(source_name, destination_name)
shutil.move(destination_name, unzip_directory+file_2)
break
return unzip_directory
###########################################################################################################################
###########################################################################################################################
def _translate(context_1, text_1, disambig_1=None):
return QtGui.QApplication.translate(context_1, text_1, disambig_1)
###########################################################################################################################
###########################################################################################################################
def layer_exists(layer_name_search):
layermap_1 = QgsMapLayerRegistry.instance().mapLayers()
for name_1, layer_1 in layermap_1.iteritems():
if layer.name_1() == layer_name_search:
if layer.isValid():
return True
else:
return False
return False
| gpl-3.0 |
caidongyun/pylearn2 | pylearn2/utils/timing.py | 49 | 2601 | """Utilities related to timing various segments of code."""
__authors__ = "David Warde-Farley"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["David Warde-Farley"]
__license__ = "3-clause BSD"
__maintainer__ = "David Warde-Farley"
__email__ = "wardefar@iro"
from contextlib import contextmanager
import logging
import datetime
def total_seconds(delta):
"""
Extract the total number of seconds from a timedelta object
in a way that is compatible with Python <= 2.6.
Parameters
----------
delta : object
A `datetime.timedelta` object.
Returns
-------
total : float
The time quantity represented by `delta` in seconds,
with a fractional portion.
"""
if hasattr(delta, 'total_seconds'):
return delta.total_seconds()
else:
return (delta.microseconds +
(delta.seconds + delta.days * 24 * 3600) * 10 ** 6
) / float(10 ** 6)
@contextmanager
def log_timing(logger, task, level=logging.INFO, final_msg=None,
callbacks=None):
"""
Context manager that logs the start/end of an operation,
and timing information, to a given logger.
Parameters
----------
logger : object
A Python standard library logger object, or an object
that supports the `logger.log(level, message, ...)`
API it defines.
task : str
A string indicating the operation being performed.
A '...' will be appended to the initial logged message.
If `None`, no initial message will be printed.
level : int, optional
The log level to use. Default `logging.INFO`.
final_msg : str, optional
Display this before the reported time instead of
'<task> done. Time elapsed:'. A space will be
added between this message and the reported
time.
callbacks: list, optional
A list of callbacks taking as argument an
integer representing the total number of seconds.
"""
start = datetime.datetime.now()
if task is not None:
logger.log(level, str(task) + '...')
yield
end = datetime.datetime.now()
delta = end - start
total = total_seconds(delta)
if total < 60:
delta_str = '%f seconds' % total
else:
delta_str = str(delta)
if final_msg is None:
logger.log(level, str(task) + ' done. Time elapsed: %s' % delta_str)
else:
logger.log(level, ' '.join((final_msg, delta_str)))
if callbacks is not None:
for callback in callbacks:
callback(total)
| bsd-3-clause |
SabaFar/plc | bindings/callbacks_list.py | 1 | 1238 | callback_classes = [
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Packet const>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Packet>', 'ns3::Mac48Address', 'ns3::Mac48Address', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::PLC_PhyCcaResult', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
]
| gpl-3.0 |
h4ck3rm1k3/MapNickAutotools | scons/scons-local-1.2.0/SCons/Tool/link.py | 12 | 4288 | """SCons.Tool.link
Tool-specific initialization for the generic Posix linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/link.py 3842 2008/12/20 22:59:52 scons"
import SCons.Defaults
import SCons.Tool
import SCons.Util
import SCons.Warnings
from SCons.Tool.FortranCommon import isfortran
cplusplus = __import__('c++', globals(), locals(), [])
issued_mixed_link_warning = False
def smart_link(source, target, env, for_signature):
has_cplusplus = cplusplus.iscplusplus(source)
has_fortran = isfortran(env, source)
if has_cplusplus and has_fortran:
global issued_mixed_link_warning
if not issued_mixed_link_warning:
msg = "Using $CXX to link Fortran and C++ code together.\n\t" + \
"This may generate a buggy executable if the %s\n\t" + \
"compiler does not know how to deal with Fortran runtimes."
SCons.Warnings.warn(SCons.Warnings.FortranCxxMixWarning,
msg % repr(env.subst('$CXX')))
issued_mixed_link_warning = True
return '$CXX'
elif has_fortran:
return '$FORTRAN'
elif has_cplusplus:
return '$CXX'
return '$CC'
def shlib_emitter(target, source, env):
for tgt in target:
tgt.attributes.shared = 1
return (target, source)
def generate(env):
"""Add Builders and construction variables for gnulink to an Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['SHLINK'] = '$LINK'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
env['SHLINKCOM'] = '$SHLINK -o $TARGET $SHLINKFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
# don't set up the emitter, cause AppendUnique will generate a list
# starting with None :-(
env.Append(SHLIBEMITTER = [shlib_emitter])
env['SMARTLINK'] = smart_link
env['LINK'] = "$SMARTLINK"
env['LINKFLAGS'] = SCons.Util.CLVar('')
env['LINKCOM'] = '$LINK -o $TARGET $LINKFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
env['LIBDIRPREFIX']='-L'
env['LIBDIRSUFFIX']=''
env['_LIBFLAGS']='${_stripixes(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, LIBPREFIXES, LIBSUFFIXES, __env__)}'
env['LIBLINKPREFIX']='-l'
env['LIBLINKSUFFIX']=''
if env['PLATFORM'] == 'hpux':
env['SHLIBSUFFIX'] = '.sl'
elif env['PLATFORM'] == 'aix':
env['SHLIBSUFFIX'] = '.a'
# For most platforms, a loadable module is the same as a shared
# library. Platforms which are different can override these, but
# setting them the same means that LoadableModule works everywhere.
SCons.Tool.createLoadableModuleBuilder(env)
env['LDMODULE'] = '$SHLINK'
env['LDMODULEPREFIX'] = '$SHLIBPREFIX'
env['LDMODULESUFFIX'] = '$SHLIBSUFFIX'
env['LDMODULEFLAGS'] = '$SHLINKFLAGS'
env['LDMODULECOM'] = '$SHLINKCOM'
def exists(env):
# This module isn't really a Tool on its own, it's common logic for
# other linkers.
return None
| lgpl-2.1 |
yueranyuan/vector_edu | learntools/kt/kt2.py | 1 | 4976 | from itertools import groupby
import numpy as np
import theano
import theano.tensor as T
from learntools.libs.logger import log_me
from learntools.libs.utils import idx_to_mask
from learntools.libs.auc import auc
from learntools.model.math import neg_log_loss
from learntools.model.theano_utils import make_shared, make_probability
@log_me('... building the model')
def build_model(prepared_data, clamp_L0=0.4, eeg_column_i=None, **kwargs):
# ##########
# STEP1: order the data properly so that we can read from it sequentially
# when training the model
subject_x, skill_x, correct_y, start_x, eeg_x, eeg_table, stim_pairs, train_idx, valid_idx = prepared_data
N = len(correct_y)
train_mask = idx_to_mask(train_idx, N)
valid_mask = idx_to_mask(valid_idx, N)
# sort data by subject and skill
sorted_i = sorted(xrange(N), key=lambda i: (subject_x[i], skill_x[i], start_x[i]))
skill_x = skill_x[sorted_i]
subject_x = subject_x[sorted_i]
correct_y = correct_y[sorted_i]
start_x = start_x[sorted_i]
train_mask = train_mask[sorted_i]
valid_mask = valid_mask[sorted_i]
train_idx = np.nonzero(train_mask)[0]
valid_idx = np.nonzero(valid_mask)[0]
n_skills = np.max(skill_x) + 1
n_subjects = np.max(subject_x) + 1
# binarize eeg
eeg_single_x = np.zeros(N)
if eeg_column_i is not None:
eeg_column = eeg_table[eeg_x, eeg_column_i]
above_median = np.greater(eeg_column, np.median(eeg_column))
eeg_single_x[above_median] = 1
# prepare parameters
p_T = 0.5
p_G = 0.1
p_S = 0.2
p_L0 = 0.7
if clamp_L0 is None:
p_L0 = 0.7
else:
p_L0 = clamp_L0
# eeg_single_x = np.zeros(N)
parameter_base = np.ones(n_skills)
tp_L0, t_L0 = make_probability(parameter_base * p_L0, name='L0')
tp_T, t_T = make_probability(np.ones((n_skills, 2)) * p_T, name='p(T)')
tp_G, t_G = make_probability(p_G, name='p(G)')
tp_S, t_S = make_probability(p_S, name='p(S)')
# declare and prepare variables for theano
i = T.ivector('i')
dummy_float = make_shared(0, name='dummy')
skill_i, subject_i = T.iscalars('skill_i', 'subject_i')
correct_y = make_shared(correct_y, to_int=True)
eeg_single_x = make_shared(eeg_single_x, to_int=True)
def step(correct_i, eeg, prev_L, prev_p_C, P_T, P_S, P_G):
Ln = prev_L + (1 - prev_L) * P_T[eeg]
p_C = prev_L * (1 - P_S) + (1 - prev_L) * P_G
return Ln, p_C
# set up theano functions
((results, p_C), updates) = theano.scan(fn=step,
sequences=[correct_y[i],
eeg_single_x[i]],
outputs_info=[tp_L0[skill_i],
dummy_float],
non_sequences=[tp_T[skill_i],
tp_G,
tp_S])
p_y = T.stack(1 - p_C, p_C)
loss = neg_log_loss(p_y, correct_y[i])
learning_rate = T.fscalar('learning_rate')
if clamp_L0 is None:
params = [t_T, t_L0]
else:
params = [t_T]
update_parameters = [(param, param - learning_rate * T.grad(loss, param))
for param in params]
tf_train = theano.function(inputs=[i, skill_i, learning_rate],
updates=update_parameters,
outputs=[loss, results, i],
allow_input_downcast=True)
tf_valid = theano.function(inputs=[i, skill_i],
outputs=[loss, results, i],
allow_input_downcast=True)
def f_train((i, (subject_i, skill_i)), learning_rate):
return tf_train(i, skill_i, learning_rate)
def f_valid((i, (subject_i, skill_i))):
return tf_valid(i, skill_i)
def gen_batches(idxs, keys):
all_keys = zip(*keys)
return [(list(idx), k) for k, idx in
groupby(idxs, key=lambda i: all_keys[i])]
def train_eval(idxs, pred):
_y = correct_y.owner.inputs[0].get_value(borrow=True)[idxs]
return auc(_y, pred, pos_label=1)
def valid_eval(idxs, pred):
_y = correct_y.owner.inputs[0].get_value(borrow=True)[idxs]
return auc(_y, pred, pos_label=1)
train_batches = gen_batches(train_idx, [subject_x, skill_x])
valid_batches = gen_batches(valid_idx, [subject_x, skill_x])
'''
for (i, (subject_i, skill_i)) in train_batches:
tf_train(i, skill_i, 0.1)
for (i, (subject_i, skill_i)) in valid_batches:
_1, _2, _3, a = tf_valid(i, skill_i)
print sum(np.equal(a, 0.2)), max(skill_x) - len(np.unique(skill_x))
import sys
sys.exit()
'''
return f_train, f_valid, train_batches, valid_batches, train_eval, valid_eval
| mit |
Russell-IO/ansible | lib/ansible/modules/cloud/ovirt/ovirt_affinity_label_facts.py | 71 | 5541 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_affinity_label_facts
short_description: Retrieve facts about one or more oVirt/RHV affinity labels
author: "Ondra Machacek (@machacekondra)"
version_added: "2.3"
description:
- "Retrieve facts about one or more oVirt/RHV affinity labels."
notes:
- "This module creates a new top-level C(ovirt_affinity_labels) fact, which
contains a list of affinity labels."
options:
name:
description:
- "Name of the affinity labels which should be listed."
vm:
description:
- "Name of the VM, which affinity labels should be listed."
host:
description:
- "Name of the host, which affinity labels should be listed."
extends_documentation_fragment: ovirt_facts
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather facts about all affinity labels, which names start with C(label):
- ovirt_affinity_label_facts:
name: label*
- debug:
var: affinity_labels
# Gather facts about all affinity labels, which are assigned to VMs
# which names start with C(postgres):
- ovirt_affinity_label_facts:
vm: postgres*
- debug:
var: affinity_labels
# Gather facts about all affinity labels, which are assigned to hosts
# which names start with C(west):
- ovirt_affinity_label_facts:
host: west*
- debug:
var: affinity_labels
# Gather facts about all affinity labels, which are assigned to hosts
# which names start with C(west) or VMs which names start with C(postgres):
- ovirt_affinity_label_facts:
host: west*
vm: postgres*
- debug:
var: affinity_labels
'''
RETURN = '''
ovirt_affinity_labels:
description: "List of dictionaries describing the affinity labels. Affinity labels attribues are mapped to dictionary keys,
all affinity labels attributes can be found at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/affinity_label."
returned: On success.
type: list
'''
import fnmatch
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_facts_full_argument_spec,
)
def main():
argument_spec = ovirt_facts_full_argument_spec(
name=dict(default=None),
host=dict(default=None),
vm=dict(default=None),
)
module = AnsibleModule(argument_spec)
if module._name == 'ovirt_affinity_labels_facts':
module.deprecate("The 'ovirt_affinity_labels_facts' module is being renamed 'ovirt_affinity_label_facts'", version=2.8)
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
affinity_labels_service = connection.system_service().affinity_labels_service()
labels = []
all_labels = affinity_labels_service.list()
if module.params['name']:
labels.extend([
l for l in all_labels
if fnmatch.fnmatch(l.name, module.params['name'])
])
if module.params['host']:
hosts_service = connection.system_service().hosts_service()
labels.extend([
label
for label in all_labels
for host in connection.follow_link(label.hosts)
if fnmatch.fnmatch(hosts_service.service(host.id).get().name, module.params['host'])
])
if module.params['vm']:
vms_service = connection.system_service().vms_service()
labels.extend([
label
for label in all_labels
for vm in connection.follow_link(label.vms)
if fnmatch.fnmatch(vms_service.service(vm.id).get().name, module.params['vm'])
])
if not (module.params['vm'] or module.params['host'] or module.params['name']):
labels = all_labels
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt_affinity_labels=[
get_dict_of_struct(
struct=l,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for l in labels
],
),
)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
| gpl-3.0 |
themrmax/scikit-learn | sklearn/linear_model/omp.py | 8 | 31640 | """Orthogonal matching pursuit algorithms
"""
# Author: Vlad Niculae
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import linalg
from scipy.linalg.lapack import get_lapack_funcs
from .base import LinearModel, _pre_fit
from ..base import RegressorMixin
from ..utils import as_float_array, check_array, check_X_y
from ..model_selection import check_cv
from ..externals.joblib import Parallel, delayed
solve_triangular_args = {'check_finite': False}
premature = """ Orthogonal matching pursuit ended prematurely due to linear
dependence in the dictionary. The requested precision might not have been met.
"""
def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True,
return_path=False):
"""Orthogonal Matching Pursuit step using the Cholesky decomposition.
Parameters
----------
X : array, shape (n_samples, n_features)
Input dictionary. Columns are assumed to have unit norm.
y : array, shape (n_samples,)
Input targets
n_nonzero_coefs : int
Targeted number of non-zero elements
tol : float
Targeted squared error, if not None overrides n_nonzero_coefs.
copy_X : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
Returns
-------
gamma : array, shape (n_nonzero_coefs,)
Non-zero elements of the solution
idx : array, shape (n_nonzero_coefs,)
Indices of the positions of the elements in gamma within the solution
vector
coef : array, shape (n_features, n_nonzero_coefs)
The first k values of column k correspond to the coefficient value
for the active features at that step. The lower left triangle contains
garbage. Only returned if ``return_path=True``.
n_active : int
Number of active features at convergence.
"""
if copy_X:
X = X.copy('F')
else: # even if we are allowed to overwrite, still copy it if bad order
X = np.asfortranarray(X)
min_float = np.finfo(X.dtype).eps
nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (X,))
potrs, = get_lapack_funcs(('potrs',), (X,))
alpha = np.dot(X.T, y)
residual = y
gamma = np.empty(0)
n_active = 0
indices = np.arange(X.shape[1]) # keeping track of swapping
max_features = X.shape[1] if tol is not None else n_nonzero_coefs
if solve_triangular_args:
# new scipy, don't need to initialize because check_finite=False
L = np.empty((max_features, max_features), dtype=X.dtype)
else:
# old scipy, we need the garbage upper triangle to be non-Inf
L = np.zeros((max_features, max_features), dtype=X.dtype)
L[0, 0] = 1.
if return_path:
coefs = np.empty_like(L)
while True:
lam = np.argmax(np.abs(np.dot(X.T, residual)))
if lam < n_active or alpha[lam] ** 2 < min_float:
# atom already selected or inner product too small
warnings.warn(premature, RuntimeWarning, stacklevel=2)
break
if n_active > 0:
# Updates the Cholesky decomposition of X' X
L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam])
linalg.solve_triangular(L[:n_active, :n_active],
L[n_active, :n_active],
trans=0, lower=1,
overwrite_b=True,
**solve_triangular_args)
v = nrm2(L[n_active, :n_active]) ** 2
if 1 - v <= min_float: # selected atoms are dependent
warnings.warn(premature, RuntimeWarning, stacklevel=2)
break
L[n_active, n_active] = np.sqrt(1 - v)
X.T[n_active], X.T[lam] = swap(X.T[n_active], X.T[lam])
alpha[n_active], alpha[lam] = alpha[lam], alpha[n_active]
indices[n_active], indices[lam] = indices[lam], indices[n_active]
n_active += 1
# solves LL'x = y as a composition of two triangular systems
gamma, _ = potrs(L[:n_active, :n_active], alpha[:n_active], lower=True,
overwrite_b=False)
if return_path:
coefs[:n_active, n_active - 1] = gamma
residual = y - np.dot(X[:, :n_active], gamma)
if tol is not None and nrm2(residual) ** 2 <= tol:
break
elif n_active == max_features:
break
if return_path:
return gamma, indices[:n_active], coefs[:, :n_active], n_active
else:
return gamma, indices[:n_active], n_active
def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None,
copy_Gram=True, copy_Xy=True, return_path=False):
"""Orthogonal Matching Pursuit step on a precomputed Gram matrix.
This function uses the Cholesky decomposition method.
Parameters
----------
Gram : array, shape (n_features, n_features)
Gram matrix of the input data matrix
Xy : array, shape (n_features,)
Input targets
n_nonzero_coefs : int
Targeted number of non-zero elements
tol_0 : float
Squared norm of y, required if tol is not None.
tol : float
Targeted squared error, if not None overrides n_nonzero_coefs.
copy_Gram : bool, optional
Whether the gram matrix must be copied by the algorithm. A false
value is only helpful if it is already Fortran-ordered, otherwise a
copy is made anyway.
copy_Xy : bool, optional
Whether the covariance vector Xy must be copied by the algorithm.
If False, it may be overwritten.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
Returns
-------
gamma : array, shape (n_nonzero_coefs,)
Non-zero elements of the solution
idx : array, shape (n_nonzero_coefs,)
Indices of the positions of the elements in gamma within the solution
vector
coefs : array, shape (n_features, n_nonzero_coefs)
The first k values of column k correspond to the coefficient value
for the active features at that step. The lower left triangle contains
garbage. Only returned if ``return_path=True``.
n_active : int
Number of active features at convergence.
"""
Gram = Gram.copy('F') if copy_Gram else np.asfortranarray(Gram)
if copy_Xy:
Xy = Xy.copy()
min_float = np.finfo(Gram.dtype).eps
nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (Gram,))
potrs, = get_lapack_funcs(('potrs',), (Gram,))
indices = np.arange(len(Gram)) # keeping track of swapping
alpha = Xy
tol_curr = tol_0
delta = 0
gamma = np.empty(0)
n_active = 0
max_features = len(Gram) if tol is not None else n_nonzero_coefs
if solve_triangular_args:
# new scipy, don't need to initialize because check_finite=False
L = np.empty((max_features, max_features), dtype=Gram.dtype)
else:
# old scipy, we need the garbage upper triangle to be non-Inf
L = np.zeros((max_features, max_features), dtype=Gram.dtype)
L[0, 0] = 1.
if return_path:
coefs = np.empty_like(L)
while True:
lam = np.argmax(np.abs(alpha))
if lam < n_active or alpha[lam] ** 2 < min_float:
# selected same atom twice, or inner product too small
warnings.warn(premature, RuntimeWarning, stacklevel=3)
break
if n_active > 0:
L[n_active, :n_active] = Gram[lam, :n_active]
linalg.solve_triangular(L[:n_active, :n_active],
L[n_active, :n_active],
trans=0, lower=1,
overwrite_b=True,
**solve_triangular_args)
v = nrm2(L[n_active, :n_active]) ** 2
if 1 - v <= min_float: # selected atoms are dependent
warnings.warn(premature, RuntimeWarning, stacklevel=3)
break
L[n_active, n_active] = np.sqrt(1 - v)
Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam])
Gram.T[n_active], Gram.T[lam] = swap(Gram.T[n_active], Gram.T[lam])
indices[n_active], indices[lam] = indices[lam], indices[n_active]
Xy[n_active], Xy[lam] = Xy[lam], Xy[n_active]
n_active += 1
# solves LL'x = y as a composition of two triangular systems
gamma, _ = potrs(L[:n_active, :n_active], Xy[:n_active], lower=True,
overwrite_b=False)
if return_path:
coefs[:n_active, n_active - 1] = gamma
beta = np.dot(Gram[:, :n_active], gamma)
alpha = Xy - beta
if tol is not None:
tol_curr += delta
delta = np.inner(gamma, beta[:n_active])
tol_curr -= delta
if abs(tol_curr) <= tol:
break
elif n_active == max_features:
break
if return_path:
return gamma, indices[:n_active], coefs[:, :n_active], n_active
else:
return gamma, indices[:n_active], n_active
def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute=False,
copy_X=True, return_path=False,
return_n_iter=False):
"""Orthogonal Matching Pursuit (OMP)
Solves n_targets Orthogonal Matching Pursuit problems.
An instance of the problem has the form:
When parametrized by the number of non-zero coefficients using
`n_nonzero_coefs`:
argmin ||y - X\gamma||^2 subject to ||\gamma||_0 <= n_{nonzero coefs}
When parametrized by error using the parameter `tol`:
argmin ||\gamma||_0 subject to ||y - X\gamma||^2 <= tol
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
X : array, shape (n_samples, n_features)
Input data. Columns are assumed to have unit norm.
y : array, shape (n_samples,) or (n_samples, n_targets)
Input targets
n_nonzero_coefs : int
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
precompute : {True, False, 'auto'},
Whether to perform precomputations. Improves performance when n_targets
or n_samples is very large.
copy_X : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
return_n_iter : bool, optional default False
Whether or not to return the number of iterations.
Returns
-------
coef : array, shape (n_features,) or (n_features, n_targets)
Coefficients of the OMP solution. If `return_path=True`, this contains
the whole coefficient path. In this case its shape is
(n_features, n_features) or (n_features, n_targets, n_features) and
iterating over the last axis yields coefficients in increasing order
of active features.
n_iters : array-like or int
Number of active features across every target. Returned only if
`return_n_iter` is set to True.
See also
--------
OrthogonalMatchingPursuit
orthogonal_mp_gram
lars_path
decomposition.sparse_encode
Notes
-----
Orthogonal matching pursuit was introduced in S. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
"""
X = check_array(X, order='F', copy=copy_X)
copy_X = False
if y.ndim == 1:
y = y.reshape(-1, 1)
y = check_array(y)
if y.shape[1] > 1: # subsequent targets will be affected
copy_X = True
if n_nonzero_coefs is None and tol is None:
# default for n_nonzero_coefs is 0.1 * n_features
# but at least one.
n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1)
if tol is not None and tol < 0:
raise ValueError("Epsilon cannot be negative")
if tol is None and n_nonzero_coefs <= 0:
raise ValueError("The number of atoms must be positive")
if tol is None and n_nonzero_coefs > X.shape[1]:
raise ValueError("The number of atoms cannot be more than the number "
"of features")
if precompute == 'auto':
precompute = X.shape[0] > X.shape[1]
if precompute:
G = np.dot(X.T, X)
G = np.asfortranarray(G)
Xy = np.dot(X.T, y)
if tol is not None:
norms_squared = np.sum((y ** 2), axis=0)
else:
norms_squared = None
return orthogonal_mp_gram(G, Xy, n_nonzero_coefs, tol, norms_squared,
copy_Gram=copy_X, copy_Xy=False,
return_path=return_path)
if return_path:
coef = np.zeros((X.shape[1], y.shape[1], X.shape[1]))
else:
coef = np.zeros((X.shape[1], y.shape[1]))
n_iters = []
for k in range(y.shape[1]):
out = _cholesky_omp(
X, y[:, k], n_nonzero_coefs, tol,
copy_X=copy_X, return_path=return_path)
if return_path:
_, idx, coefs, n_iter = out
coef = coef[:, :, :len(idx)]
for n_active, x in enumerate(coefs.T):
coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1]
else:
x, idx, n_iter = out
coef[idx, k] = x
n_iters.append(n_iter)
if y.shape[1] == 1:
n_iters = n_iters[0]
if return_n_iter:
return np.squeeze(coef), n_iters
else:
return np.squeeze(coef)
def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None,
norms_squared=None, copy_Gram=True,
copy_Xy=True, return_path=False,
return_n_iter=False):
"""Gram Orthogonal Matching Pursuit (OMP)
Solves n_targets Orthogonal Matching Pursuit problems using only
the Gram matrix X.T * X and the product X.T * y.
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
Gram : array, shape (n_features, n_features)
Gram matrix of the input data: X.T * X
Xy : array, shape (n_features,) or (n_features, n_targets)
Input targets multiplied by X: X.T * y
n_nonzero_coefs : int
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
norms_squared : array-like, shape (n_targets,)
Squared L2 norms of the lines of y. Required if tol is not None.
copy_Gram : bool, optional
Whether the gram matrix must be copied by the algorithm. A false
value is only helpful if it is already Fortran-ordered, otherwise a
copy is made anyway.
copy_Xy : bool, optional
Whether the covariance vector Xy must be copied by the algorithm.
If False, it may be overwritten.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
return_n_iter : bool, optional default False
Whether or not to return the number of iterations.
Returns
-------
coef : array, shape (n_features,) or (n_features, n_targets)
Coefficients of the OMP solution. If `return_path=True`, this contains
the whole coefficient path. In this case its shape is
(n_features, n_features) or (n_features, n_targets, n_features) and
iterating over the last axis yields coefficients in increasing order
of active features.
n_iters : array-like or int
Number of active features across every target. Returned only if
`return_n_iter` is set to True.
See also
--------
OrthogonalMatchingPursuit
orthogonal_mp
lars_path
decomposition.sparse_encode
Notes
-----
Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
"""
Gram = check_array(Gram, order='F', copy=copy_Gram)
Xy = np.asarray(Xy)
if Xy.ndim > 1 and Xy.shape[1] > 1:
# or subsequent target will be affected
copy_Gram = True
if Xy.ndim == 1:
Xy = Xy[:, np.newaxis]
if tol is not None:
norms_squared = [norms_squared]
if n_nonzero_coefs is None and tol is None:
n_nonzero_coefs = int(0.1 * len(Gram))
if tol is not None and norms_squared is None:
raise ValueError('Gram OMP needs the precomputed norms in order '
'to evaluate the error sum of squares.')
if tol is not None and tol < 0:
raise ValueError("Epsilon cannot be negative")
if tol is None and n_nonzero_coefs <= 0:
raise ValueError("The number of atoms must be positive")
if tol is None and n_nonzero_coefs > len(Gram):
raise ValueError("The number of atoms cannot be more than the number "
"of features")
if return_path:
coef = np.zeros((len(Gram), Xy.shape[1], len(Gram)))
else:
coef = np.zeros((len(Gram), Xy.shape[1]))
n_iters = []
for k in range(Xy.shape[1]):
out = _gram_omp(
Gram, Xy[:, k], n_nonzero_coefs,
norms_squared[k] if tol is not None else None, tol,
copy_Gram=copy_Gram, copy_Xy=copy_Xy,
return_path=return_path)
if return_path:
_, idx, coefs, n_iter = out
coef = coef[:, :, :len(idx)]
for n_active, x in enumerate(coefs.T):
coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1]
else:
x, idx, n_iter = out
coef[idx, k] = x
n_iters.append(n_iter)
if Xy.shape[1] == 1:
n_iters = n_iters[0]
if return_n_iter:
return np.squeeze(coef), n_iters
else:
return np.squeeze(coef)
class OrthogonalMatchingPursuit(LinearModel, RegressorMixin):
"""Orthogonal Matching Pursuit model (OMP)
Parameters
----------
n_nonzero_coefs : int, optional
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float, optional
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
fit_intercept : boolean, optional
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default True
This parameter is ignored when ``fit_intercept`` is set to False.
If True, the regressors X will be normalized before regression by
subtracting the mean and dividing by the l2-norm.
If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.
precompute : {True, False, 'auto'}, default 'auto'
Whether to use a precomputed Gram and Xy matrix to speed up
calculations. Improves performance when `n_targets` or `n_samples` is
very large. Note that if you already have such matrices, you can pass
them directly to the fit method.
Read more in the :ref:`User Guide <omp>`.
Attributes
----------
coef_ : array, shape (n_features,) or (n_targets, n_features)
parameter vector (w in the formula)
intercept_ : float or array, shape (n_targets,)
independent term in decision function.
n_iter_ : int or array-like
Number of active features across every target.
Notes
-----
Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
See also
--------
orthogonal_mp
orthogonal_mp_gram
lars_path
Lars
LassoLars
decomposition.sparse_encode
"""
def __init__(self, n_nonzero_coefs=None, tol=None, fit_intercept=True,
normalize=True, precompute='auto'):
self.n_nonzero_coefs = n_nonzero_coefs
self.tol = tol
self.fit_intercept = fit_intercept
self.normalize = normalize
self.precompute = precompute
def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,) or (n_samples, n_targets)
Target values.
Returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
n_features = X.shape[1]
X, y, X_offset, y_offset, X_scale, Gram, Xy = \
_pre_fit(X, y, None, self.precompute, self.normalize,
self.fit_intercept, copy=True)
if y.ndim == 1:
y = y[:, np.newaxis]
if self.n_nonzero_coefs is None and self.tol is None:
# default for n_nonzero_coefs is 0.1 * n_features
# but at least one.
self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1)
else:
self.n_nonzero_coefs_ = self.n_nonzero_coefs
if Gram is False:
coef_, self.n_iter_ = orthogonal_mp(
X, y, self.n_nonzero_coefs_, self.tol,
precompute=False, copy_X=True,
return_n_iter=True)
else:
norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None
coef_, self.n_iter_ = orthogonal_mp_gram(
Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_,
tol=self.tol, norms_squared=norms_sq,
copy_Gram=True, copy_Xy=True,
return_n_iter=True)
self.coef_ = coef_.T
self._set_intercept(X_offset, y_offset, X_scale)
return self
def _omp_path_residues(X_train, y_train, X_test, y_test, copy=True,
fit_intercept=True, normalize=True, max_iter=100):
"""Compute the residues on left-out data for a full LARS path
Parameters
-----------
X_train : array, shape (n_samples, n_features)
The data to fit the LARS on
y_train : array, shape (n_samples)
The target variable to fit LARS on
X_test : array, shape (n_samples, n_features)
The data to compute the residues on
y_test : array, shape (n_samples)
The target variable to compute the residues on
copy : boolean, optional
Whether X_train, X_test, y_train and y_test should be copied. If
False, they may be overwritten.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default True
This parameter is ignored when ``fit_intercept`` is set to False.
If True, the regressors X will be normalized before regression by
subtracting the mean and dividing by the l2-norm.
If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 100 by default.
Returns
-------
residues : array, shape (n_samples, max_features)
Residues of the prediction on the test data
"""
if copy:
X_train = X_train.copy()
y_train = y_train.copy()
X_test = X_test.copy()
y_test = y_test.copy()
if fit_intercept:
X_mean = X_train.mean(axis=0)
X_train -= X_mean
X_test -= X_mean
y_mean = y_train.mean(axis=0)
y_train = as_float_array(y_train, copy=False)
y_train -= y_mean
y_test = as_float_array(y_test, copy=False)
y_test -= y_mean
if normalize:
norms = np.sqrt(np.sum(X_train ** 2, axis=0))
nonzeros = np.flatnonzero(norms)
X_train[:, nonzeros] /= norms[nonzeros]
coefs = orthogonal_mp(X_train, y_train, n_nonzero_coefs=max_iter, tol=None,
precompute=False, copy_X=False,
return_path=True)
if coefs.ndim == 1:
coefs = coefs[:, np.newaxis]
if normalize:
coefs[nonzeros] /= norms[nonzeros][:, np.newaxis]
return np.dot(coefs.T, X_test.T) - y_test
class OrthogonalMatchingPursuitCV(LinearModel, RegressorMixin):
"""Cross-validated Orthogonal Matching Pursuit model (OMP)
Parameters
----------
copy : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
fit_intercept : boolean, optional
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default True
This parameter is ignored when ``fit_intercept`` is set to False.
If True, the regressors X will be normalized before regression by
subtracting the mean and dividing by the l2-norm.
If you wish to standardize, please use
:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``
on an estimator with ``normalize=False``.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 10% of ``n_features`` but at least 5 if available.
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, :class:`KFold` is used.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validation strategies that can be used here.
n_jobs : integer, optional
Number of CPUs to use during the cross validation. If ``-1``, use
all the CPUs
verbose : boolean or integer, optional
Sets the verbosity amount
Read more in the :ref:`User Guide <omp>`.
Attributes
----------
intercept_ : float or array, shape (n_targets,)
Independent term in decision function.
coef_ : array, shape (n_features,) or (n_targets, n_features)
Parameter vector (w in the problem formulation).
n_nonzero_coefs_ : int
Estimated number of non-zero coefficients giving the best mean squared
error over the cross-validation folds.
n_iter_ : int or array-like
Number of active features across every target for the model refit with
the best hyperparameters got by cross-validating across all folds.
See also
--------
orthogonal_mp
orthogonal_mp_gram
lars_path
Lars
LassoLars
OrthogonalMatchingPursuit
LarsCV
LassoLarsCV
decomposition.sparse_encode
"""
def __init__(self, copy=True, fit_intercept=True, normalize=True,
max_iter=None, cv=None, n_jobs=1, verbose=False):
self.copy = copy
self.fit_intercept = fit_intercept
self.normalize = normalize
self.max_iter = max_iter
self.cv = cv
self.n_jobs = n_jobs
self.verbose = verbose
def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Training data.
y : array-like, shape [n_samples]
Target values.
Returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, y_numeric=True, ensure_min_features=2,
estimator=self)
X = as_float_array(X, copy=False, force_all_finite=False)
cv = check_cv(self.cv, classifier=False)
max_iter = (min(max(int(0.1 * X.shape[1]), 5), X.shape[1])
if not self.max_iter
else self.max_iter)
cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
delayed(_omp_path_residues)(
X[train], y[train], X[test], y[test], self.copy,
self.fit_intercept, self.normalize, max_iter)
for train, test in cv.split(X))
min_early_stop = min(fold.shape[0] for fold in cv_paths)
mse_folds = np.array([(fold[:min_early_stop] ** 2).mean(axis=1)
for fold in cv_paths])
best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1
self.n_nonzero_coefs_ = best_n_nonzero_coefs
omp = OrthogonalMatchingPursuit(n_nonzero_coefs=best_n_nonzero_coefs,
fit_intercept=self.fit_intercept,
normalize=self.normalize)
omp.fit(X, y)
self.coef_ = omp.coef_
self.intercept_ = omp.intercept_
self.n_iter_ = omp.n_iter_
return self
| bsd-3-clause |
tylertian/Openstack | openstack F/glance/glance/openstack/common/policy.py | 1 | 9320 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Common Policy Engine Implementation"""
import logging
import urllib
import urllib2
from glance.openstack.common.gettextutils import _
from glance.openstack.common import jsonutils
LOG = logging.getLogger(__name__)
_BRAIN = None
def set_brain(brain):
"""Set the brain used by enforce().
Defaults use Brain() if not set.
"""
global _BRAIN
_BRAIN = brain
def reset():
"""Clear the brain used by enforce()."""
global _BRAIN
_BRAIN = None
def enforce(match_list, target_dict, credentials_dict, exc=None,
*args, **kwargs):
"""Enforces authorization of some rules against credentials.
:param match_list: nested tuples of data to match against
The basic brain supports three types of match lists:
1) rules
looks like: ``('rule:compute:get_instance',)``
Retrieves the named rule from the rules dict and recursively
checks against the contents of the rule.
2) roles
looks like: ``('role:compute:admin',)``
Matches if the specified role is in credentials_dict['roles'].
3) generic
looks like: ``('tenant_id:%(tenant_id)s',)``
Substitutes values from the target dict into the match using
the % operator and matches them against the creds dict.
Combining rules:
The brain returns True if any of the outer tuple of rules
match and also True if all of the inner tuples match. You
can use this to perform simple boolean logic. For
example, the following rule would return True if the creds
contain the role 'admin' OR the if the tenant_id matches
the target dict AND the the creds contains the role
'compute_sysadmin':
::
{
"rule:combined": (
'role:admin',
('tenant_id:%(tenant_id)s', 'role:compute_sysadmin')
)
}
Note that rule and role are reserved words in the credentials match, so
you can't match against properties with those names. Custom brains may
also add new reserved words. For example, the HttpBrain adds http as a
reserved word.
:param target_dict: dict of object properties
Target dicts contain as much information as we can about the object being
operated on.
:param credentials_dict: dict of actor properties
Credentials dicts contain as much information as we can about the user
performing the action.
:param exc: exception to raise
Class of the exception to raise if the check fails. Any remaining
arguments passed to enforce() (both positional and keyword arguments)
will be passed to the exception class. If exc is not provided, returns
False.
:return: True if the policy allows the action
:return: False if the policy does not allow the action and exc is not set
"""
global _BRAIN
if not _BRAIN:
_BRAIN = Brain()
if not _BRAIN.check(match_list, target_dict, credentials_dict):
if exc:
raise exc(*args, **kwargs)
return False
return True
class Brain(object):
"""Implements policy checking."""
_checks = {}
@classmethod
def _register(cls, name, func):
cls._checks[name] = func
@classmethod
def load_json(cls, data, default_rule=None):
"""Init a brain using json instead of a rules dictionary."""
rules_dict = jsonutils.loads(data)
return cls(rules=rules_dict, default_rule=default_rule)
def __init__(self, rules=None, default_rule=None):
if self.__class__ != Brain:
LOG.warning(_("Inheritance-based rules are deprecated; use "
"the default brain instead of %s.") %
self.__class__.__name__)
self.rules = rules or {}
self.default_rule = default_rule
def add_rule(self, key, match):
self.rules[key] = match
def _check(self, match, target_dict, cred_dict):
try:
match_kind, match_value = match.split(':', 1)
except Exception:
LOG.exception(_("Failed to understand rule %(match)r") % locals())
# If the rule is invalid, fail closed
return False
func = None
try:
old_func = getattr(self, '_check_%s' % match_kind)
except AttributeError:
func = self._checks.get(match_kind, self._checks.get(None, None))
else:
LOG.warning(_("Inheritance-based rules are deprecated; update "
"_check_%s") % match_kind)
func = (lambda brain, kind, value, target, cred:
old_func(value, target, cred))
if not func:
LOG.error(_("No handler for matches of kind %s") % match_kind)
# Fail closed
return False
return func(self, match_kind, match_value, target_dict, cred_dict)
def check(self, match_list, target_dict, cred_dict):
"""Checks authorization of some rules against credentials.
Detailed description of the check with examples in policy.enforce().
:param match_list: nested tuples of data to match against
:param target_dict: dict of object properties
:param credentials_dict: dict of actor properties
:returns: True if the check passes
"""
if not match_list:
return True
for and_list in match_list:
if isinstance(and_list, basestring):
and_list = (and_list,)
if all([self._check(item, target_dict, cred_dict)
for item in and_list]):
return True
return False
class HttpBrain(Brain):
"""A brain that can check external urls for policy.
Posts json blobs for target and credentials.
Note that this brain is deprecated; the http check is registered
by default.
"""
pass
def register(name, func=None):
"""
Register a function as a policy check.
:param name: Gives the name of the check type, e.g., 'rule',
'role', etc. If name is None, a default function
will be registered.
:param func: If given, provides the function to register. If not
given, returns a function taking one argument to
specify the function to register, allowing use as a
decorator.
"""
# Perform the actual decoration by registering the function.
# Returns the function for compliance with the decorator
# interface.
def decorator(func):
# Register the function
Brain._register(name, func)
return func
# If the function is given, do the registration
if func:
return decorator(func)
return decorator
@register("rule")
def _check_rule(brain, match_kind, match, target_dict, cred_dict):
"""Recursively checks credentials based on the brains rules."""
try:
new_match_list = brain.rules[match]
except KeyError:
if brain.default_rule and match != brain.default_rule:
new_match_list = ('rule:%s' % brain.default_rule,)
else:
return False
return brain.check(new_match_list, target_dict, cred_dict)
@register("role")
def _check_role(brain, match_kind, match, target_dict, cred_dict):
"""Check that there is a matching role in the cred dict."""
return match.lower() in [x.lower() for x in cred_dict['roles']]
@register('http')
def _check_http(brain, match_kind, match, target_dict, cred_dict):
"""Check http: rules by calling to a remote server.
This example implementation simply verifies that the response is
exactly 'True'. A custom brain using response codes could easily
be implemented.
"""
url = 'http:' + (match % target_dict)
data = {'target': jsonutils.dumps(target_dict),
'credentials': jsonutils.dumps(cred_dict)}
post_data = urllib.urlencode(data)
f = urllib2.urlopen(url, post_data)
return f.read() == "True"
@register(None)
def _check_generic(brain, match_kind, match, target_dict, cred_dict):
"""Check an individual match.
Matches look like:
tenant:%(tenant_id)s
role:compute:admin
"""
# TODO(termie): do dict inspection via dot syntax
match = match % target_dict
if match_kind in cred_dict:
return match == unicode(cred_dict[match_kind])
return False
| apache-2.0 |
nwiizo/workspace_2017 | pipng/pointstore1.py | 2 | 1602 | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or 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. It is provided for
# educational purposes and 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.
import sys
import time
def main():
regression = False
size = int(1e6)
if len(sys.argv) > 1 and sys.argv[1] == "-P":
regression = True
size = 20
start = time.clock()
points = []
for i in range(size):
points.append(Point(i, i ** 2, i // 2))
end = time.clock() - start
assert points[size - 1].x == size - 1
assert points[size - 1].color is None
print(len(points))
if not regression: # wait until we can see how much memory is used
print("took {} secs to create {:,} points".format(end, size))
input("press Enter to finish")
class Point:
__slots__ = ("x", "y", "z", "color")
def __init__(self, x=0, y=0, z=0, color=None):
self.x = x
self.y = y
self.z = z
self.color = color
def __repr__(self):
return "Point({0.x!r}, {0.y!r}, {0.z!r}, {0.color!r})".format(self)
if __name__ == "__main__":
main()
| mit |
phenoxim/cinder | cinder/volume/drivers/vmware/fcd.py | 3 | 12601 | # Copyright (c) 2017 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
VMware VStorageObject driver
Volume driver based on VMware VStorageObject aka First Class Disk (FCD). This
driver requires a minimum vCenter version of 6.5.
"""
from oslo_log import log as logging
from oslo_utils import units
from oslo_vmware import image_transfer
from oslo_vmware.objects import datastore
from oslo_vmware import vim_util
from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder.volume.drivers.vmware import datastore as hub
from cinder.volume.drivers.vmware import vmdk
from cinder.volume.drivers.vmware import volumeops as vops
LOG = logging.getLogger(__name__)
@interface.volumedriver
class VMwareVStorageObjectDriver(vmdk.VMwareVcVmdkDriver):
"""Volume driver based on VMware VStorageObject"""
# 1.0 - initial version based on vSphere 6.5 vStorageObject APIs
VERSION = '1.0.0'
# ThirdPartySystems wiki page
CI_WIKI_NAME = "VMware_CI"
# minimum supported vCenter version
MIN_SUPPORTED_VC_VERSION = '6.5'
STORAGE_TYPE = 'vstorageobject'
def do_setup(self, context):
"""Any initialization the volume driver needs to do while starting.
:param context: The admin context.
"""
super(VMwareVStorageObjectDriver, self).do_setup(context)
self._storage_policy_enabled = False
self.volumeops.set_vmx_version('vmx-13')
def get_volume_stats(self, refresh=False):
"""Collects volume backend stats.
:param refresh: Whether to discard any cached values and force a full
refresh of stats.
:returns: dict of appropriate values.
"""
stats = super(VMwareVStorageObjectDriver, self).get_volume_stats(
refresh=refresh)
stats['storage_protocol'] = self.STORAGE_TYPE
return stats
def _select_ds_fcd(self, volume):
req = {}
req[hub.DatastoreSelector.SIZE_BYTES] = volume.size * units.Gi
(_host_ref, _resource_pool, summary) = self._select_datastore(req)
return summary.datastore
def _get_temp_image_folder(self, size_bytes, preallocated=False):
req = {}
req[hub.DatastoreSelector.SIZE_BYTES] = size_bytes
if preallocated:
req[hub.DatastoreSelector.HARD_AFFINITY_DS_TYPE] = (
hub.DatastoreType.get_all_types() -
{hub.DatastoreType.VSAN, hub.DatastoreType.VVOL})
(host_ref, _resource_pool, summary) = self._select_datastore(req)
folder_path = vmdk.TMP_IMAGES_DATASTORE_FOLDER_PATH
dc_ref = self.volumeops.get_dc(host_ref)
self.volumeops.create_datastore_folder(
summary.name, folder_path, dc_ref)
return (dc_ref, summary, folder_path)
def _get_disk_type(self, volume):
extra_spec_disk_type = super(
VMwareVStorageObjectDriver, self)._get_disk_type(volume)
return vops.VirtualDiskType.get_virtual_disk_type(extra_spec_disk_type)
def create_volume(self, volume):
"""Create a new volume on the backend.
:param volume: Volume object containing specifics to create.
:returns: (Optional) dict of database updates for the new volume.
"""
disk_type = self._get_disk_type(volume)
ds_ref = self._select_ds_fcd(volume)
fcd_loc = self.volumeops.create_fcd(
volume.name, volume.size * units.Ki, ds_ref, disk_type)
return {'provider_location': fcd_loc.provider_location()}
def _delete_fcd(self, provider_loc):
fcd_loc = vops.FcdLocation.from_provider_location(provider_loc)
self.volumeops.delete_fcd(fcd_loc)
def delete_volume(self, volume):
"""Delete a volume from the backend.
:param volume: The volume to delete.
"""
self._delete_fcd(volume.provider_location)
def initialize_connection(self, volume, connector, initiator_data=None):
"""Allow connection to connector and return connection info.
:param volume: The volume to be attached.
:param connector: Dictionary containing information about what is being
connected to.
:param initiator_data: (Optional) A dictionary of driver_initiator_data
objects with key-value pairs that have been
saved for this initiator by a driver in previous
initialize_connection calls.
:returns: A dictionary of connection information.
"""
fcd_loc = vops.FcdLocation.from_provider_location(
volume.provider_location)
connection_info = {'driver_volume_type': self.STORAGE_TYPE}
connection_info['data'] = {
'id': fcd_loc.fcd_id,
'ds_ref_val': fcd_loc.ds_ref_val,
'adapter_type': self._get_adapter_type(volume)
}
LOG.debug("Connection info for volume %(name)s: %(connection_info)s.",
{'name': volume.name, 'connection_info': connection_info})
return connection_info
def _validate_container_format(self, container_format, image_id):
if container_format and container_format != 'bare':
msg = _("Container format: %s is unsupported, only 'bare' "
"is supported.") % container_format
LOG.error(msg)
raise exception.ImageUnacceptable(image_id=image_id, reason=msg)
def copy_image_to_volume(self, context, volume, image_service, image_id):
"""Fetch the image from image_service and write it to the volume.
:param context: Security/policy info for the request.
:param volume: The volume to create.
:param image_service: The image service to use.
:param image_id: The image identifier.
:returns: Model updates.
"""
metadata = image_service.show(context, image_id)
self._validate_disk_format(metadata['disk_format'])
self._validate_container_format(
metadata.get('container_format'), image_id)
properties = metadata['properties'] or {}
disk_type = properties.get('vmware_disktype',
vmdk.ImageDiskType.PREALLOCATED)
vmdk.ImageDiskType.validate(disk_type)
size_bytes = metadata['size']
dc_ref, summary, folder_path = self._get_temp_image_folder(
volume.size * units.Gi)
disk_name = volume.id
if disk_type in [vmdk.ImageDiskType.SPARSE,
vmdk.ImageDiskType.STREAM_OPTIMIZED]:
vmdk_path = self._create_virtual_disk_from_sparse_image(
context, image_service, image_id, size_bytes, dc_ref,
summary.name, folder_path, disk_name)
else:
vmdk_path = self._create_virtual_disk_from_preallocated_image(
context, image_service, image_id, size_bytes, dc_ref,
summary.name, folder_path, disk_name,
vops.VirtualDiskAdapterType.LSI_LOGIC)
ds_path = datastore.DatastorePath.parse(
vmdk_path.get_descriptor_ds_file_path())
dc_path = self.volumeops.get_inventory_path(dc_ref)
vmdk_url = datastore.DatastoreURL(
'https', self.configuration.vmware_host_ip, ds_path.rel_path,
dc_path, ds_path.datastore)
fcd_loc = self.volumeops.register_disk(
str(vmdk_url), volume.name, summary.datastore)
return {'provider_location': fcd_loc.provider_location()}
def copy_volume_to_image(self, context, volume, image_service, image_meta):
"""Copy the volume to the specified image.
:param context: Security/policy info for the request.
:param volume: The volume to copy.
:param image_service: The image service to use.
:param image_meta: Information about the image.
:returns: Model updates.
"""
self._validate_disk_format(image_meta['disk_format'])
fcd_loc = vops.FcdLocation.from_provider_location(
volume.provider_location)
hosts = self.volumeops.get_connected_hosts(fcd_loc.ds_ref())
host = vim_util.get_moref(hosts[0], 'HostSystem')
LOG.debug("Selected host: %(host)s for downloading fcd: %(fcd_loc)s.",
{'host': host, 'fcd_loc': fcd_loc})
attached = False
try:
create_params = {vmdk.CREATE_PARAM_DISK_LESS: True}
backing = self._create_backing(volume, host, create_params)
self.volumeops.attach_fcd(backing, fcd_loc)
attached = True
vmdk_file_path = self.volumeops.get_vmdk_path(backing)
conf = self.configuration
image_transfer.upload_image(
context,
conf.vmware_image_transfer_timeout_secs,
image_service,
image_meta['id'],
volume.project_id,
session=self.session,
host=conf.vmware_host_ip,
port=conf.vmware_host_port,
vm=backing,
vmdk_file_path=vmdk_file_path,
vmdk_size=volume.size * units.Gi,
image_name=image_meta['name'])
finally:
if attached:
self.volumeops.detach_fcd(backing, fcd_loc)
backing = self.volumeops.get_backing_by_uuid(volume.id)
if backing:
self._delete_temp_backing(backing)
def extend_volume(self, volume, new_size):
"""Extend the size of a volume.
:param volume: The volume to extend.
:param new_size: The new desired size of the volume.
"""
fcd_loc = vops.FcdLocation.from_provider_location(
volume.provider_location)
self.volumeops.extend_fcd(fcd_loc, new_size * units.Ki)
def _clone_fcd(self, provider_loc, name, dest_ds_ref,
disk_type=vops.VirtualDiskType.THIN):
fcd_loc = vops.FcdLocation.from_provider_location(provider_loc)
return self.volumeops.clone_fcd(name, fcd_loc, dest_ds_ref, disk_type)
def create_snapshot(self, snapshot):
"""Creates a snapshot.
:param snapshot: Information for the snapshot to be created.
"""
ds_ref = self._select_ds_fcd(snapshot.volume)
cloned_fcd_loc = self._clone_fcd(
snapshot.volume.provider_location, snapshot.name, ds_ref)
return {'provider_location': cloned_fcd_loc.provider_location()}
def delete_snapshot(self, snapshot):
"""Deletes a snapshot.
:param snapshot: The snapshot to delete.
"""
self._delete_fcd(snapshot.provider_location)
def _extend_if_needed(self, fcd_loc, cur_size, new_size):
if new_size > cur_size:
self.volumeops.extend_fcd(fcd_loc, new_size * units.Ki)
def _create_volume_from_fcd(self, provider_loc, cur_size, volume):
ds_ref = self._select_ds_fcd(volume)
disk_type = self._get_disk_type(volume)
cloned_fcd_loc = self._clone_fcd(
provider_loc, volume.name, ds_ref, disk_type=disk_type)
self._extend_if_needed(cloned_fcd_loc, cur_size, volume.size)
return {'provider_location': cloned_fcd_loc.provider_location()}
def create_volume_from_snapshot(self, volume, snapshot):
"""Creates a volume from a snapshot.
:param volume: The volume to be created.
:param snapshot: The snapshot from which to create the volume.
:returns: A dict of database updates for the new volume.
"""
return self._create_volume_from_fcd(
snapshot.provider_location, snapshot.volume.size, volume)
def create_cloned_volume(self, volume, src_vref):
"""Creates a clone of the specified volume.
:param volume: New Volume object
:param src_vref: Source Volume object
"""
return self._create_volume_from_fcd(
src_vref.provider_location, src_vref.size, volume)
| apache-2.0 |
abhattad4/Digi-Menu | digimenu2/build/lib.linux-x86_64-2.7/django/contrib/sitemaps/__init__.py | 84 | 6499 | import warnings
from django.apps import apps as django_apps
from django.conf import settings
from django.core import urlresolvers, paginator
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.six.moves.urllib.parse import urlencode
from django.utils.six.moves.urllib.request import urlopen
PING_URL = "http://www.google.com/webmasters/tools/ping"
class SitemapNotFound(Exception):
pass
def ping_google(sitemap_url=None, ping_url=PING_URL):
"""
Alerts Google that the sitemap for the current site has been updated.
If sitemap_url is provided, it should be an absolute path to the sitemap
for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
function will attempt to deduce it by using urlresolvers.reverse().
"""
if sitemap_url is None:
try:
# First, try to get the "index" sitemap URL.
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
# Next, try for the "global" sitemap URL.
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if sitemap_url is None:
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
if not django_apps.is_installed('django.contrib.sites'):
raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")
Site = django_apps.get_model('sites.Site')
current_site = Site.objects.get_current()
url = "http://%s%s" % (current_site.domain, sitemap_url)
params = urlencode({'sitemap': url})
urlopen("%s?%s" % (ping_url, params))
class Sitemap(object):
# This limit is defined by Google. See the index documentation at
# http://sitemaps.org/protocol.php#index.
limit = 50000
# If protocol is None, the URLs in the sitemap will use the protocol
# with which the sitemap was requested.
protocol = None
def __get(self, name, obj, default=None):
try:
attr = getattr(self, name)
except AttributeError:
return default
if callable(attr):
return attr(obj)
return attr
def items(self):
return []
def location(self, obj):
return obj.get_absolute_url()
def _get_paginator(self):
return paginator.Paginator(self.items(), self.limit)
paginator = property(_get_paginator)
def get_urls(self, page=1, site=None, protocol=None):
# Determine protocol
if self.protocol is not None:
protocol = self.protocol
if protocol is None:
protocol = 'http'
# Determine domain
if site is None:
if django_apps.is_installed('django.contrib.sites'):
Site = django_apps.get_model('sites.Site')
try:
site = Site.objects.get_current()
except Site.DoesNotExist:
pass
if site is None:
raise ImproperlyConfigured(
"To use sitemaps, either enable the sites framework or pass "
"a Site/RequestSite object in your view."
)
domain = site.domain
if getattr(self, 'i18n', False):
urls = []
current_lang_code = translation.get_language()
for lang_code, lang_name in settings.LANGUAGES:
translation.activate(lang_code)
urls += self._urls(page, protocol, domain)
translation.activate(current_lang_code)
else:
urls = self._urls(page, protocol, domain)
return urls
def _urls(self, page, protocol, domain):
urls = []
latest_lastmod = None
all_items_lastmod = True # track if all items have a lastmod
for item in self.paginator.page(page).object_list:
loc = "%s://%s%s" % (protocol, domain, self.__get('location', item))
priority = self.__get('priority', item, None)
lastmod = self.__get('lastmod', item, None)
if all_items_lastmod:
all_items_lastmod = lastmod is not None
if (all_items_lastmod and
(latest_lastmod is None or lastmod > latest_lastmod)):
latest_lastmod = lastmod
url_info = {
'item': item,
'location': loc,
'lastmod': lastmod,
'changefreq': self.__get('changefreq', item, None),
'priority': str(priority if priority is not None else ''),
}
urls.append(url_info)
if all_items_lastmod and latest_lastmod:
self.latest_lastmod = latest_lastmod
return urls
class FlatPageSitemap(Sitemap):
# This class is not a subclass of
# django.contrib.flatpages.sitemaps.FlatPageSitemap to avoid a
# circular import problem.
def __init__(self):
warnings.warn(
"'django.contrib.sitemaps.FlatPageSitemap' is deprecated. "
"Use 'django.contrib.flatpages.sitemaps.FlatPageSitemap' instead.",
RemovedInDjango19Warning,
stacklevel=2
)
def items(self):
if not django_apps.is_installed('django.contrib.sites'):
raise ImproperlyConfigured("FlatPageSitemap requires django.contrib.sites, which isn't installed.")
Site = django_apps.get_model('sites.Site')
current_site = Site.objects.get_current()
return current_site.flatpage_set.filter(registration_required=False)
class GenericSitemap(Sitemap):
priority = None
changefreq = None
def __init__(self, info_dict, priority=None, changefreq=None):
self.queryset = info_dict['queryset']
self.date_field = info_dict.get('date_field', None)
self.priority = priority
self.changefreq = changefreq
def items(self):
# Make sure to return a clone; we don't want premature evaluation.
return self.queryset.filter()
def lastmod(self, item):
if self.date_field is not None:
return getattr(item, self.date_field)
return None
default_app_config = 'django.contrib.sitemaps.apps.SiteMapsConfig'
| bsd-3-clause |
seraphlnWu/wekka | wekka/wekka/themes/steward/models.py | 1 | 1530 | # coding=utf8
#
from datetime import datetime
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from memodels import SiteConfig as MSiteConfig
from memodels import Vendor as MVendor
from memodels import MCategory, MVideos
class SiteConfig(models.Model):
''' '''
site_title = models.CharField(max_length=32)
site_desc = RichTextField(verbose_name=u"站点信息")
site_keywords = models.CharField(max_length=128)
site_name = models.CharField(max_length=32)
site_url = models.CharField(max_length=255)
admin_email = models.EmailField()
icp_info = models.CharField(max_length=128)
show_icp = models.BooleanField(default=False)
third_analysis_code = RichTextField()
close_site = models.BooleanField(default=False)
class meta:
verbose_name = u"站点配置"
verbose_name_plural = u"站点配置"
def save(self, *args, **kwargs):
''' rewrite the save function '''
msc = MSiteConfig(site_title=self.site_title, site_desc=self.site_desc,
site_name=self.site_name, site_url=self.site_url,
admin_email=self.admin_email, icp_info=self.icp_info,
show_icp=self.show_icp, close_site=self.close_site,
third_analysis_code=self.third_analysis_code)
msc.site_keywords = self.site_keywords.split(',')
msc.save()
super(self.__class__, self).save(*args, **kwargs)
| gpl-2.0 |
shikhar413/openmc | openmc/filter.py | 6 | 63054 | from abc import ABCMeta
from collections import OrderedDict
from collections.abc import Iterable
import hashlib
from itertools import product
from numbers import Real, Integral
from xml.etree import ElementTree as ET
import numpy as np
import pandas as pd
import openmc
import openmc.checkvalue as cv
from .cell import Cell
from .material import Material
from .mixin import IDManagerMixin
from .surface import Surface
from .universe import Universe
_FILTER_TYPES = (
'universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy',
'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup',
'energyfunction', 'cellfrom', 'legendre', 'spatiallegendre',
'sphericalharmonics', 'zernike', 'zernikeradial', 'particle', 'cellinstance'
)
_CURRENT_NAMES = (
'x-min out', 'x-min in', 'x-max out', 'x-max in',
'y-min out', 'y-min in', 'y-max out', 'y-max in',
'z-min out', 'z-min in', 'z-max out', 'z-max in'
)
_PARTICLES = {'neutron', 'photon', 'electron', 'positron'}
class FilterMeta(ABCMeta):
"""Metaclass for filters that ensures class names are appropriate."""
def __new__(cls, name, bases, namespace, **kwargs):
# Check the class name.
required_suffix = 'Filter'
if not name.endswith(required_suffix):
raise ValueError("All filter class names must end with 'Filter'")
# Create a 'short_name' attribute that removes the 'Filter' suffix.
namespace['short_name'] = name[:-len(required_suffix)]
# Subclass methods can sort of inherit the docstring of parent class
# methods. If a function is defined without a docstring, most (all?)
# Python interpreters will search through the parent classes to see if
# there is a docstring for a function with the same name, and they will
# use that docstring. However, Sphinx does not have that functionality.
# This chunk of code handles this docstring inheritance manually so that
# the autodocumentation will pick it up.
if name != required_suffix:
# Look for newly-defined functions that were also in Filter.
for func_name in namespace:
if func_name in Filter.__dict__:
# Inherit the docstring from Filter if not defined.
if isinstance(namespace[func_name],
(classmethod, staticmethod)):
new_doc = namespace[func_name].__func__.__doc__
old_doc = Filter.__dict__[func_name].__func__.__doc__
if new_doc is None and old_doc is not None:
namespace[func_name].__func__.__doc__ = old_doc
else:
new_doc = namespace[func_name].__doc__
old_doc = Filter.__dict__[func_name].__doc__
if new_doc is None and old_doc is not None:
namespace[func_name].__doc__ = old_doc
# Make the class.
return super().__new__(cls, name, bases, namespace, **kwargs)
def _repeat_and_tile(bins, repeat_factor, data_size):
filter_bins = np.repeat(bins, repeat_factor)
tile_factor = data_size // len(filter_bins)
return np.tile(filter_bins, tile_factor)
class Filter(IDManagerMixin, metaclass=FilterMeta):
"""Tally modifier that describes phase-space and other characteristics.
Parameters
----------
bins : Integral or Iterable of Integral or Iterable of Real
The bins for the filter. This takes on different meaning for different
filters. See the docstrings for sublcasses of this filter or the online
documentation for more details.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Integral or Iterable of Integral or Iterable of Real
The bins for the filter
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
next_id = 1
used_ids = set()
def __init__(self, bins, filter_id=None):
self.bins = bins
self.id = filter_id
def __eq__(self, other):
if type(self) is not type(other):
return False
elif len(self.bins) != len(other.bins):
return False
else:
return np.allclose(self.bins, other.bins)
def __gt__(self, other):
if type(self) is not type(other):
if self.short_name in _FILTER_TYPES and \
other.short_name in _FILTER_TYPES:
delta = _FILTER_TYPES.index(self.short_name) - \
_FILTER_TYPES.index(other.short_name)
return delta > 0
else:
return False
else:
return max(self.bins) > max(other.bins)
def __lt__(self, other):
return not self > other
def __hash__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tBins', self.bins)
return hash(string)
def __repr__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tBins', self.bins)
string += '{: <16}=\t{}\n'.format('\tID', self.id)
return string
@classmethod
def _recursive_subclasses(cls):
"""Return all subclasses and their subclasses, etc."""
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(subclass._recursive_subclasses())
return all_subclasses
@classmethod
def from_hdf5(cls, group, **kwargs):
"""Construct a new Filter instance from HDF5 data.
Parameters
----------
group : h5py.Group
HDF5 group to read from
Keyword arguments
-----------------
meshes : dict
Dictionary mapping integer IDs to openmc.MeshBase objects. Only
used for openmc.MeshFilter objects.
"""
filter_id = int(group.name.split('/')[-1].lstrip('filter '))
# If the HDF5 'type' variable matches this class's short_name, then
# there is no overriden from_hdf5 method. Pass the bins to __init__.
if group['type'][()].decode() == cls.short_name.lower():
out = cls(group['bins'][()], filter_id=filter_id)
out._num_bins = group['n_bins'][()]
return out
# Search through all subclasses and find the one matching the HDF5
# 'type'. Call that class's from_hdf5 method.
for subclass in cls._recursive_subclasses():
if group['type'][()].decode() == subclass.short_name.lower():
return subclass.from_hdf5(group, **kwargs)
raise ValueError("Unrecognized Filter class: '"
+ group['type'][()].decode() + "'")
@property
def bins(self):
return self._bins
@bins.setter
def bins(self, bins):
self.check_bins(bins)
self._bins = bins
@property
def num_bins(self):
return len(self.bins)
def check_bins(self, bins):
"""Make sure given bins are valid for this filter.
Raises
------
TypeError
ValueError
"""
pass
def to_xml_element(self):
"""Return XML Element representing the Filter.
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing filter data
"""
element = ET.Element('filter')
element.set('id', str(self.id))
element.set('type', self.short_name.lower())
subelement = ET.SubElement(element, 'bins')
subelement.text = ' '.join(str(b) for b in self.bins)
return element
def can_merge(self, other):
"""Determine if filter can be merged with another.
Parameters
----------
other : openmc.Filter
Filter to compare with
Returns
-------
bool
Whether the filter can be merged
"""
return type(self) is type(other)
def merge(self, other):
"""Merge this filter with another.
Parameters
----------
other : openmc.Filter
Filter to merge with
Returns
-------
merged_filter : openmc.Filter
Filter resulting from the merge
"""
if not self.can_merge(other):
msg = 'Unable to merge "{0}" with "{1}" '.format(
type(self), type(other))
raise ValueError(msg)
# Merge unique filter bins
merged_bins = np.concatenate((self.bins, other.bins))
merged_bins = np.unique(merged_bins, axis=0)
# Create a new filter with these bins and a new auto-generated ID
return type(self)(merged_bins)
def is_subset(self, other):
"""Determine if another filter is a subset of this filter.
If all of the bins in the other filter are included as bins in this
filter, then it is a subset of this filter.
Parameters
----------
other : openmc.Filter
The filter to query as a subset of this filter
Returns
-------
bool
Whether or not the other filter is a subset of this filter
"""
if type(self) is not type(other):
return False
for b in other.bins:
if b not in self.bins:
return False
return True
def get_bin_index(self, filter_bin):
"""Returns the index in the Filter for some bin.
Parameters
----------
filter_bin : int or tuple
The bin is the integer ID for 'material', 'surface', 'cell',
'cellborn', and 'universe' Filters. The bin is an integer for the
cell instance ID for 'distribcell' Filters. The bin is a 2-tuple of
floats for 'energy' and 'energyout' filters corresponding to the
energy boundaries of the bin of interest. The bin is an (x,y,z)
3-tuple for 'mesh' filters corresponding to the mesh cell of
interest.
Returns
-------
filter_index : int
The index in the Tally data array for this filter bin.
"""
if filter_bin not in self.bins:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
raise ValueError(msg)
if isinstance(self.bins, np.ndarray):
return np.where(self.bins == filter_bin)[0][0]
else:
return self.bins.index(filter_bin)
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Keyword arguments
-----------------
paths : bool
Only used for DistribcellFilter. If True (default), expand
distribcell indices into multi-index columns describing the path
to that distribcell through the CSG tree. NOTE: This option assumes
that all distribcell paths are of the same length and do not have
the same universes and cells but different lattice cell indices.
Returns
-------
pandas.DataFrame
A Pandas DataFrame with columns of strings that characterize the
filter's bins. The number of rows in the DataFrame is the same as
the total number of bins in the corresponding tally, with the filter
bin appropriately tiled to map to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Initialize Pandas DataFrame
df = pd.DataFrame()
filter_bins = np.repeat(self.bins, stride)
tile_factor = data_size // len(filter_bins)
filter_bins = np.tile(filter_bins, tile_factor)
df = pd.concat([df, pd.DataFrame(
{self.short_name.lower(): filter_bins})])
return df
class WithIDFilter(Filter):
"""Abstract parent for filters of types with IDs (Cell, Material, etc.)."""
def __init__(self, bins, filter_id=None):
bins = np.atleast_1d(bins)
# Make sure bins are either integers or appropriate objects
cv.check_iterable_type('filter bins', bins,
(Integral, self.expected_type))
# Extract ID values
bins = np.array([b if isinstance(b, Integral) else b.id
for b in bins])
super().__init__(bins, filter_id)
def check_bins(self, bins):
# Check the bin values.
for edge in bins:
cv.check_greater_than('filter bin', edge, 0, equality=True)
class UniverseFilter(WithIDFilter):
"""Bins tally event locations based on the Universe they occured in.
Parameters
----------
bins : openmc.Universe, int, or iterable thereof
The Universes to tally. Either openmc.Universe objects or their
Integral ID numbers can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
openmc.Universe IDs.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Universe
class MaterialFilter(WithIDFilter):
"""Bins tally event locations based on the Material they occured in.
Parameters
----------
bins : openmc.Material, Integral, or iterable thereof
The Materials to tally. Either openmc.Material objects or their
Integral ID numbers can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
openmc.Material IDs.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Material
class CellFilter(WithIDFilter):
"""Bins tally event locations based on the Cell they occured in.
Parameters
----------
bins : openmc.Cell, int, or iterable thereof
The cells to tally. Either openmc.Cell objects or their ID numbers can
be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
openmc.Cell IDs.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Cell
class CellFromFilter(WithIDFilter):
"""Bins tally on which Cell the neutron came from.
Parameters
----------
bins : openmc.Cell, Integral, or iterable thereof
The Cell(s) to tally. Either openmc.Cell objects or their
Integral ID numbers can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Integral or Iterable of Integral
openmc.Cell IDs.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Cell
class CellbornFilter(WithIDFilter):
"""Bins tally events based on which Cell the neutron was born in.
Parameters
----------
bins : openmc.Cell, Integral, or iterable thereof
The birth Cells to tally. Either openmc.Cell objects or their
Integral ID numbers can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
openmc.Cell IDs.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Cell
class CellInstanceFilter(Filter):
"""Bins tally events based on which cell instance a particle is in.
This filter is similar to :class:`DistribcellFilter` but allows one to
select particular instances to be tallied (instead of obtaining *all*
instances by default) and allows instances from different cells to be
specified in a single filter.
.. versionadded:: 0.12
Parameters
----------
bins : iterable of 2-tuples or numpy.ndarray
The cell instances to tally, given as 2-tuples. For the first value in
the tuple, either openmc.Cell objects or their integral ID numbers can
be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : numpy.ndarray
2D numpy array of cell IDs and instances
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
See Also
--------
DistribcellFilter
"""
def __init__(self, bins, filter_id=None):
self.bins = bins
self.id = filter_id
@Filter.bins.setter
def bins(self, bins):
pairs = np.empty((len(bins), 2), dtype=int)
for i, (cell, instance) in enumerate(bins):
cv.check_type('cell', cell, (openmc.Cell, Integral))
cv.check_type('instance', instance, Integral)
pairs[i, 0] = cell if isinstance(cell, Integral) else cell.id
pairs[i, 1] = instance
self._bins = pairs
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Returns
-------
pandas.DataFrame
A Pandas DataFrame with a multi-index column for the cell instance.
The number of rows in the DataFrame is the same as the total number
of bins in the corresponding tally, with the filter bin appropriately
tiled to map to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Repeat and tile bins as necessary to account for other filters.
bins = np.repeat(self.bins, stride, axis=0)
tile_factor = data_size // len(bins)
bins = np.tile(bins, (tile_factor, 1))
columns = pd.MultiIndex.from_product([[self.short_name.lower()],
['cell', 'instance']])
return pd.DataFrame(bins, columns=columns)
def to_xml_element(self):
"""Return XML Element representing the Filter.
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing filter data
"""
element = ET.Element('filter')
element.set('id', str(self.id))
element.set('type', self.short_name.lower())
subelement = ET.SubElement(element, 'bins')
subelement.text = ' '.join(str(i) for i in self.bins.ravel())
return element
class SurfaceFilter(WithIDFilter):
"""Filters particles by surface crossing
Parameters
----------
bins : openmc.Surface, int, or iterable of Integral
The surfaces to tally over. Either openmc.Surface objects or their ID
numbers can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
The surfaces to tally over. Either openmc.Surface objects or their ID
numbers can be used.
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
expected_type = Surface
class ParticleFilter(Filter):
"""Bins tally events based on the Particle type.
Parameters
----------
bins : str, or iterable of str
The particles to tally represented as strings ('neutron', 'photon',
'electron', 'positron').
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
The Particles to tally
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
def __eq__(self, other):
if type(self) is not type(other):
return False
elif len(self.bins) != len(other.bins):
return False
else:
return np.all(self.bins == other.bins)
__hash__ = Filter.__hash__
@Filter.bins.setter
def bins(self, bins):
bins = np.atleast_1d(bins)
cv.check_iterable_type('filter bins', bins, str)
for edge in bins:
cv.check_value('filter bin', edge, _PARTICLES)
self._bins = bins
@classmethod
def from_hdf5(cls, group, **kwargs):
if group['type'][()].decode() != cls.short_name.lower():
raise ValueError("Expected HDF5 data for filter type '"
+ cls.short_name.lower() + "' but got '"
+ group['type'][()].decode() + " instead")
particles = [b.decode() for b in group['bins'][()]]
filter_id = int(group.name.split('/')[-1].lstrip('filter '))
return cls(particles, filter_id=filter_id)
class MeshFilter(Filter):
"""Bins tally event locations onto a regular, rectangular mesh.
Parameters
----------
mesh : openmc.MeshBase
The mesh object that events will be tallied onto
filter_id : int
Unique identifier for the filter
Attributes
----------
mesh : openmc.MeshBase
The mesh object that events will be tallied onto
id : int
Unique identifier for the filter
bins : list of tuple
A list of mesh indices for each filter bin, e.g. [(1, 1, 1), (2, 1, 1),
...]
num_bins : Integral
The number of filter bins
"""
def __init__(self, mesh, filter_id=None):
self.mesh = mesh
self.id = filter_id
def __hash__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tMesh ID', self.mesh.id)
return hash(string)
def __repr__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tMesh ID', self.mesh.id)
string += '{: <16}=\t{}\n'.format('\tID', self.id)
return string
@classmethod
def from_hdf5(cls, group, **kwargs):
if group['type'][()].decode() != cls.short_name.lower():
raise ValueError("Expected HDF5 data for filter type '"
+ cls.short_name.lower() + "' but got '"
+ group['type'][()].decode() + " instead")
if 'meshes' not in kwargs:
raise ValueError(cls.__name__ + " requires a 'meshes' keyword "
"argument.")
mesh_id = group['bins'][()]
mesh_obj = kwargs['meshes'][mesh_id]
filter_id = int(group.name.split('/')[-1].lstrip('filter '))
out = cls(mesh_obj, filter_id=filter_id)
return out
@property
def mesh(self):
return self._mesh
@mesh.setter
def mesh(self, mesh):
cv.check_type('filter mesh', mesh, openmc.MeshBase)
self._mesh = mesh
if isinstance(mesh, openmc.UnstructuredMesh):
if mesh.volumes is None:
self.bins = []
else:
self.bins = list(range(len(mesh.volumes)))
else:
self.bins = list(mesh.indices)
def can_merge(self, other):
# Mesh filters cannot have more than one bin
return False
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Returns
-------
pandas.DataFrame
A Pandas DataFrame with three columns describing the x,y,z mesh
cell indices corresponding to each filter bin. The number of rows
in the DataFrame is the same as the total number of bins in the
corresponding tally, with the filter bin appropriately tiled to map
to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Initialize Pandas DataFrame
df = pd.DataFrame()
# Initialize dictionary to build Pandas Multi-index column
filter_dict = {}
# Append mesh ID as outermost index of multi-index
mesh_key = 'mesh {}'.format(self.mesh.id)
# Find mesh dimensions - use 3D indices for simplicity
n_dim = len(self.mesh.dimension)
if n_dim == 3:
nx, ny, nz = self.mesh.dimension
elif n_dim == 2:
nx, ny = self.mesh.dimension
nz = 1
else:
nx = self.mesh.dimension
ny = nz = 1
# Generate multi-index sub-column for x-axis
filter_dict[mesh_key, 'x'] = _repeat_and_tile(
np.arange(1, nx + 1), stride, data_size)
# Generate multi-index sub-column for y-axis
filter_dict[mesh_key, 'y'] = _repeat_and_tile(
np.arange(1, ny + 1), nx * stride, data_size)
# Generate multi-index sub-column for z-axis
filter_dict[mesh_key, 'z'] = _repeat_and_tile(
np.arange(1, nz + 1), nx * ny * stride, data_size)
# Initialize a Pandas DataFrame from the mesh dictionary
df = pd.concat([df, pd.DataFrame(filter_dict)])
return df
def to_xml_element(self):
"""Return XML Element representing the Filter.
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing filter data
"""
element = super().to_xml_element()
element[0].text = str(self.mesh.id)
return element
class MeshSurfaceFilter(MeshFilter):
"""Filter events by surface crossings on a regular, rectangular mesh.
Parameters
----------
mesh : openmc.MeshBase
The mesh object that events will be tallied onto
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Integral
The mesh ID
mesh : openmc.MeshBase
The mesh object that events will be tallied onto
id : int
Unique identifier for the filter
bins : list of tuple
A list of mesh indices / surfaces for each filter bin, e.g. [(1, 1,
'x-min out'), (1, 1, 'x-min in'), ...]
num_bins : Integral
The number of filter bins
"""
@MeshFilter.mesh.setter
def mesh(self, mesh):
cv.check_type('filter mesh', mesh, openmc.MeshBase)
self._mesh = mesh
# Take the product of mesh indices and current names
n_dim = mesh.n_dimension
self.bins = [mesh_tuple + (surf,) for mesh_tuple, surf in
product(mesh.indices, _CURRENT_NAMES[:4*n_dim])]
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Returns
-------
pandas.DataFrame
A Pandas DataFrame with three columns describing the x,y,z mesh
cell indices corresponding to each filter bin. The number of rows
in the DataFrame is the same as the total number of bins in the
corresponding tally, with the filter bin appropriately tiled to map
to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Initialize Pandas DataFrame
df = pd.DataFrame()
# Initialize dictionary to build Pandas Multi-index column
filter_dict = {}
# Append mesh ID as outermost index of multi-index
mesh_key = 'mesh {}'.format(self.mesh.id)
# Find mesh dimensions - use 3D indices for simplicity
n_surfs = 4 * len(self.mesh.dimension)
if len(self.mesh.dimension) == 3:
nx, ny, nz = self.mesh.dimension
elif len(self.mesh.dimension) == 2:
nx, ny = self.mesh.dimension
nz = 1
else:
nx = self.mesh.dimension
ny = nz = 1
# Generate multi-index sub-column for x-axis
filter_dict[mesh_key, 'x'] = _repeat_and_tile(
np.arange(1, nx + 1), n_surfs * stride, data_size)
# Generate multi-index sub-column for y-axis
if len(self.mesh.dimension) > 1:
filter_dict[mesh_key, 'y'] = _repeat_and_tile(
np.arange(1, ny + 1), n_surfs * nx * stride, data_size)
# Generate multi-index sub-column for z-axis
if len(self.mesh.dimension) > 2:
filter_dict[mesh_key, 'z'] = _repeat_and_tile(
np.arange(1, nz + 1), n_surfs * nx * ny * stride, data_size)
# Generate multi-index sub-column for surface
filter_dict[mesh_key, 'surf'] = _repeat_and_tile(
_CURRENT_NAMES[:n_surfs], stride, data_size)
# Initialize a Pandas DataFrame from the mesh dictionary
return pd.concat([df, pd.DataFrame(filter_dict)])
class RealFilter(Filter):
"""Tally modifier that describes phase-space and other characteristics
Parameters
----------
values : iterable of float
A list of values for which each successive pair constitutes a range of
values for a single bin
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
values for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of values indicating a
filter bin range
num_bins : int
The number of filter bins
"""
def __init__(self, values, filter_id=None):
self.values = np.asarray(values)
self.bins = np.vstack((self.values[:-1], self.values[1:])).T
self.id = filter_id
def __gt__(self, other):
if type(self) is type(other):
# Compare largest/smallest bin edges in filters
# This logic is used when merging tallies with real filters
return self.values[0] >= other.values[-1]
else:
return super().__gt__(other)
def __repr__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tValues', self.values)
string += '{: <16}=\t{}\n'.format('\tID', self.id)
return string
@Filter.bins.setter
def bins(self, bins):
Filter.bins.__set__(self, np.asarray(bins))
def check_bins(self, bins):
for v0, v1 in bins:
# Values should be real
cv.check_type('filter value', v0, Real)
cv.check_type('filter value', v1, Real)
# Make sure that each tuple has values that are increasing
if v1 < v0:
raise ValueError('Values {} and {} appear to be out of order'
.format(v0, v1))
for pair0, pair1 in zip(bins[:-1], bins[1:]):
# Successive pairs should be ordered
if pair1[1] < pair0[1]:
raise ValueError('Values {} and {} appear to be out of order'
.format(pair1[1], pair0[1]))
def can_merge(self, other):
if type(self) is not type(other):
return False
if self.bins[0, 0] == other.bins[-1][1]:
# This low edge coincides with other's high edge
return True
elif self.bins[-1][1] == other.bins[0, 0]:
# This high edge coincides with other's low edge
return True
else:
return False
def merge(self, other):
if not self.can_merge(other):
msg = 'Unable to merge "{0}" with "{1}" ' \
'filters'.format(type(self), type(other))
raise ValueError(msg)
# Merge unique filter bins
merged_values = np.concatenate((self.values, other.values))
merged_values = np.unique(merged_values)
# Create a new filter with these bins and a new auto-generated ID
return type(self)(sorted(merged_values))
def is_subset(self, other):
"""Determine if another filter is a subset of this filter.
If all of the bins in the other filter are included as bins in this
filter, then it is a subset of this filter.
Parameters
----------
other : openmc.Filter
The filter to query as a subset of this filter
Returns
-------
bool
Whether or not the other filter is a subset of this filter
"""
if type(self) is not type(other):
return False
elif self.num_bins != other.num_bins:
return False
else:
return np.allclose(self.values, other.values)
def get_bin_index(self, filter_bin):
i = np.where(self.bins[:, 1] == filter_bin[1])[0]
if len(i) == 0:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
raise ValueError(msg)
else:
return i[0]
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Returns
-------
pandas.DataFrame
A Pandas DataFrame with one column of the lower energy bound and one
column of upper energy bound for each filter bin. The number of
rows in the DataFrame is the same as the total number of bins in the
corresponding tally, with the filter bin appropriately tiled to map
to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Initialize Pandas DataFrame
df = pd.DataFrame()
# Extract the lower and upper energy bounds, then repeat and tile
# them as necessary to account for other filters.
lo_bins = np.repeat(self.bins[:, 0], stride)
hi_bins = np.repeat(self.bins[:, 1], stride)
tile_factor = data_size // len(lo_bins)
lo_bins = np.tile(lo_bins, tile_factor)
hi_bins = np.tile(hi_bins, tile_factor)
# Add the new energy columns to the DataFrame.
if hasattr(self, 'units'):
units = ' [{}]'.format(self.units)
else:
units = ''
df.loc[:, self.short_name.lower() + ' low' + units] = lo_bins
df.loc[:, self.short_name.lower() + ' high' + units] = hi_bins
return df
def to_xml_element(self):
"""Return XML Element representing the Filter.
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing filter data
"""
element = super().to_xml_element()
element[0].text = ' '.join(str(x) for x in self.values)
return element
class EnergyFilter(RealFilter):
"""Bins tally events based on incident particle energy.
Parameters
----------
values : Iterable of Real
A list of values for which each successive pair constitutes a range of
energies in [eV] for a single bin
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
energies in [eV] for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of energies in [eV]
for a single filter bin
num_bins : int
The number of filter bins
"""
units = 'eV'
def get_bin_index(self, filter_bin):
# Use lower energy bound to find index for RealFilters
deltas = np.abs(self.bins[:, 1] - filter_bin[1]) / filter_bin[1]
min_delta = np.min(deltas)
if min_delta < 1E-3:
return deltas.argmin()
else:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
raise ValueError(msg)
def check_bins(self, bins):
super().check_bins(bins)
for v0, v1 in bins:
cv.check_greater_than('filter value', v0, 0., equality=True)
cv.check_greater_than('filter value', v1, 0., equality=True)
class EnergyoutFilter(EnergyFilter):
"""Bins tally events based on outgoing particle energy.
Parameters
----------
values : Iterable of Real
A list of values for which each successive pair constitutes a range of
energies in [eV] for a single bin
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
energies in [eV] for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of energies in [eV]
for a single filter bin
num_bins : int
The number of filter bins
"""
def _path_to_levels(path):
"""Convert distribcell path to list of levels
Parameters
----------
path : str
Distribcell path
Returns
-------
list
List of levels in path
"""
# Split path into universes/cells/lattices
path_items = path.split('->')
# Pair together universe and cell information from the same level
idx = [i for i, item in enumerate(path_items) if item.startswith('u')]
for i in reversed(idx):
univ_id = int(path_items.pop(i)[1:])
cell_id = int(path_items.pop(i)[1:])
path_items.insert(i, ('universe', univ_id, cell_id))
# Reformat lattice into tuple
idx = [i for i, item in enumerate(path_items) if isinstance(item, str)]
for i in idx:
item = path_items.pop(i)[1:-1]
lat_id, lat_xyz = item.split('(')
lat_id = int(lat_id)
lat_xyz = tuple(int(x) for x in lat_xyz.split(','))
path_items.insert(i, ('lattice', lat_id, lat_xyz))
return path_items
class DistribcellFilter(Filter):
"""Bins tally event locations on instances of repeated cells.
This filter provides a separate score for each unique instance of a repeated
cell in a geometry. Note that only one cell can be specified in this filter.
The related :class:`CellInstanceFilter` allows one to obtain scores for
particular cell instances as well as instances from different cells.
Parameters
----------
cell : openmc.Cell or Integral
The distributed cell to tally. Either an openmc.Cell or an Integral
cell ID number can be used.
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : Iterable of Integral
An iterable with one element---the ID of the distributed Cell.
id : int
Unique identifier for the filter
num_bins : int
The number of filter bins
paths : list of str
The paths traversed through the CSG tree to reach each distribcell
instance (for 'distribcell' filters only)
See Also
--------
CellInstanceFilter
"""
def __init__(self, cell, filter_id=None):
self._paths = None
super().__init__(cell, filter_id)
@classmethod
def from_hdf5(cls, group, **kwargs):
if group['type'][()].decode() != cls.short_name.lower():
raise ValueError("Expected HDF5 data for filter type '"
+ cls.short_name.lower() + "' but got '"
+ group['type'][()].decode() + " instead")
filter_id = int(group.name.split('/')[-1].lstrip('filter '))
out = cls(group['bins'][()], filter_id=filter_id)
out._num_bins = group['n_bins'][()]
return out
@property
def num_bins(self):
# Need to handle number of bins carefully -- for distribcell tallies, we
# need to know how many instances of the cell there are
return self._num_bins
@property
def paths(self):
return self._paths
@Filter.bins.setter
def bins(self, bins):
# Format the bins as a 1D numpy array.
bins = np.atleast_1d(bins)
# Make sure there is only 1 bin.
if not len(bins) == 1:
msg = 'Unable to add bins "{0}" to a DistribcellFilter since ' \
'only a single distribcell can be used per tally'.format(bins)
raise ValueError(msg)
# Check the type and extract the id, if necessary.
cv.check_type('distribcell bin', bins[0], (Integral, openmc.Cell))
if isinstance(bins[0], openmc.Cell):
bins = np.atleast_1d(bins[0].id)
self._bins = bins
@paths.setter
def paths(self, paths):
cv.check_iterable_type('paths', paths, str)
self._paths = paths
def can_merge(self, other):
# Distribcell filters cannot have more than one bin
return False
def get_bin_index(self, filter_bin):
# Filter bins for distribcells are indices of each unique placement of
# the Cell in the Geometry (consecutive integers starting at 0).
return filter_bin
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Keyword arguments
-----------------
paths : bool
If True (default), expand distribcell indices into multi-index
columns describing the path to that distribcell through the CSG
tree. NOTE: This option assumes that all distribcell paths are of
the same length and do not have the same universes and cells but
different lattice cell indices.
Returns
-------
pandas.DataFrame
A Pandas DataFrame with columns describing distributed cells. The
dataframe will have either:
1. a single column with the cell instance IDs (without summary info)
2. separate columns for the cell IDs, universe IDs, and lattice IDs
and x,y,z cell indices corresponding to each (distribcell paths).
The number of rows in the DataFrame is the same as the total number
of bins in the corresponding tally, with the filter bin
appropriately tiled to map to the corresponding tally bins.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
# Initialize Pandas DataFrame
df = pd.DataFrame()
level_df = None
paths = kwargs.setdefault('paths', True)
# Create Pandas Multi-index columns for each level in CSG tree
if paths:
# Distribcell paths require linked metadata from the Summary
if self.paths is None:
msg = 'Unable to construct distribcell paths since ' \
'the Summary is not linked to the StatePoint'
raise ValueError(msg)
# Make copy of array of distribcell paths to use in
# Pandas Multi-index column construction
num_offsets = len(self.paths)
paths = [_path_to_levels(p) for p in self.paths]
# Loop over CSG levels in the distribcell paths
num_levels = len(paths[0])
for i_level in range(num_levels):
# Use level key as first index in Pandas Multi-index column
level_key = 'level {}'.format(i_level + 1)
# Create a dictionary for this level for Pandas Multi-index
level_dict = OrderedDict()
# Use the first distribcell path to determine if level
# is a universe/cell or lattice level
path = paths[0]
if path[i_level][0] == 'lattice':
# Initialize prefix Multi-index keys
lat_id_key = (level_key, 'lat', 'id')
lat_x_key = (level_key, 'lat', 'x')
lat_y_key = (level_key, 'lat', 'y')
lat_z_key = (level_key, 'lat', 'z')
# Allocate NumPy arrays for each CSG level and
# each Multi-index column in the DataFrame
level_dict[lat_id_key] = np.empty(num_offsets)
level_dict[lat_x_key] = np.empty(num_offsets)
level_dict[lat_y_key] = np.empty(num_offsets)
if len(path[i_level][2]) == 3:
level_dict[lat_z_key] = np.empty(num_offsets)
else:
# Initialize prefix Multi-index keys
univ_key = (level_key, 'univ', 'id')
cell_key = (level_key, 'cell', 'id')
# Allocate NumPy arrays for each CSG level and
# each Multi-index column in the DataFrame
level_dict[univ_key] = np.empty(num_offsets)
level_dict[cell_key] = np.empty(num_offsets)
# Populate Multi-index arrays with all distribcell paths
for i, path in enumerate(paths):
level = path[i_level]
if level[0] == 'lattice':
# Assign entry to Lattice Multi-index column
level_dict[lat_id_key][i] = level[1]
level_dict[lat_x_key][i] = level[2][0]
level_dict[lat_y_key][i] = level[2][1]
if len(level[2]) == 3:
level_dict[lat_z_key][i] = level[2][2]
else:
# Assign entry to Universe, Cell Multi-index columns
level_dict[univ_key][i] = level[1]
level_dict[cell_key][i] = level[2]
# Tile the Multi-index columns
for level_key, level_bins in level_dict.items():
level_dict[level_key] = _repeat_and_tile(
level_bins, stride, data_size)
# Initialize a Pandas DataFrame from the level dictionary
if level_df is None:
level_df = pd.DataFrame(level_dict)
else:
level_df = pd.concat([level_df, pd.DataFrame(level_dict)],
axis=1)
# Create DataFrame column for distribcell instance IDs
# NOTE: This is performed regardless of whether the user
# requests Summary geometric information
filter_bins = _repeat_and_tile(
np.arange(self.num_bins), stride, data_size)
df = pd.DataFrame({self.short_name.lower() : filter_bins})
# Concatenate with DataFrame of distribcell instance IDs
if level_df is not None:
level_df = level_df.dropna(axis=1, how='all')
level_df = level_df.astype(np.int)
df = pd.concat([level_df, df], axis=1)
return df
class MuFilter(RealFilter):
"""Bins tally events based on particle scattering angle.
Parameters
----------
values : int or Iterable of Real
A grid of scattering angles which events will binned into. Values
represent the cosine of the scattering angle. If an iterable is given,
the values will be used explicitly as grid points. If a single int is
given, the range [-1, 1] will be divided up equally into that number of
bins.
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
scattering angle cosines for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of scattering angle
cosines for a single filter bin
num_bins : Integral
The number of filter bins
"""
def __init__(self, values, filter_id=None):
if isinstance(values, Integral):
values = np.linspace(-1., 1., values + 1)
super().__init__(values, filter_id)
def check_bins(self, bins):
super().check_bins(bins)
for x in np.ravel(bins):
if not np.isclose(x, -1.):
cv.check_greater_than('filter value', x, -1., equality=True)
if not np.isclose(x, 1.):
cv.check_less_than('filter value', x, 1., equality=True)
class PolarFilter(RealFilter):
"""Bins tally events based on the incident particle's direction.
Parameters
----------
values : int or Iterable of Real
A grid of polar angles which events will binned into. Values represent
an angle in radians relative to the z-axis. If an iterable is given, the
values will be used explicitly as grid points. If a single int is given,
the range [0, pi] will be divided up equally into that number of bins.
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
polar angles in [rad] for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of polar angles for a
single filter bin
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
units = 'rad'
def __init__(self, values, filter_id=None):
if isinstance(values, Integral):
values = np.linspace(0., np.pi, values + 1)
super().__init__(values, filter_id)
def check_bins(self, bins):
super().check_bins(bins)
for x in np.ravel(bins):
if not np.isclose(x, 0.):
cv.check_greater_than('filter value', x, 0., equality=True)
if not np.isclose(x, np.pi):
cv.check_less_than('filter value', x, np.pi, equality=True)
class AzimuthalFilter(RealFilter):
"""Bins tally events based on the incident particle's direction.
Parameters
----------
values : int or Iterable of Real
A grid of azimuthal angles which events will binned into. Values
represent an angle in radians relative to the x-axis and perpendicular
to the z-axis. If an iterable is given, the values will be used
explicitly as grid points. If a single int is given, the range
[-pi, pi) will be divided up equally into that number of bins.
filter_id : int
Unique identifier for the filter
Attributes
----------
values : numpy.ndarray
An array of values for which each successive pair constitutes a range of
azimuthal angles in [rad] for a single bin
id : int
Unique identifier for the filter
bins : numpy.ndarray
An array of shape (N, 2) where each row is a pair of azimuthal angles
for a single filter bin
num_bins : Integral
The number of filter bins
"""
units = 'rad'
def __init__(self, values, filter_id=None):
if isinstance(values, Integral):
values = np.linspace(-np.pi, np.pi, values + 1)
super().__init__(values, filter_id)
def check_bins(self, bins):
super().check_bins(bins)
for x in np.ravel(bins):
if not np.isclose(x, -np.pi):
cv.check_greater_than('filter value', x, -np.pi, equality=True)
if not np.isclose(x, np.pi):
cv.check_less_than('filter value', x, np.pi, equality=True)
class DelayedGroupFilter(Filter):
"""Bins fission events based on the produced neutron precursor groups.
Parameters
----------
bins : iterable of int
The delayed neutron precursor groups. For example, ENDF/B-VII.1 uses
6 precursor groups so a tally with all groups will have bins =
[1, 2, 3, 4, 5, 6].
filter_id : int
Unique identifier for the filter
Attributes
----------
bins : iterable of int
The delayed neutron precursor groups. For example, ENDF/B-VII.1 uses
6 precursor groups so a tally with all groups will have bins =
[1, 2, 3, 4, 5, 6].
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins
"""
def check_bins(self, bins):
# Check the bin values.
for g in bins:
cv.check_greater_than('delayed group', g, 0)
class EnergyFunctionFilter(Filter):
"""Multiplies tally scores by an arbitrary function of incident energy.
The arbitrary function is described by a piecewise linear-linear
interpolation of energy and y values. Values outside of the given energy
range will be evaluated as zero.
Parameters
----------
energy : Iterable of Real
A grid of energy values in [eV]
y : iterable of Real
A grid of interpolant values in [eV]
filter_id : int
Unique identifier for the filter
Attributes
----------
energy : Iterable of Real
A grid of energy values in [eV]
y : iterable of Real
A grid of interpolant values in [eV]
id : int
Unique identifier for the filter
num_bins : Integral
The number of filter bins (always 1 for this filter)
"""
def __init__(self, energy, y, filter_id=None):
self.energy = energy
self.y = y
self.id = filter_id
def __eq__(self, other):
if type(self) is not type(other):
return False
elif not all(self.energy == other.energy):
return False
else:
return all(self.y == other.y)
def __gt__(self, other):
if type(self) is not type(other):
if self.short_name in _FILTER_TYPES and \
other.short_name in _FILTER_TYPES:
delta = _FILTER_TYPES.index(self.short_name) - \
_FILTER_TYPES.index(other.short_name)
return delta > 0
else:
return False
else:
return False
def __lt__(self, other):
if type(self) is not type(other):
if self.short_name in _FILTER_TYPES and \
other.short_name in _FILTER_TYPES:
delta = _FILTER_TYPES.index(self.short_name) - \
_FILTER_TYPES.index(other.short_name)
return delta < 0
else:
return False
else:
return False
def __hash__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tEnergy', self.energy)
string += '{: <16}=\t{}\n'.format('\tInterpolant', self.y)
return hash(string)
def __repr__(self):
string = type(self).__name__ + '\n'
string += '{: <16}=\t{}\n'.format('\tEnergy', self.energy)
string += '{: <16}=\t{}\n'.format('\tInterpolant', self.y)
string += '{: <16}=\t{}\n'.format('\tID', self.id)
return string
@classmethod
def from_hdf5(cls, group, **kwargs):
if group['type'][()].decode() != cls.short_name.lower():
raise ValueError("Expected HDF5 data for filter type '"
+ cls.short_name.lower() + "' but got '"
+ group['type'][()].decode() + " instead")
energy = group['energy'][()]
y = group['y'][()]
filter_id = int(group.name.split('/')[-1].lstrip('filter '))
return cls(energy, y, filter_id=filter_id)
@classmethod
def from_tabulated1d(cls, tab1d):
"""Construct a filter from a Tabulated1D object.
Parameters
----------
tab1d : openmc.data.Tabulated1D
A linear-linear Tabulated1D object with only a single interpolation
region.
Returns
-------
EnergyFunctionFilter
"""
cv.check_type('EnergyFunctionFilter tab1d', tab1d,
openmc.data.Tabulated1D)
if tab1d.n_regions > 1:
raise ValueError('Only Tabulated1Ds with a single interpolation '
'region are supported')
if tab1d.interpolation[0] != 2:
raise ValueError('Only linear-linar Tabulated1Ds are supported')
return cls(tab1d.x, tab1d.y)
@property
def energy(self):
return self._energy
@property
def y(self):
return self._y
@property
def bins(self):
raise AttributeError('EnergyFunctionFilters have no bins.')
@property
def num_bins(self):
return 1
@energy.setter
def energy(self, energy):
# Format the bins as a 1D numpy array.
energy = np.atleast_1d(energy)
# Make sure the values are Real and positive.
cv.check_type('filter energy grid', energy, Iterable, Real)
for E in energy:
cv.check_greater_than('filter energy grid', E, 0, equality=True)
self._energy = energy
@y.setter
def y(self, y):
# Format the bins as a 1D numpy array.
y = np.atleast_1d(y)
# Make sure the values are Real.
cv.check_type('filter interpolant values', y, Iterable, Real)
self._y = y
@bins.setter
def bins(self, bins):
raise RuntimeError('EnergyFunctionFilters have no bins.')
def to_xml_element(self):
"""Return XML Element representing the Filter.
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing filter data
"""
element = ET.Element('filter')
element.set('id', str(self.id))
element.set('type', self.short_name.lower())
subelement = ET.SubElement(element, 'energy')
subelement.text = ' '.join(str(e) for e in self.energy)
subelement = ET.SubElement(element, 'y')
subelement.text = ' '.join(str(y) for y in self.y)
return element
def can_merge(self, other):
return False
def is_subset(self, other):
return self == other
def get_bin_index(self, filter_bin):
# This filter only has one bin. Always return 0.
return 0
def get_pandas_dataframe(self, data_size, stride, **kwargs):
"""Builds a Pandas DataFrame for the Filter's bins.
This method constructs a Pandas DataFrame object for the filter with
columns annotated by filter bin information. This is a helper method for
:meth:`Tally.get_pandas_dataframe`.
Parameters
----------
data_size : int
The total number of bins in the tally corresponding to this filter
stride : int
Stride in memory for the filter
Returns
-------
pandas.DataFrame
A Pandas DataFrame with a column that is filled with a hash of this
filter. EnergyFunctionFilters have only 1 bin so the purpose of this
DataFrame column is to differentiate the filter from other
EnergyFunctionFilters. The number of rows in the DataFrame is the
same as the total number of bins in the corresponding tally.
See also
--------
Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe()
"""
df = pd.DataFrame()
# There is no clean way of sticking all the energy, y data into a
# DataFrame so instead we'll just make a column with the filter name
# and fill it with a hash of the __repr__. We want a hash that is
# reproducible after restarting the interpreter so we'll use hashlib.md5
# rather than the intrinsic hash().
hash_fun = hashlib.md5()
hash_fun.update(repr(self).encode('utf-8'))
out = hash_fun.hexdigest()
# The full 16 bytes make for a really wide column. Just 7 bytes (14
# hex characters) of the digest are probably sufficient.
out = out[:14]
filter_bins = _repeat_and_tile(out, stride, data_size)
df = pd.concat([df, pd.DataFrame(
{self.short_name.lower(): filter_bins})])
return df
| mit |
shikhardb/scikit-learn | sklearn/tree/export.py | 30 | 4529 | """
This module defines export functions for decision trees.
"""
# Authors: Gilles Louppe <g.louppe@gmail.com>
# Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Brian Holt <bdholt1@gmail.com>
# Noel Dawe <noel@dawe.me>
# Satrajit Gosh <satrajit.ghosh@gmail.com>
# Licence: BSD 3 clause
from ..externals import six
from . import _tree
def export_graphviz(decision_tree, out_file="tree.dot", feature_names=None,
max_depth=None):
"""Export a decision tree in DOT format.
This function generates a GraphViz representation of the decision tree,
which is then written into `out_file`. Once exported, graphical renderings
can be generated using, for example::
$ dot -Tps tree.dot -o tree.ps (PostScript format)
$ dot -Tpng tree.dot -o tree.png (PNG format)
The sample counts that are shown are weighted with any sample_weights that
might be present.
Parameters
----------
decision_tree : decision tree classifier
The decision tree to be exported to GraphViz.
out_file : file object or string, optional (default="tree.dot")
Handle or name of the output file.
feature_names : list of strings, optional (default=None)
Names of each of the features.
max_depth : int, optional (default=None)
The maximum depth of the representation. If None, the tree is fully
generated.
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> clf = tree.DecisionTreeClassifier()
>>> iris = load_iris()
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.export_graphviz(clf,
... out_file='tree.dot') # doctest: +SKIP
"""
def node_to_str(tree, node_id, criterion):
if not isinstance(criterion, six.string_types):
criterion = "impurity"
value = tree.value[node_id]
if tree.n_outputs == 1:
value = value[0, :]
if tree.children_left[node_id] == _tree.TREE_LEAF:
return "%s = %.4f\\nsamples = %s\\nvalue = %s" \
% (criterion,
tree.impurity[node_id],
tree.n_node_samples[node_id],
value)
else:
if feature_names is not None:
feature = feature_names[tree.feature[node_id]]
else:
feature = "X[%s]" % tree.feature[node_id]
return "%s <= %.4f\\n%s = %s\\nsamples = %s" \
% (feature,
tree.threshold[node_id],
criterion,
tree.impurity[node_id],
tree.n_node_samples[node_id])
def recurse(tree, node_id, criterion, parent=None, depth=0):
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
# Add node with description
if max_depth is None or depth <= max_depth:
out_file.write('%d [label="%s", shape="box"] ;\n' %
(node_id, node_to_str(tree, node_id, criterion)))
if parent is not None:
# Add edge to parent
out_file.write('%d -> %d ;\n' % (parent, node_id))
if left_child != _tree.TREE_LEAF:
recurse(tree, left_child, criterion=criterion, parent=node_id,
depth=depth + 1)
recurse(tree, right_child, criterion=criterion, parent=node_id,
depth=depth + 1)
else:
out_file.write('%d [label="(...)", shape="box"] ;\n' % node_id)
if parent is not None:
# Add edge to parent
out_file.write('%d -> %d ;\n' % (parent, node_id))
own_file = False
try:
if isinstance(out_file, six.string_types):
if six.PY3:
out_file = open(out_file, "w", encoding="utf-8")
else:
out_file = open(out_file, "wb")
own_file = True
out_file.write("digraph Tree {\n")
if isinstance(decision_tree, _tree.Tree):
recurse(decision_tree, 0, criterion="impurity")
else:
recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)
out_file.write("}")
finally:
if own_file:
out_file.close()
| bsd-3-clause |
BT-ojossen/bank-statement-reconcile | __unported__/account_statement_completion_label/__openerp__.py | 14 | 2038 | # -*- coding: utf-8 -*-
###############################################################################
#
# account_statement_completion_label for OpenERP
# Copyright (C) 2013 Akretion (http://www.akretion.com). All Rights Reserved
# @author Benoît GUILLOT <benoit.guillot@akretion.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/>.
#
###############################################################################
{
'name': 'Bank statement completion from label',
'version': '0.1',
'category': 'Generic Modules/Others',
'license': 'AGPL-3',
'description': """
Improve the basic rule "Match from statement line label (based on partner
field 'Bank Statement Label')" provided by the Bank statement base
completion module. The goal is to match the label field from the bank
statement line with a partner and an account.
For this, you have to create your record in the new class
account.statement.label where you can link the label you want with a
partner and an account.
""",
'author': "Akretion,Odoo Community Association (OCA)",
'website': 'http://www.akretion.com/',
'depends': ['account_statement_base_completion'],
'data': [
'partner_view.xml',
'statement_view.xml',
'security/ir.model.access.csv',
'security/ir_rule.xml',
],
'demo': [],
'installable': False,
'active': False,
}
| agpl-3.0 |
Ms2ger/servo | tests/wpt/css-tests/tools/pywebsocket/src/example/origin_check_wsh.py | 516 | 1992 | # Copyright 2011, 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.
# This example is derived from test/testdata/handlers/origin_check_wsh.py.
def web_socket_do_extra_handshake(request):
if request.ws_origin == 'http://example.com':
return
raise ValueError('Unacceptable origin: %r' % request.ws_origin)
def web_socket_transfer_data(request):
request.connection.write('origin_check_wsh.py is called for %s, %s' %
(request.ws_resource, request.ws_protocol))
# vi:sts=4 sw=4 et
| mpl-2.0 |
wzhy90/git-repo | subcmds/prune.py | 90 | 1792 | #
# Copyright (C) 2008 The Android Open Source Project
#
# 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 __future__ import print_function
from color import Coloring
from command import PagedCommand
class Prune(PagedCommand):
common = True
helpSummary = "Prune (delete) already merged topics"
helpUsage = """
%prog [<project>...]
"""
def Execute(self, opt, args):
all_branches = []
for project in self.GetProjects(args):
all_branches.extend(project.PruneHeads())
if not all_branches:
return
class Report(Coloring):
def __init__(self, config):
Coloring.__init__(self, config, 'status')
self.project = self.printer('header', attr='bold')
out = Report(all_branches[0].project.config)
out.project('Pending Branches')
out.nl()
project = None
for branch in all_branches:
if project != branch.project:
project = branch.project
out.nl()
out.project('project %s/' % project.relpath)
out.nl()
commits = branch.commits
date = branch.date
print('%s %-33s (%2d commit%s, %s)' % (
branch.name == project.CurrentBranch and '*' or ' ',
branch.name,
len(commits),
len(commits) != 1 and 's' or ' ',
date))
| apache-2.0 |
dnozay/lettuce | tests/integration/lib/Django-1.2.5/django/conf/locale/id/formats.py | 80 | 1578 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
DATE_FORMAT = 'j N Y'
DATETIME_FORMAT = "j N Y, G:i:s"
TIME_FORMAT = 'G:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'd-m-Y'
SHORT_DATETIME_FORMAT = 'd-m-Y G:i:s'
FIRST_DAY_OF_WEEK = 1 #Monday
DATE_INPUT_FORMATS = (
'%d-%m-%y', '%d/%m/%y', # '25-10-09' , 25/10/09'
'%d-%m-%Y', '%d/%m/%Y', # '25-10-2009' , 25/10/2009'
# '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
# '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
)
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
DATETIME_INPUT_FORMATS = (
'%d-%m-%Y %H:%M:%S', # '25-10-2009 14:30:59'
'%d-%m-%Y %H:%M', # '25-10-2009 14:30'
'%d-%m-%Y', # '25-10-2009'
'%d-%m-%y %H:%M:%S', # '25-10-09' 14:30:59'
'%d-%m-%y %H:%M', # '25-10-09' 14:30'
'%d-%m-%y', # '25-10-09''
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
'%m/%d/%Y %H:%M:%S', # '25/10/2009 14:30:59'
'%m/%d/%Y %H:%M', # '25/10/2009 14:30'
'%m/%d/%Y', # '10/25/2009'
)
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
NUMBER_GROUPING = 3
| gpl-3.0 |
MakerReduxCorp/MARDS | MARDS/doc.py | 1 | 8271 | # -*- coding: iso-8859-1 -*-
# MARDS\doc.py
#
# DOCUMENTATION GENERATION
#
from rolne import rolne
from MARDS import st
# the breakdown_rolne contains instructions on how to "break down" the files used in the final docs.
#
def generate_rst_files(schema_rolne, breakdown_rolne, dest_dir, language="en"):
docs = {}
# initialize with root doc
root = breakdown_rolne["root"]
docs[root.value] = []
title = root.value
if root.has("title"):
title = str(root.get_value("title"))
docs[root.value].append("="*len(title))
docs[root.value].append(title)
docs[root.value].append("="*len(title))
docs[root.value].append('')
if root.has("add_body_file"):
for body_file in root.list_values("add_body_file"):
docs[root.value].append('.. include:: '+body_file)
docs[root.value].append('')
for sub in root.only('sub'):
docs[root.value].append('* :doc:`'+sub.value+'`')
# make subs
parse_rst(root, schema_rolne, docs, language)
# generate everything
for key in docs:
fh = open(dest_dir+"/"+key+".rst", 'w')
for line in docs[key]:
fh.write(line)
fh.write('\n')
fh.close()
return
def parse_rst(breakdown, schema_rolne, docs, language):
for sub in breakdown.only('sub'):
skip_vt = False
if schema_rolne.has(('name', sub.value)):
schema_sub = schema_rolne['name', sub.value]
else:
match = sub.value.split(".")[-1]
if schema_rolne.has(('match', match)):
schema_sub = schema_rolne['match', match]
skip_vt = True
else:
continue
docs[sub.value] = []
current = docs[sub.value]
# body
if schema_sub.has([('describe', language),('title')]):
title = schema_sub['describe', language].get_value('title')
else:
title = sub.value
current.append(title)
current.append('='*len(title))
current.append('')
if schema_sub.has([('value'),('type')]):
type = schema_sub['value'].get_value('type')
else:
type = 'string'
if type!='ignore':
if not skip_vt:
current.append('.. raw:: html')
current.append('')
current.append(' <pre><b>'+sub.value+'</b> <i>'+type+'</i></pre>')
current.append('')
current.append('..')
current.append('')
if schema_sub.has(('describe', language)):
d = schema_sub['describe', language]
if d.has('abstract'):
temp = ""
for paragraph in d.list_values('abstract'):
temp += paragraph + " "
current.append('*'+temp.strip()+'*')
current.append('')
if d.has('body'):
for paragraph in d.list_values('body'):
current.append(paragraph)
current.append('')
# items list
if schema_sub.has('search'):
current.append(".. sidebar:: Variations")
current.append(' ')
for v in schema_sub.only('search'):
current.append(' There are additional attributes based on **'+v.value+'** :')
current.append(' ')
for m in v.only('match'):
# head = sub.value.split(".")[0]
doc_name = sub.value+"."+v.value+'.'+m.value
current.append(' * ``'+str(m.value).strip()+'`` - :doc:`'+doc_name+'`')
sub.append("sub", doc_name)
sub["sub", doc_name].append("new_doc", "true")
current.append(' ')
parse_rst(sub, v, docs, language)
current.append('')
if schema_sub.has('name'):
current.append("''''''''''")
current.append("Attributes")
current.append("''''''''''")
current.append('')
current.extend(rst_list_attributes_recursive(schema_sub, language, sub.value))
return
def rst_list_attributes_recursive(schema, language, head):
result = []
for item in schema.only('name'):
if str(item.value)[0:2]!="__":
val_type = item['value'].get_value('type')
result.append('.. raw:: html')
result.append('')
if val_type=='ignore':
result.append(' <pre><b>'+str(item.value)+'</b></pre>')
else:
# TODO: add a hyperlink for val_type as gen'd by from st module
result.append(' <pre><b>'+str(item.value)+'</b> <i>'+val_type+'</i></pre>')
# if val_type!='radio_select':
# temp_list = st.rst(item['value'])
# for line in temp_list:
# result.append(' '+line)
result.append('')
result.append('..')
result.append('')
if item['value']['type'].has('choice'):
long_flag = False
match_list = []
if schema.has(('search', item.value)):
match_list = schema['search', item.value].list_values('match')
result.append(' The choice selected adds additional attributes. Click above to see them.')
long_flag = True
result.append(' choices:')
result.append(' ')
if len(item['value']['type'].list_values("choice"))<10:
long_flag = True
else:
for choice in item['value']['type'].only("choice"):
if choice.has('name'):
long_flag = True
if long_flag:
for choice in item['value']['type'].only("choice"):
if choice.value in match_list:
result.append(' * ``'+choice.value.strip()+'`` - :doc:`'+head+"."+item.value+'.'+choice.value+'`')
else:
result.append(' * ``'+choice.value.strip()+'``')
result.append(' ')
if choice.has('name'):
temp_list = rst_list_attributes_recursive(choice, language, head)
result.append(' The following can further define this choice:')
result.append(' ')
for line in temp_list:
result.append(' '+line)
result.append(' ')
else:
result.append('.. raw:: html')
result.append('')
result.append(' <select>')
for choice in item['value']['type'].only("choice"):
result.append(' <option>'+choice.value+'</option>')
result.append(' </select>')
result.append('')
result.append('..')
result.append('')
result.append(' ')
if item.has(('describe', language)):
d = item['describe', language]
if d.has('abstract'):
temp = ""
for paragraph in d.list_values('abstract'):
temp += paragraph + " "
result.append(' *'+temp.strip()+'*')
result.append(' ')
if d.has('body'):
for paragraph in d.list_values('body'):
result.append(' '+paragraph)
result.append(' ')
if item.has('name'):
temp_list = rst_list_attributes_recursive(item.only('name'), language, head)
result.append(' The following can further define this attribute:')
result.append(' ')
for line in temp_list:
result.append(' '+line)
result.append(' ')
result.append(' ')
return result
# eof: MARDS\doc.py
| mit |
HybridF5/tempest_debug | setup.py | 334 | 1028 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr>=1.8'],
pbr=True)
| apache-2.0 |
infoxchange/lettuce | tests/integration/lib/Django-1.3/django/utils/module_loading.py | 222 | 2306 | import imp
import os
import sys
def module_has_submodule(package, module_name):
"""See if 'module' is in 'package'."""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
for finder in sys.meta_path:
if finder.find_module(name):
return True
for entry in package.__path__: # No __path__, then not a package.
try:
# Try the cached finder.
finder = sys.path_importer_cache[entry]
if finder is None:
# Implicit import machinery should be used.
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
continue
# Else see if the finder knows of a loader.
elif finder.find_module(name):
return True
else:
continue
except KeyError:
# No cached finder, so try and make one.
for hook in sys.path_hooks:
try:
finder = hook(entry)
# XXX Could cache in sys.path_importer_cache
if finder.find_module(name):
return True
else:
# Once a finder is found, stop the search.
break
except ImportError:
# Continue the search for a finder.
continue
else:
# No finder found.
# Try the implicit import machinery if searching a directory.
if os.path.isdir(entry):
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
pass
# XXX Could insert None or NullImporter
else:
# Exhausted the search, so the module cannot be found.
return False
| gpl-3.0 |
mfwarren/FreeCoding | 2014/10/fc_2014_10_02.py | 1 | 1847 | #!/usr/bin/env python
#imports go here
#
# Free Coding session for 2014-10-02
# Written by Matt Warren
#
# example of 3-tier pattern
class Data:
data = [{"account": 234, "name":"bob"},
{"account": 643, "name":"joan"}]
def __iter__(self):
for d in self.data:
yield d
def find(self, account_number):
for d in self.data:
if d['account'] == account_number:
return d
class Controller:
def __init__(self):
self.data = Data()
def get_data(self):
return self.data
def get_name(self, account_number):
return self.data.find(account_number).get("name", None)
def get_accounts(self):
return [f['account'] for f in self.data]
class UI:
def __init__(self):
self.controller = Controller()
def print_names(self):
accounts = self.controller.get_accounts()
for acct in accounts:
print acct
print self.controller.get_name(acct)
if __name__=='__main__':
ui = UI()
ui.print_names()
##
#
# Quicksort
#
import random
numbers = random.sample(xrange(100), 100)
def swap(numbers, i, j):
temp = numbers[j]
numbers[j] = numbers[i]
numbers[i] = temp
def pivot(numbers, start_index, end_index):
q = numbers[start_index]
i = start_index + 1
j = end_index
while i <= j:
if numbers[i] <= q:
i = i+1
elif numbers[i] > q:
swap(numbers, i, j)
j = j - 1
swap(numbers, start_index, i-1)
if (i-2) > start_index:
pivot(numbers,start_index, i-2)
if end_index > i:
pivot(numbers, i, end_index)
print numbers
pivot(numbers,0,len(numbers)-1)
print numbers
# test_numbers = random.sample(xrange(10),3)
# print test_numbers
# swap(test_numbers, 1,2)
# print test_numbers
| mit |
yanlend/scikit-learn | sklearn/feature_selection/tests/test_base.py | 143 | 3670 | import numpy as np
from scipy import sparse as sp
from nose.tools import assert_raises, assert_equal
from numpy.testing import assert_array_equal
from sklearn.base import BaseEstimator
from sklearn.feature_selection.base import SelectorMixin
from sklearn.utils import check_array
class StepSelector(SelectorMixin, BaseEstimator):
"""Retain every `step` features (beginning with 0)"""
def __init__(self, step=2):
self.step = step
def fit(self, X, y=None):
X = check_array(X, 'csc')
self.n_input_feats = X.shape[1]
return self
def _get_support_mask(self):
mask = np.zeros(self.n_input_feats, dtype=bool)
mask[::self.step] = True
return mask
support = [True, False] * 5
support_inds = [0, 2, 4, 6, 8]
X = np.arange(20).reshape(2, 10)
Xt = np.arange(0, 20, 2).reshape(2, 5)
Xinv = X.copy()
Xinv[:, 1::2] = 0
y = [0, 1]
feature_names = list('ABCDEFGHIJ')
feature_names_t = feature_names[::2]
feature_names_inv = np.array(feature_names)
feature_names_inv[1::2] = ''
def test_transform_dense():
sel = StepSelector()
Xt_actual = sel.fit(X, y).transform(X)
Xt_actual2 = StepSelector().fit_transform(X, y)
assert_array_equal(Xt, Xt_actual)
assert_array_equal(Xt, Xt_actual2)
# Check dtype matches
assert_equal(np.int32, sel.transform(X.astype(np.int32)).dtype)
assert_equal(np.float32, sel.transform(X.astype(np.float32)).dtype)
# Check 1d list and other dtype:
names_t_actual = sel.transform([feature_names])
assert_array_equal(feature_names_t, names_t_actual.ravel())
# Check wrong shape raises error
assert_raises(ValueError, sel.transform, np.array([[1], [2]]))
def test_transform_sparse():
sparse = sp.csc_matrix
sel = StepSelector()
Xt_actual = sel.fit(sparse(X)).transform(sparse(X))
Xt_actual2 = sel.fit_transform(sparse(X))
assert_array_equal(Xt, Xt_actual.toarray())
assert_array_equal(Xt, Xt_actual2.toarray())
# Check dtype matches
assert_equal(np.int32, sel.transform(sparse(X).astype(np.int32)).dtype)
assert_equal(np.float32, sel.transform(sparse(X).astype(np.float32)).dtype)
# Check wrong shape raises error
assert_raises(ValueError, sel.transform, np.array([[1], [2]]))
def test_inverse_transform_dense():
sel = StepSelector()
Xinv_actual = sel.fit(X, y).inverse_transform(Xt)
assert_array_equal(Xinv, Xinv_actual)
# Check dtype matches
assert_equal(np.int32,
sel.inverse_transform(Xt.astype(np.int32)).dtype)
assert_equal(np.float32,
sel.inverse_transform(Xt.astype(np.float32)).dtype)
# Check 1d list and other dtype:
names_inv_actual = sel.inverse_transform([feature_names_t])
assert_array_equal(feature_names_inv, names_inv_actual.ravel())
# Check wrong shape raises error
assert_raises(ValueError, sel.inverse_transform, np.array([[1], [2]]))
def test_inverse_transform_sparse():
sparse = sp.csc_matrix
sel = StepSelector()
Xinv_actual = sel.fit(sparse(X)).inverse_transform(sparse(Xt))
assert_array_equal(Xinv, Xinv_actual.toarray())
# Check dtype matches
assert_equal(np.int32,
sel.inverse_transform(sparse(Xt).astype(np.int32)).dtype)
assert_equal(np.float32,
sel.inverse_transform(sparse(Xt).astype(np.float32)).dtype)
# Check wrong shape raises error
assert_raises(ValueError, sel.inverse_transform, np.array([[1], [2]]))
def test_get_support():
sel = StepSelector()
sel.fit(X, y)
assert_array_equal(support, sel.get_support())
assert_array_equal(support_inds, sel.get_support(indices=True))
| bsd-3-clause |
gef756/scipy | scipy/linalg/tests/test_basic.py | 27 | 34110 | #!/usr/bin/env python
#
# Created by: Pearu Peterson, March 2002
#
""" Test functions for linalg.basic module
"""
from __future__ import division, print_function, absolute_import
"""
Bugs:
1) solve.check_random_sym_complex fails if a is complex
and transpose(a) = conjugate(a) (a is Hermitian).
"""
__usage__ = """
Build linalg:
python setup_linalg.py build
Run tests if scipy is installed:
python -c 'import scipy;scipy.linalg.test()'
Run tests if linalg is not installed:
python tests/test_basic.py
"""
import numpy as np
from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
float32)
import numpy.linalg as linalg
from numpy.testing import (TestCase, rand, run_module_suite, assert_raises,
assert_equal, assert_almost_equal, assert_array_almost_equal, assert_,
assert_allclose, assert_array_equal)
from scipy.linalg import (solve, inv, det, lstsq, pinv, pinv2, pinvh, norm,
solve_banded, solveh_banded, solve_triangular, solve_circulant,
circulant, LinAlgError)
from scipy.linalg._testutils import assert_no_overwrite
def random(size):
return rand(*size)
class TestSolveBanded(TestCase):
def test_real(self):
a = array([[1.0, 20, 0, 0],
[-30, 4, 6, 0],
[2, 1, 20, 2],
[0, -1, 7, 14]])
ab = array([[0.0, 20, 6, 2],
[1, 4, 20, 14],
[-30, 1, 7, 0],
[2, -1, 0, 0]])
l,u = 2,1
b4 = array([10.0, 0.0, 2.0, 14.0])
b4by1 = b4.reshape(-1,1)
b4by2 = array([[2, 1],
[-30, 4],
[2, 3],
[1, 3]])
b4by4 = array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 1, 0, 0]])
for b in [b4, b4by1, b4by2, b4by4]:
x = solve_banded((l, u), ab, b)
assert_array_almost_equal(dot(a, x), b)
def test_complex(self):
a = array([[1.0, 20, 0, 0],
[-30, 4, 6, 0],
[2j, 1, 20, 2j],
[0, -1, 7, 14]])
ab = array([[0.0, 20, 6, 2j],
[1, 4, 20, 14],
[-30, 1, 7, 0],
[2j, -1, 0, 0]])
l,u = 2,1
b4 = array([10.0, 0.0, 2.0, 14.0j])
b4by1 = b4.reshape(-1,1)
b4by2 = array([[2, 1],
[-30, 4],
[2, 3],
[1, 3]])
b4by4 = array([[1, 0, 0, 0],
[0, 0, 0,1j],
[0, 1, 0, 0],
[0, 1, 0, 0]])
for b in [b4, b4by1, b4by2, b4by4]:
x = solve_banded((l, u), ab, b)
assert_array_almost_equal(dot(a, x), b)
def test_tridiag_real(self):
ab = array([[0.0, 20, 6, 2],
[1, 4, 20, 14],
[-30, 1, 7, 0]])
a = np.diag(ab[0,1:], 1) + np.diag(ab[1,:], 0) + np.diag(ab[2,:-1], -1)
b4 = array([10.0, 0.0, 2.0, 14.0])
b4by1 = b4.reshape(-1,1)
b4by2 = array([[2, 1],
[-30, 4],
[2, 3],
[1, 3]])
b4by4 = array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 1, 0, 0]])
for b in [b4, b4by1, b4by2, b4by4]:
x = solve_banded((1, 1), ab, b)
assert_array_almost_equal(dot(a, x), b)
def test_tridiag_complex(self):
ab = array([[0.0, 20, 6, 2j],
[1, 4, 20, 14],
[-30, 1, 7, 0]])
a = np.diag(ab[0,1:], 1) + np.diag(ab[1,:], 0) + np.diag(ab[2,:-1], -1)
b4 = array([10.0, 0.0, 2.0, 14.0j])
b4by1 = b4.reshape(-1,1)
b4by2 = array([[2, 1],
[-30, 4],
[2, 3],
[1, 3]])
b4by4 = array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 1, 0, 0]])
for b in [b4, b4by1, b4by2, b4by4]:
x = solve_banded((1, 1), ab, b)
assert_array_almost_equal(dot(a, x), b)
def test_check_finite(self):
a = array([[1.0, 20, 0, 0],
[-30, 4, 6, 0],
[2, 1, 20, 2],
[0, -1, 7, 14]])
ab = array([[0.0, 20, 6, 2],
[1, 4, 20, 14],
[-30, 1, 7, 0],
[2, -1, 0, 0]])
l,u = 2,1
b4 = array([10.0, 0.0, 2.0, 14.0])
x = solve_banded((l, u), ab, b4, check_finite=False)
assert_array_almost_equal(dot(a, x), b4)
def test_bad_shape(self):
ab = array([[0.0, 20, 6, 2],
[1, 4, 20, 14],
[-30, 1, 7, 0],
[2, -1, 0, 0]])
l,u = 2,1
bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1,4)
assert_raises(ValueError, solve_banded, (l, u), ab, bad)
assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
# Values of (l,u) are not compatible with ab.
assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
def test_1x1(self):
x = solve_banded((1, 1), [[0], [1], [0]], [[1, 2, 3]])
assert_array_equal(x, [[1.0, 2.0, 3.0]])
assert_equal(x.dtype, np.dtype('f8'))
class TestSolveHBanded(TestCase):
def test_01_upper(self):
# Solve
# [ 4 1 2 0] [1]
# [ 1 4 1 2] X = [4]
# [ 2 1 4 1] [1]
# [ 0 2 1 4] [2]
# with the RHS as a 1D array.
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0, 4.0, 4.0, 4.0]])
b = array([1.0, 4.0, 1.0, 2.0])
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_upper(self):
# Solve
# [ 4 1 2 0] [1 6]
# [ 1 4 1 2] X = [4 2]
# [ 2 1 4 1] [1 6]
# [ 0 2 1 4] [2 1]
#
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0, 4.0, 4.0, 4.0]])
b = array([[1.0, 6.0],
[4.0, 2.0],
[1.0, 6.0],
[2.0, 1.0]])
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, 0.0]])
assert_array_almost_equal(x, expected)
def test_03_upper(self):
# Solve
# [ 4 1 2 0] [1]
# [ 1 4 1 2] X = [4]
# [ 2 1 4 1] [1]
# [ 0 2 1 4] [2]
# with the RHS as a 2D array with shape (3,1).
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0, 4.0, 4.0, 4.0]])
b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1,1)
x = solveh_banded(ab, b)
assert_array_almost_equal(x, array([0.0, 1.0, 0.0, 0.0]).reshape(-1,1))
def test_01_lower(self):
# Solve
# [ 4 1 2 0] [1]
# [ 1 4 1 2] X = [4]
# [ 2 1 4 1] [1]
# [ 0 2 1 4] [2]
#
ab = array([[4.0, 4.0, 4.0, 4.0],
[1.0, 1.0, 1.0, -99],
[2.0, 2.0, 0.0, 0.0]])
b = array([1.0, 4.0, 1.0, 2.0])
x = solveh_banded(ab, b, lower=True)
assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_lower(self):
# Solve
# [ 4 1 2 0] [1 6]
# [ 1 4 1 2] X = [4 2]
# [ 2 1 4 1] [1 6]
# [ 0 2 1 4] [2 1]
#
ab = array([[4.0, 4.0, 4.0, 4.0],
[1.0, 1.0, 1.0, -99],
[2.0, 2.0, 0.0, 0.0]])
b = array([[1.0, 6.0],
[4.0, 2.0],
[1.0, 6.0],
[2.0, 1.0]])
x = solveh_banded(ab, b, lower=True)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, 0.0]])
assert_array_almost_equal(x, expected)
def test_01_float32(self):
# Solve
# [ 4 1 2 0] [1]
# [ 1 4 1 2] X = [4]
# [ 2 1 4 1] [1]
# [ 0 2 1 4] [2]
#
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0, 4.0, 4.0, 4.0]], dtype=float32)
b = array([1.0, 4.0, 1.0, 2.0], dtype=float32)
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_float32(self):
# Solve
# [ 4 1 2 0] [1 6]
# [ 1 4 1 2] X = [4 2]
# [ 2 1 4 1] [1 6]
# [ 0 2 1 4] [2 1]
#
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0, 4.0, 4.0, 4.0]], dtype=float32)
b = array([[1.0, 6.0],
[4.0, 2.0],
[1.0, 6.0],
[2.0, 1.0]], dtype=float32)
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, 0.0]])
assert_array_almost_equal(x, expected)
def test_01_complex(self):
# Solve
# [ 4 -j 2 0] [2-j]
# [ j 4 -j 2] X = [4-j]
# [ 2 j 4 -j] [4+j]
# [ 0 2 j 4] [2+j]
#
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, -1.0j, -1.0j, -1.0j],
[4.0, 4.0, 4.0, 4.0]])
b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j])
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
def test_02_complex(self):
# Solve
# [ 4 -j 2 0] [2-j 2+4j]
# [ j 4 -j 2] X = [4-j -1-j]
# [ 2 j 4 -j] [4+j 4+2j]
# [ 0 2 j 4] [2+j j]
#
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, -1.0j, -1.0j, -1.0j],
[4.0, 4.0, 4.0, 4.0]])
b = array([[2-1j, 2+4j],
[4.0-1j, -1-1j],
[4.0+1j, 4+2j],
[2+1j, 1j]])
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0j],
[1.0, 0.0],
[1.0, 1.0],
[0.0, 0.0]])
assert_array_almost_equal(x, expected)
def test_tridiag_01_upper(self):
# Solve
# [ 4 1 0] [1]
# [ 1 4 1] X = [4]
# [ 0 1 4] [1]
# with the RHS as a 1D array.
ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
b = array([1.0, 4.0, 1.0])
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_upper(self):
# Solve
# [ 4 1 0] [1 4]
# [ 1 4 1] X = [4 2]
# [ 0 1 4] [1 4]
#
ab = array([[-99, 1.0, 1.0],
[4.0, 4.0, 4.0]])
b = array([[1.0, 4.0],
[4.0, 2.0],
[1.0, 4.0]])
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0]])
assert_array_almost_equal(x, expected)
def test_tridiag_03_upper(self):
# Solve
# [ 4 1 0] [1]
# [ 1 4 1] X = [4]
# [ 0 1 4] [1]
# with the RHS as a 2D array with shape (3,1).
ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
b = array([1.0, 4.0, 1.0]).reshape(-1,1)
x = solveh_banded(ab, b)
assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1,1))
def test_tridiag_01_lower(self):
# Solve
# [ 4 1 0] [1]
# [ 1 4 1] X = [4]
# [ 0 1 4] [1]
#
ab = array([[4.0, 4.0, 4.0],
[1.0, 1.0, -99]])
b = array([1.0, 4.0, 1.0])
x = solveh_banded(ab, b, lower=True)
assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_lower(self):
# Solve
# [ 4 1 0] [1 4]
# [ 1 4 1] X = [4 2]
# [ 0 1 4] [1 4]
#
ab = array([[4.0, 4.0, 4.0],
[1.0, 1.0, -99]])
b = array([[1.0, 4.0],
[4.0, 2.0],
[1.0, 4.0]])
x = solveh_banded(ab, b, lower=True)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0]])
assert_array_almost_equal(x, expected)
def test_tridiag_01_float32(self):
# Solve
# [ 4 1 0] [1]
# [ 1 4 1] X = [4]
# [ 0 1 4] [1]
#
ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
b = array([1.0, 4.0, 1.0], dtype=float32)
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_float32(self):
# Solve
# [ 4 1 0] [1 4]
# [ 1 4 1] X = [4 2]
# [ 0 1 4] [1 4]
#
ab = array([[-99, 1.0, 1.0],
[4.0, 4.0, 4.0]], dtype=float32)
b = array([[1.0, 4.0],
[4.0, 2.0],
[1.0, 4.0]], dtype=float32)
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0]])
assert_array_almost_equal(x, expected)
def test_tridiag_01_complex(self):
# Solve
# [ 4 -j 0] [ -j]
# [ j 4 -j] X = [4-j]
# [ 0 j 4] [4+j]
#
ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
b = array([-1.0j, 4.0-1j, 4+1j])
x = solveh_banded(ab, b)
assert_array_almost_equal(x, [0.0, 1.0, 1.0])
def test_tridiag_02_complex(self):
# Solve
# [ 4 -j 0] [ -j 4j]
# [ j 4 -j] X = [4-j -1-j]
# [ 0 j 4] [4+j 4 ]
#
ab = array([[-99, -1.0j, -1.0j],
[4.0, 4.0, 4.0]])
b = array([[-1j, 4.0j],
[4.0-1j, -1.0-1j],
[4.0+1j, 4.0]])
x = solveh_banded(ab, b)
expected = array([[0.0, 1.0j],
[1.0, 0.0],
[1.0, 1.0]])
assert_array_almost_equal(x, expected)
def test_check_finite(self):
# Solve
# [ 4 1 0] [1]
# [ 1 4 1] X = [4]
# [ 0 1 4] [1]
# with the RHS as a 1D array.
ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
b = array([1.0, 4.0, 1.0])
x = solveh_banded(ab, b, check_finite=False)
assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_bad_shapes(self):
ab = array([[-99, 1.0, 1.0],
[4.0, 4.0, 4.0]])
b = array([[1.0, 4.0],
[4.0, 2.0]])
assert_raises(ValueError, solveh_banded, ab, b)
assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0])
assert_raises(ValueError, solveh_banded, ab, [1.0])
def test_1x1(self):
x = solveh_banded([[1]], [[1, 2, 3]])
assert_array_equal(x, [[1.0, 2.0, 3.0]])
assert_equal(x.dtype, np.dtype('f8'))
class TestSolve(TestCase):
def setUp(self):
np.random.seed(1234)
def test_20Feb04_bug(self):
a = [[1,1],[1.0,0]] # ok
x0 = solve(a,[1,0j])
assert_array_almost_equal(dot(a,x0),[1,0])
a = [[1,1],[1.2,0]] # gives failure with clapack.zgesv(..,rowmajor=0)
b = [1,0j]
x0 = solve(a,b)
assert_array_almost_equal(dot(a,x0),[1,0])
def test_simple(self):
a = [[1,20],[-30,4]]
for b in ([[1,0],[0,1]],[1,0],
[[2,1],[-30,4]]):
x = solve(a,b)
assert_array_almost_equal(dot(a,x),b)
def test_simple_sym(self):
a = [[2,3],[3,5]]
for lower in [0,1]:
for b in ([[1,0],[0,1]],[1,0]):
x = solve(a,b,sym_pos=1,lower=lower)
assert_array_almost_equal(dot(a,x),b)
def test_simple_sym_complex(self):
a = [[5,2],[2,4]]
for b in [[1j,0],
[[1j,1j],
[0,2]],
]:
x = solve(a,b,sym_pos=1)
assert_array_almost_equal(dot(a,x),b)
def test_simple_complex(self):
a = array([[5,2],[2j,4]],'D')
for b in [[1j,0],
[[1j,1j],
[0,2]],
[1,0j],
array([1,0],'D'),
]:
x = solve(a,b)
assert_array_almost_equal(dot(a,x),b)
def test_nils_20Feb04(self):
n = 2
A = random([n,n])+random([n,n])*1j
X = zeros((n,n),'D')
Ainv = inv(A)
R = identity(n)+identity(n)*0j
for i in arange(0,n):
r = R[:,i]
X[:,i] = solve(A,r)
assert_array_almost_equal(X,Ainv)
def test_random(self):
n = 20
a = random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
for i in range(4):
b = random([n,3])
x = solve(a,b)
assert_array_almost_equal(dot(a,x),b)
def test_random_complex(self):
n = 20
a = random([n,n]) + 1j * random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
for i in range(2):
b = random([n,3])
x = solve(a,b)
assert_array_almost_equal(dot(a,x),b)
def test_random_sym(self):
n = 20
a = random([n,n])
for i in range(n):
a[i,i] = abs(20*(.1+a[i,i]))
for j in range(i):
a[i,j] = a[j,i]
for i in range(4):
b = random([n])
x = solve(a,b,sym_pos=1)
assert_array_almost_equal(dot(a,x),b)
def test_random_sym_complex(self):
n = 20
a = random([n,n])
# a = a + 1j*random([n,n]) # XXX: with this the accuracy will be very low
for i in range(n):
a[i,i] = abs(20*(.1+a[i,i]))
for j in range(i):
a[i,j] = conjugate(a[j,i])
b = random([n])+2j*random([n])
for i in range(2):
x = solve(a,b,sym_pos=1)
assert_array_almost_equal(dot(a,x),b)
def test_check_finite(self):
a = [[1,20],[-30,4]]
for b in ([[1,0],[0,1]],[1,0],
[[2,1],[-30,4]]):
x = solve(a,b, check_finite=False)
assert_array_almost_equal(dot(a,x),b)
class TestSolveTriangular(TestCase):
def test_simple(self):
"""
solve_triangular on a simple 2x2 matrix.
"""
A = array([[1,0], [1,2]])
b = [1, 1]
sol = solve_triangular(A, b, lower=True)
assert_array_almost_equal(sol, [1, 0])
# check that it works also for non-contiguous matrices
sol = solve_triangular(A.T, b, lower=False)
assert_array_almost_equal(sol, [.5, .5])
# and that it gives the same result as trans=1
sol = solve_triangular(A, b, lower=True, trans=1)
assert_array_almost_equal(sol, [.5, .5])
b = identity(2)
sol = solve_triangular(A, b, lower=True, trans=1)
assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
def test_simple_complex(self):
"""
solve_triangular on a simple 2x2 complex matrix
"""
A = array([[1+1j, 0], [1j, 2]])
b = identity(2)
sol = solve_triangular(A, b, lower=True, trans=1)
assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
def test_check_finite(self):
"""
solve_triangular on a simple 2x2 matrix.
"""
A = array([[1,0], [1,2]])
b = [1, 1]
sol = solve_triangular(A, b, lower=True, check_finite=False)
assert_array_almost_equal(sol, [1, 0])
class TestInv(TestCase):
def setUp(self):
np.random.seed(1234)
def test_simple(self):
a = [[1,2],[3,4]]
a_inv = inv(a)
assert_array_almost_equal(dot(a,a_inv),
[[1,0],[0,1]])
a = [[1,2,3],[4,5,6],[7,8,10]]
a_inv = inv(a)
assert_array_almost_equal(dot(a,a_inv),
[[1,0,0],[0,1,0],[0,0,1]])
def test_random(self):
n = 20
for i in range(4):
a = random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
a_inv = inv(a)
assert_array_almost_equal(dot(a,a_inv),
identity(n))
def test_simple_complex(self):
a = [[1,2],[3,4j]]
a_inv = inv(a)
assert_array_almost_equal(dot(a,a_inv),
[[1,0],[0,1]])
def test_random_complex(self):
n = 20
for i in range(4):
a = random([n,n])+2j*random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
a_inv = inv(a)
assert_array_almost_equal(dot(a,a_inv),
identity(n))
def test_check_finite(self):
a = [[1,2],[3,4]]
a_inv = inv(a, check_finite=False)
assert_array_almost_equal(dot(a,a_inv),
[[1,0],[0,1]])
class TestDet(TestCase):
def setUp(self):
np.random.seed(1234)
def test_simple(self):
a = [[1,2],[3,4]]
a_det = det(a)
assert_almost_equal(a_det,-2.0)
def test_simple_complex(self):
a = [[1,2],[3,4j]]
a_det = det(a)
assert_almost_equal(a_det,-6+4j)
def test_random(self):
basic_det = linalg.det
n = 20
for i in range(4):
a = random([n,n])
d1 = det(a)
d2 = basic_det(a)
assert_almost_equal(d1,d2)
def test_random_complex(self):
basic_det = linalg.det
n = 20
for i in range(4):
a = random([n,n]) + 2j*random([n,n])
d1 = det(a)
d2 = basic_det(a)
assert_allclose(d1, d2, rtol=1e-13)
def test_check_finite(self):
a = [[1,2],[3,4]]
a_det = det(a, check_finite=False)
assert_almost_equal(a_det,-2.0)
def direct_lstsq(a,b,cmplx=0):
at = transpose(a)
if cmplx:
at = conjugate(at)
a1 = dot(at, a)
b1 = dot(at, b)
return solve(a1, b1)
class TestLstsq(TestCase):
def setUp(self):
np.random.seed(1234)
def test_random_overdet_large(self):
# bug report: Nils Wagner
n = 200
a = random([n,2])
for i in range(2):
a[i,i] = 20*(.1+a[i,i])
b = random([n,3])
x = lstsq(a,b)[0]
assert_array_almost_equal(x,direct_lstsq(a,b))
def test_simple_exact(self):
a = [[1,20],[-30,4]]
for b in ([[1,0],[0,1]],[1,0],
[[2,1],[-30,4]]):
x = lstsq(a,b)[0]
assert_array_almost_equal(dot(a,x),b)
def test_simple_overdet(self):
a = [[1,2],[4,5],[3,4]]
b = [1,2,3]
x,res,r,s = lstsq(a,b)
assert_array_almost_equal(x,direct_lstsq(a,b))
assert_almost_equal((abs(dot(a,x) - b)**2).sum(axis=0), res)
def test_simple_overdet_complex(self):
a = [[1+2j,2],[4,5],[3,4]]
b = [1,2+4j,3]
x,res,r,s = lstsq(a,b)
assert_array_almost_equal(x,direct_lstsq(a,b,cmplx=1))
assert_almost_equal(res, (abs(dot(a,x) - b)**2).sum(axis=0))
def test_simple_underdet(self):
a = [[1,2,3],[4,5,6]]
b = [1,2]
x,res,r,s = lstsq(a,b)
# XXX: need independent check
assert_array_almost_equal(x,[-0.05555556, 0.11111111, 0.27777778])
def test_random_exact(self):
n = 20
a = random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
for i in range(4):
b = random([n,3])
x = lstsq(a,b)[0]
assert_array_almost_equal(dot(a,x),b)
def test_random_complex_exact(self):
n = 20
a = random([n,n]) + 1j * random([n,n])
for i in range(n):
a[i,i] = 20*(.1+a[i,i])
for i in range(2):
b = random([n,3])
x = lstsq(a,b)[0]
assert_array_almost_equal(dot(a,x),b)
def test_random_overdet(self):
n = 20
m = 15
a = random([n,m])
for i in range(m):
a[i,i] = 20*(.1+a[i,i])
for i in range(4):
b = random([n,3])
x,res,r,s = lstsq(a,b)
assert_(r == m, 'unexpected efficient rank')
# XXX: check definition of res
assert_array_almost_equal(x,direct_lstsq(a,b))
def test_random_complex_overdet(self):
n = 20
m = 15
a = random([n,m]) + 1j * random([n,m])
for i in range(m):
a[i,i] = 20*(.1+a[i,i])
for i in range(2):
b = random([n,3])
x,res,r,s = lstsq(a,b)
assert_(r == m, 'unexpected efficient rank')
# XXX: check definition of res
assert_array_almost_equal(x,direct_lstsq(a,b,1))
def test_check_finite(self):
a = [[1,20],[-30,4]]
for b in ([[1,0],[0,1]],[1,0],
[[2,1],[-30,4]]):
x = lstsq(a,b, check_finite=False)[0]
assert_array_almost_equal(dot(a,x),b)
class TestPinv(TestCase):
def test_simple_real(self):
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
a_pinv = pinv(a)
assert_array_almost_equal(dot(a,a_pinv), np.eye(3))
a_pinv = pinv2(a)
assert_array_almost_equal(dot(a,a_pinv), np.eye(3))
def test_simple_complex(self):
a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+ 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], dtype=float))
a_pinv = pinv(a)
assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
a_pinv = pinv2(a)
assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
def test_simple_singular(self):
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
a_pinv = pinv(a)
a_pinv2 = pinv2(a)
assert_array_almost_equal(a_pinv,a_pinv2)
def test_simple_cols(self):
a = array([[1, 2, 3], [4, 5, 6]], dtype=float)
a_pinv = pinv(a)
a_pinv2 = pinv2(a)
assert_array_almost_equal(a_pinv,a_pinv2)
def test_simple_rows(self):
a = array([[1, 2], [3, 4], [5, 6]], dtype=float)
a_pinv = pinv(a)
a_pinv2 = pinv2(a)
assert_array_almost_equal(a_pinv,a_pinv2)
def test_check_finite(self):
a = array([[1,2,3],[4,5,6.],[7,8,10]])
a_pinv = pinv(a, check_finite=False)
assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]])
a_pinv = pinv2(a, check_finite=False)
assert_array_almost_equal(dot(a,a_pinv),[[1,0,0],[0,1,0],[0,0,1]])
class TestPinvSymmetric(TestCase):
def test_simple_real(self):
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
a = np.dot(a, a.T)
a_pinv = pinvh(a)
assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
def test_nonpositive(self):
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
a = np.dot(a, a.T)
u, s, vt = np.linalg.svd(a)
s[0] *= -1
a = np.dot(u * s, vt) # a is now symmetric non-positive and singular
a_pinv = pinv2(a)
a_pinvh = pinvh(a)
assert_array_almost_equal(a_pinv, a_pinvh)
def test_simple_complex(self):
a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+ 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], dtype=float))
a = np.dot(a, a.conj().T)
a_pinv = pinvh(a)
assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
class TestVectorNorms(object):
def test_types(self):
for dtype in np.typecodes['AllFloat']:
x = np.array([1,2,3], dtype=dtype)
tol = max(1e-15, np.finfo(dtype).eps.real * 20)
assert_allclose(norm(x), np.sqrt(14), rtol=tol)
assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
for dtype in np.typecodes['Complex']:
x = np.array([1j,2j,3j], dtype=dtype)
tol = max(1e-15, np.finfo(dtype).eps.real * 20)
assert_allclose(norm(x), np.sqrt(14), rtol=tol)
assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
def test_overflow(self):
# unlike numpy's norm, this one is
# safer on overflow
a = array([1e20], dtype=float32)
assert_almost_equal(norm(a), a)
def test_stable(self):
# more stable than numpy's norm
a = array([1e4] + [1]*10000, dtype=float32)
try:
# snrm in double precision; we obtain the same as for float64
# -- large atol needed due to varying blas implementations
assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2)
except AssertionError:
# snrm implemented in single precision, == np.linalg.norm result
msg = ": Result should equal either 0.0 or 0.5 (depending on " \
"implementation of snrm2)."
assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
def test_zero_norm(self):
assert_equal(norm([1,0,3], 0), 2)
assert_equal(norm([1,2,3], 0), 3)
class TestMatrixNorms(object):
def test_matrix_norms(self):
# Not all of these are matrix norms in the most technical sense.
np.random.seed(1234)
for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4):
for t in np.single, np.double, np.csingle, np.cdouble, np.int64:
A = 10 * np.random.randn(n, m).astype(t)
if np.issubdtype(A.dtype, np.complexfloating):
A = (A + 10j * np.random.randn(n, m)).astype(t)
t_high = np.cdouble
else:
t_high = np.double
for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf):
actual = norm(A, ord=order)
desired = np.linalg.norm(A, ord=order)
# SciPy may return higher precision matrix norms.
# This is a consequence of using LAPACK.
if not np.allclose(actual, desired):
desired = np.linalg.norm(A.astype(t_high), ord=order)
np.assert_allclose(actual, desired)
class TestOverwrite(object):
def test_solve(self):
assert_no_overwrite(solve, [(3,3), (3,)])
def test_solve_triangular(self):
assert_no_overwrite(solve_triangular, [(3,3), (3,)])
def test_solve_banded(self):
assert_no_overwrite(lambda ab, b: solve_banded((2,1), ab, b),
[(4,6), (6,)])
def test_solveh_banded(self):
assert_no_overwrite(solveh_banded, [(2,6), (6,)])
def test_inv(self):
assert_no_overwrite(inv, [(3,3)])
def test_det(self):
assert_no_overwrite(det, [(3,3)])
def test_lstsq(self):
assert_no_overwrite(lstsq, [(3,2), (3,)])
def test_pinv(self):
assert_no_overwrite(pinv, [(3,3)])
def test_pinv2(self):
assert_no_overwrite(pinv2, [(3,3)])
def test_pinvh(self):
assert_no_overwrite(pinvh, [(3,3)])
class TestSolveCirculant(TestCase):
def test_basic1(self):
c = np.array([1, 2, 3, 5])
b = np.array([1, -1, 1, 0])
x = solve_circulant(c, b)
y = solve(circulant(c), b)
assert_allclose(x, y)
def test_basic2(self):
# b is a 2-d matrix.
c = np.array([1, 2, -3, -5])
b = np.arange(12).reshape(4, 3)
x = solve_circulant(c, b)
y = solve(circulant(c), b)
assert_allclose(x, y)
def test_basic3(self):
# b is a 3-d matrix.
c = np.array([1, 2, -3, -5])
b = np.arange(24).reshape(4, 3, 2)
x = solve_circulant(c, b)
y = solve(circulant(c), b)
assert_allclose(x, y)
def test_complex(self):
# Complex b and c
c = np.array([1+2j, -3, 4j, 5])
b = np.arange(8).reshape(4, 2) + 0.5j
x = solve_circulant(c, b)
y = solve(circulant(c), b)
assert_allclose(x, y)
def test_random_b_and_c(self):
# Random b and c
np.random.seed(54321)
c = np.random.randn(50)
b = np.random.randn(50)
x = solve_circulant(c, b)
y = solve(circulant(c), b)
assert_allclose(x, y)
def test_singular(self):
# c gives a singular circulant matrix.
c = np.array([1, 1, 0, 0])
b = np.array([1, 2, 3, 4])
x = solve_circulant(c, b, singular='lstsq')
y, res, rnk, s = lstsq(circulant(c), b)
assert_allclose(x, y)
assert_raises(LinAlgError, solve_circulant, x, y)
def test_axis_args(self):
# Test use of caxis, baxis and outaxis.
# c has shape (2, 1, 4)
c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
# b has shape (3, 4)
b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
x = solve_circulant(c, b, baxis=1)
assert_equal(x.shape, (4, 2, 3))
expected = np.empty_like(x)
expected[:, 0, :] = solve(circulant(c[0]), b.T)
expected[:, 1, :] = solve(circulant(c[1]), b.T)
assert_allclose(x, expected)
x = solve_circulant(c, b, baxis=1, outaxis=-1)
assert_equal(x.shape, (2, 3, 4))
assert_allclose(np.rollaxis(x, -1), expected)
# np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3).
x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1)
assert_equal(x.shape, (4, 2, 3))
assert_allclose(x, expected)
if __name__ == "__main__":
run_module_suite()
| bsd-3-clause |
MediaSapiens/wavesf | django/contrib/localflavor/ch/forms.py | 256 | 3951 | """
Swiss-specific Form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
id_re = re.compile(r"^(?P<idnumber>\w{8})(?P<pos9>(\d{1}|<))(?P<checksum>\d{1})$")
phone_digits_re = re.compile(r'^0([1-9]{1})\d{8}$')
class CHZipCodeField(RegexField):
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXX.'),
}
def __init__(self, *args, **kwargs):
super(CHZipCodeField, self).__init__(r'^\d{4}$',
max_length=None, min_length=None, *args, **kwargs)
class CHPhoneNumberField(Field):
"""
Validate local Swiss phone number (not international ones)
The correct format is '0XX XXX XX XX'.
'0XX.XXX.XX.XX' and '0XXXXXXXXX' validate but are corrected to
'0XX XXX XX XX'.
"""
default_error_messages = {
'invalid': 'Phone numbers must be in 0XX XXX XX XX format.',
}
def clean(self, value):
super(CHPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
value = re.sub('(\.|\s|/|-)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
return u'%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10])
raise ValidationError(self.error_messages['invalid'])
class CHStateSelect(Select):
"""
A Select widget that uses a list of CH states as its choices.
"""
def __init__(self, attrs=None):
from ch_states import STATE_CHOICES # relative import
super(CHStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
class CHIdentityCardNumberField(Field):
"""
A Swiss identity card number.
Checks the following rules to determine whether the number is valid:
* Conforms to the X1234567<0 or 1234567890 format.
* Included checksums match calculated checksums
Algorithm is documented at http://adi.kousz.ch/artikel/IDCHE.htm
"""
default_error_messages = {
'invalid': _('Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.'),
}
def has_valid_checksum(self, number):
given_number, given_checksum = number[:-1], number[-1]
new_number = given_number
calculated_checksum = 0
fragment = ""
parameter = 7
first = str(number[:1])
if first.isalpha():
num = ord(first.upper()) - 65
if num < 0 or num > 8:
return False
new_number = str(num) + new_number[1:]
new_number = new_number[:8] + '0'
if not new_number.isdigit():
return False
for i in range(len(new_number)):
fragment = int(new_number[i])*parameter
calculated_checksum += fragment
if parameter == 1:
parameter = 7
elif parameter == 3:
parameter = 1
elif parameter ==7:
parameter = 3
return str(calculated_checksum)[-1] == given_checksum
def clean(self, value):
super(CHIdentityCardNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
match = re.match(id_re, value)
if not match:
raise ValidationError(self.error_messages['invalid'])
idnumber, pos9, checksum = match.groupdict()['idnumber'], match.groupdict()['pos9'], match.groupdict()['checksum']
if idnumber == '00000000' or \
idnumber == 'A0000000':
raise ValidationError(self.error_messages['invalid'])
all_digits = "%s%s%s" % (idnumber, pos9, checksum)
if not self.has_valid_checksum(all_digits):
raise ValidationError(self.error_messages['invalid'])
return u'%s%s%s' % (idnumber, pos9, checksum)
| bsd-3-clause |
chekunkov/scrapy | scrapy/dupefilter.py | 27 | 2133 | from __future__ import print_function
import os
from scrapy import log
from scrapy.utils.job import job_dir
from scrapy.utils.request import request_fingerprint
class BaseDupeFilter(object):
@classmethod
def from_settings(cls, settings):
return cls()
def request_seen(self, request):
return False
def open(self): # can return deferred
pass
def close(self, reason): # can return a deferred
pass
def log(self, request, spider): # log that a request has been filtered
pass
class RFPDupeFilter(BaseDupeFilter):
"""Request Fingerprint duplicates filter"""
def __init__(self, path=None, debug=False):
self.file = None
self.fingerprints = set()
self.logdupes = True
self.debug = debug
if path:
self.file = open(os.path.join(path, 'requests.seen'), 'a+')
self.fingerprints.update(x.rstrip() for x in self.file)
@classmethod
def from_settings(cls, settings):
debug = settings.getbool('DUPEFILTER_DEBUG')
return cls(job_dir(settings), debug)
def request_seen(self, request):
fp = self.request_fingerprint(request)
if fp in self.fingerprints:
return True
self.fingerprints.add(fp)
if self.file:
self.file.write(fp + os.linesep)
def request_fingerprint(self, request):
return request_fingerprint(request)
def close(self, reason):
if self.file:
self.file.close()
def log(self, request, spider):
if self.debug:
fmt = "Filtered duplicate request: %(request)s"
log.msg(format=fmt, request=request, level=log.DEBUG, spider=spider)
elif self.logdupes:
fmt = ("Filtered duplicate request: %(request)s"
" - no more duplicates will be shown"
" (see DUPEFILTER_DEBUG to show all duplicates)")
log.msg(format=fmt, request=request, level=log.DEBUG, spider=spider)
self.logdupes = False
spider.crawler.stats.inc_value('dupefilter/filtered', spider=spider)
| bsd-3-clause |
gedare/gem5 | util/cpt_upgrader.py | 10 | 12775 | #!/usr/bin/env python2
# Copyright (c) 2012-2013,2015-2016 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: Ali Saidi
# Curtis Dunham
#
# This python code is used to migrate checkpoints that were created in one
# version of the simulator to newer version. As features are added or bugs are
# fixed some of the state that needs to be checkpointed can change. If you have
# many historic checkpoints that you use, manually editing them to fix them is
# both time consuming and error-prone.
# This script provides a way to migrate checkpoints to the newer repository in
# a programmatic way. It can be imported into another script or used on the
# command line. From the command line the script will either migrate every
# checkpoint it finds recursively (-r option) or a single checkpoint. When a
# change is made to the gem5 repository that breaks previous checkpoints an
# upgrade() method should be implemented in its own .py file and placed in
# src/util/cpt_upgraders/. For each upgrader whose tag is not present in
# the checkpoint tag list, the upgrade() method will be run, passing in a
# ConfigParser object which contains the open file. As these operations can
# be isa specific the method can verify the isa and use regexes to find the
# correct sections that need to be updated.
# It is also possible to use this mechanism to revert prior tags. In this
# case, implement a downgrade() method instead. Dependencies should still
# work naturally - a tag depending on a tag with a downgrader means that it
# insists on the other tag being removed and its downgrader executed before
# its upgrader (or downgrader) can run. It is still the case that a tag
# can only be used once.
# Dependencies between tags are expressed by two variables at the top-level
# of the upgrader script: "depends" can be either a string naming another
# tag that it depends upon or a list of such strings; and "fwd_depends"
# accepts the same datatypes but it reverses the sense of the dependency
# arrow(s) -- it expresses that that tag depends upon the tag of the current
# upgrader. This can be especially valuable when maintaining private
# upgraders in private branches.
import ConfigParser
import glob, types, sys, os
import os.path as osp
verbose_print = False
def verboseprint(*args):
if not verbose_print:
return
for arg in args:
print arg,
print
class Upgrader:
tag_set = set()
untag_set = set() # tags to remove by downgrading
by_tag = {}
legacy = {}
def __init__(self, filename):
self.filename = filename
execfile(filename, {}, self.__dict__)
if not hasattr(self, 'tag'):
self.tag = osp.basename(filename)[:-3]
if not hasattr(self, 'depends'):
self.depends = []
elif isinstance(self.depends, str):
self.depends = [self.depends]
if not isinstance(self.depends, list):
print "Error: 'depends' for %s is the wrong type" % self.tag
sys.exit(1)
if hasattr(self, 'fwd_depends'):
if isinstance(self.fwd_depends, str):
self.fwd_depends = [self.fwd_depends]
else:
self.fwd_depends = []
if not isinstance(self.fwd_depends, list):
print "Error: 'fwd_depends' for %s is the wrong type" % self.tag
sys.exit(1)
if hasattr(self, 'upgrader'):
if not isinstance(self.upgrader, types.FunctionType):
print "Error: 'upgrader' for %s is %s, not function" \
% (self.tag, type(self))
sys.exit(1)
Upgrader.tag_set.add(self.tag)
elif hasattr(self, 'downgrader'):
if not isinstance(self.downgrader, types.FunctionType):
print "Error: 'downgrader' for %s is %s, not function" \
% (self.tag, type(self))
sys.exit(1)
Upgrader.untag_set.add(self.tag)
else:
print "Error: no upgrader or downgrader method for", self.tag
sys.exit(1)
if hasattr(self, 'legacy_version'):
Upgrader.legacy[self.legacy_version] = self
Upgrader.by_tag[self.tag] = self
def ready(self, tags):
for dep in self.depends:
if dep not in tags:
return False
return True
def update(self, cpt, tags):
if hasattr(self, 'upgrader'):
self.upgrader(cpt)
tags.add(self.tag)
verboseprint("applied upgrade for", self.tag)
else:
self.downgrader(cpt)
tags.remove(self.tag)
verboseprint("applied downgrade for", self.tag)
@staticmethod
def get(tag):
return Upgrader.by_tag[tag]
@staticmethod
def load_all():
util_dir = osp.dirname(osp.abspath(__file__))
for py in glob.glob(util_dir + '/cpt_upgraders/*.py'):
Upgrader(py)
# make linear dependences for legacy versions
i = 3
while i in Upgrader.legacy:
Upgrader.legacy[i].depends = [Upgrader.legacy[i-1].tag]
i = i + 1
# resolve forward dependencies and audit normal dependencies
for tag, upg in Upgrader.by_tag.items():
for fd in upg.fwd_depends:
if fd not in Upgrader.by_tag:
print "Error: '%s' cannot (forward) depend on "\
"nonexistent tag '%s'" % (fd, tag)
sys.exit(1)
Upgrader.by_tag[fd].depends.append(tag)
for dep in upg.depends:
if dep not in Upgrader.by_tag:
print "Error: '%s' cannot depend on "\
"nonexistent tag '%s'" % (tag, dep)
sys.exit(1)
def process_file(path, **kwargs):
if not osp.isfile(path):
import errno
raise IOError(ennro.ENOENT, "No such file", path)
verboseprint("Processing file %s...." % path)
if kwargs.get('backup', True):
import shutil
shutil.copyfile(path, path + '.bak')
cpt = ConfigParser.SafeConfigParser()
# gem5 is case sensitive with paramaters
cpt.optionxform = str
# Read the current data
cpt_file = file(path, 'r')
cpt.readfp(cpt_file)
cpt_file.close()
change = False
# Make sure we know what we're starting from
if cpt.has_option('root','cpt_ver'):
cpt_ver = cpt.getint('root','cpt_ver')
# Legacy linear checkpoint version
# convert to list of tags before proceeding
tags = set([])
for i in xrange(2, cpt_ver+1):
tags.add(Upgrader.legacy[i].tag)
verboseprint("performed legacy version -> tags conversion")
change = True
cpt.remove_option('root', 'cpt_ver')
elif cpt.has_option('Globals','version_tags'):
tags = set((''.join(cpt.get('Globals','version_tags'))).split())
else:
print "fatal: no version information in checkpoint"
exit(1)
verboseprint("has tags", ' '.join(tags))
# If the current checkpoint has a tag we don't know about, we have
# a divergence that (in general) must be addressed by (e.g.) merging
# simulator support for its changes.
unknown_tags = tags - (Upgrader.tag_set | Upgrader.untag_set)
if unknown_tags:
print "warning: upgrade script does not recognize the following "\
"tags in this checkpoint:", ' '.join(unknown_tags)
# Apply migrations for tags not in checkpoint and tags present for which
# downgraders are present, respecting dependences
to_apply = (Upgrader.tag_set - tags) | (Upgrader.untag_set & tags)
while to_apply:
ready = set([ t for t in to_apply if Upgrader.get(t).ready(tags) ])
if not ready:
print "could not apply these upgrades:", ' '.join(to_apply)
print "update dependences impossible to resolve; aborting"
exit(1)
for tag in ready:
Upgrader.get(tag).update(cpt, tags)
change = True
to_apply -= ready
if not change:
verboseprint("...nothing to do")
return
cpt.set('Globals', 'version_tags', ' '.join(tags))
# Write the old data back
verboseprint("...completed")
cpt.write(file(path, 'w'))
if __name__ == '__main__':
from optparse import OptionParser, SUPPRESS_HELP
parser = OptionParser("usage: %prog [options] <filename or directory>")
parser.add_option("-r", "--recurse", action="store_true",
help="Recurse through all subdirectories modifying "\
"each checkpoint that is found")
parser.add_option("-N", "--no-backup", action="store_false",
dest="backup", default=True,
help="Do no backup each checkpoint before modifying it")
parser.add_option("-v", "--verbose", action="store_true",
help="Print out debugging information as")
parser.add_option("--get-cc-file", action="store_true",
# used during build; generate src/sim/tags.cc and exit
help=SUPPRESS_HELP)
(options, args) = parser.parse_args()
verbose_print = options.verbose
Upgrader.load_all()
if options.get_cc_file:
print "// this file is auto-generated by util/cpt_upgrader.py"
print "#include <string>"
print "#include <set>"
print
print "std::set<std::string> version_tags = {"
for tag in Upgrader.tag_set:
print " \"%s\"," % tag
print "};"
exit(0)
elif len(args) != 1:
parser.error("You must specify a checkpoint file to modify or a "\
"directory of checkpoints to recursively update")
# Deal with shell variables and ~
path = osp.expandvars(osp.expanduser(args[0]))
# Process a single file if we have it
if osp.isfile(path):
process_file(path, **vars(options))
# Process an entire directory
elif osp.isdir(path):
cpt_file = osp.join(path, 'm5.cpt')
if options.recurse:
# Visit very file and see if it matches
for root,dirs,files in os.walk(path):
for name in files:
if name == 'm5.cpt':
process_file(osp.join(root,name), **vars(options))
for dir in dirs:
pass
# Maybe someone passed a cpt.XXXXXXX directory and not m5.cpt
elif osp.isfile(cpt_file):
process_file(cpt_file, **vars(options))
else:
print "Error: checkpoint file not found at in %s " % path,
print "and recurse not specified"
sys.exit(1)
sys.exit(0)
| bsd-3-clause |
alfanugraha/LUMENS-repo | processing/modeler/ModelerArrowItem.py | 6 | 5685 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Portions of this code have been taken and adapted from PyQt
examples, released under the following license terms
#############################################################################
#
# Copyright (C) 2010 Riverbank Computing Limited.
# Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
#
# This file is part of the examples of PyQt.
#
# $QT_BEGIN_LICENSE:BSD$
# You may use this file under the terms of the BSD license as follows:
#
# "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 Nokia Corporation and its Subsidiary(-ies) 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."
# $QT_END_LICENSE$
#
***************************************************************************
"""
import math
from PyQt4 import QtCore, QtGui
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.modeler.ModelerGraphicItem import ModelerGraphicItem
class ModelerArrowItem(QtGui.QGraphicsPathItem):
def __init__(self, startItem, outputIndex, endItem, paramIndex,
parent=None, scene=None):
super(ModelerArrowItem, self).__init__(parent, scene)
self.arrowHead = QtGui.QPolygonF()
self.paramIndex = paramIndex
self.outputIndex = outputIndex
self.myStartItem = startItem
self.myEndItem = endItem
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, False)
self.myColor = QtCore.Qt.gray
self.setPen(QtGui.QPen(self.myColor, 1, QtCore.Qt.SolidLine,
QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
self.setZValue(0)
def startItem(self):
return self.myStartItem
def endItem(self):
return self.myEndItem
def paint(self, painter, option, widget=None):
startItem = self.myStartItem
endItem = self.myEndItem
myPen = self.pen()
myPen.setColor(self.myColor)
painter.setPen(myPen)
painter.setBrush(self.myColor)
controlPoints = []
endPt = self.endItem().getLinkPointForParameter(self.paramIndex)
startPt = self.startItem().getLinkPointForOutput(self.outputIndex)
if isinstance(self.startItem().element, GeoAlgorithm):
if self.startItem().element.outputs:
controlPoints.append(startItem.pos() + startPt)
controlPoints.append(startItem.pos() + startPt
+ QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt
- QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt)
pt = QtCore.QPointF(startItem.pos() + startPt
+ QtCore.QPointF(-3, -3))
painter.drawEllipse(pt.x(), pt.y(), 6, 6)
pt = QtCore.QPointF(endItem.pos() + endPt +
QtCore.QPointF(-3, -3))
painter.drawEllipse(pt.x(), pt.y(), 6, 6)
else:
# Case where there is a dependency on an algorithm not
# on an output
controlPoints.append(startItem.pos() + startPt)
controlPoints.append(startItem.pos() + startPt
+ QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt
- QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt)
else:
controlPoints.append(startItem.pos())
controlPoints.append(startItem.pos()
+ QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt
- QtCore.QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0))
controlPoints.append(endItem.pos() + endPt)
pt = QtCore.QPointF(endItem.pos() + endPt + QtCore.QPointF(-3, -3))
painter.drawEllipse(pt.x(), pt.y(), 6, 6)
path = QtGui.QPainterPath()
path.moveTo(controlPoints[0])
path.cubicTo(*controlPoints[1:])
painter.strokePath(path, painter.pen())
self.setPath(path)
| gpl-2.0 |
ye-zhi/project-epsilon | code/utils/scripts/noise-pca_script.py | 1 | 13894 | """
This script is used to design the design matrix for our linear regression.
We explore the influence of linear and quadratic drifts on the model
performance.
Script for the raw data.
Run with:
python noise-pca_script.py
from this directory
"""
from __future__ import print_function, division
import sys, os, pdb
from scipy import ndimage
from scipy.ndimage import gaussian_filter
from matplotlib import colors
from os.path import splitext
from scipy.stats import t as t_dist
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
import nibabel as nib
import scipy
import pprint as pp
import json
#Specicy the path for functions
sys.path.append(os.path.join(os.path.dirname(__file__), "../functions/"))
sys.path.append(os.path.join(os.path.dirname(__file__), "./"))
from smoothing import *
from diagnostics import *
from glm import *
from plot_mosaic import *
from mask_filtered_data import *
# Locate the paths
project_path = '../../../'
data_path = project_path+'data/ds005/'
path_dict = {'data_filtered':{
'type' : 'filtered',
'feat' : '.feat/',
'bold_img_name' : 'filtered_func_data_mni.nii.gz',
'run_path' : 'model/model001/'
},
'data_original':{
'type' : '',
'feat': '',
'bold_img_name' : 'bold.nii.gz',
'run_path' : 'BOLD/'
}}
# TODO: uncomment for final version
#subject_list = [str(i) for i in range(1,17)]
#run_list = [str(i) for i in range(1,4)]
# Run only for subject 1 and 5 - run 1
run_list = [str(i) for i in range(1,2)]
subject_list = ['1', '5']
d_path = path_dict['data_original'] #OR original or filtered
images_paths = [('ds005' + '_sub' + s.zfill(3) + '_t1r' + r, \
data_path + 'sub%s/'%(s.zfill(3)) + d_path['run_path'] \
+ 'task001_run%s%s/%s' %(r.zfill(3),d_path['feat'],\
d_path['bold_img_name'])) \
for r in run_list \
for s in subject_list]
# set gray colormap and nearest neighbor interpolation by default
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['image.interpolation'] = 'nearest'
# Mask
# To be used with the normal data
thres = 375 #From analysis of the histograms
# To be used with the filtered data
mask_path = project_path+'data/mni_icbm152_t1_tal_nlin_asym_09c_mask_2mm.nii'
sm = ''
#sm='not_smooth/'
project_path = project_path + sm
# Create the needed directories if they do not exist
dirs = [project_path+'fig/',\
project_path+'fig/BOLD',\
project_path+'fig/drifts',\
project_path+'fig/pca',\
project_path+'fig/pca/projections/',\
project_path+'fig/linear_model/mosaic',\
project_path+'fig/linear_model/mosaic/middle_slice',\
project_path+'txt_output/',\
project_path+'txt_output/MRSS/',\
project_path+'txt_output/pca/',\
project_path+'txt_output/drifts/']
for d in dirs:
if not os.path.exists(d):
os.makedirs(d)
print("Starting noise-pca for the raw data analysis\n")
for image_path in images_paths:
name = image_path[0]
if d_path['type']=='filtered':
in_brain_img = nib.load('../../../'+
'data/ds005/sub001/model/model001/task001_run001.feat/'\
+ 'masked_filtered_func_data_mni.nii.gz')
# Image shape (91, 109, 91, 240)
#in_brain_img = make_mask_filtered_data(image_path[1],mask_path)
data_int = in_brain_img.get_data()
data = data_int.astype(float)
mean_data = np.mean(data, axis=-1)
in_brain_mask = (mean_data - 0.0) < 0.01
Transpose = False
else:
img = nib.load(image_path[1])
data_int = img.get_data()
data = data_int.astype(float)
mean_data = np.mean(data, axis=-1)
in_brain_mask = mean_data > thres
Transpose = True
# Smoothing with Gaussian filter
smooth_data = smoothing(data,1,range(data.shape[-1]))
# Selecting the voxels in the brain
in_brain_tcs = smooth_data[in_brain_mask, :]
#in_brain_tcs = data[in_brain_mask, :]
vol_shape = data.shape[:-1]
# Plotting the voxels in the brain
plt.imshow(plot_mosaic(mean_data, transpose=Transpose), cmap='gray', alpha=1)
plt.colorbar()
plt.contour(plot_mosaic(in_brain_mask, transpose=Transpose),colors='blue')
plt.title('In brain voxel mean values' + '\n' + (d_path['type'] + str(name)))
plt.savefig(project_path+'fig/BOLD/%s_mean_voxels_countour.png'\
%(d_path['type'] + str(name)))
#plt.show()
plt.clf()
# Convolution with 1 to 4 conditions
convolved = np.zeros((240,5))
for i in range(1,5):
#convolved = np.loadtxt(\
# '../../../txt_output/conv_normal/%s_conv_00%s_canonical.txt'\
# %(str(name),str(i)))
convolved[:,i] = np.loadtxt(\
'../../../txt_output/conv_high_res/%s_conv_00%s_high_res.txt'\
%(str(name),str(i)))
reg_str = ['Intercept','Task', 'Gain', 'Loss', 'Distance', 'Linear Drift',\
'Quadratic drift', 'PC#1', 'PC#2', 'PC#3', 'PC#4']
# Create design matrix X - Including drifts
P = 7 #number of regressors of X including the ones for intercept
n_trs = data.shape[-1]
X = np.ones((n_trs, P))
for i in range(1,5):
X[:,i] = convolved[:,i]
linear_drift = np.linspace(-1, 1, n_trs)
X[:,5] = linear_drift
quadratic_drift = linear_drift ** 2
quadratic_drift -= np.mean(quadratic_drift)
X[:,6] = quadratic_drift
# Save the design matrix
np.savetxt(project_path+\
'txt_output/drifts/%s_design_matrix_with_drift.txt'\
%(d_path['type'] + str(name)), X)
# Linear Model - Including drifts
Y = in_brain_tcs.T
betas = npl.pinv(X).dot(Y)
# Save the betas for the linear model including drifts
np.savetxt(project_path+\
'txt_output/drifts/%s_betas_with_drift.txt'%(d_path['type'] + str(name)), betas)
betas_vols = np.zeros(vol_shape + (P,))
betas_vols[in_brain_mask] = betas.T
# Plot
# Set regions outside mask as missing with np.nan
mean_data[~in_brain_mask] = np.nan
betas_vols[~in_brain_mask] = np.nan
nice_cmap_values = np.loadtxt('actc.txt')
nice_cmap = colors.ListedColormap(nice_cmap_values, 'actc')
# Plot each slice on the 3rd dimension of the image in a mosaic
for k in range(1,P):
plt.imshow(plot_mosaic(mean_data, transpose=Transpose), cmap='gray', alpha=1)
#plt.imshow(plot_mosaic(betas_vols[...,k], transpose=Transpose), cmap='gray', alpha=1)
plt.imshow(plot_mosaic(betas_vols[...,k], transpose=Transpose), cmap=nice_cmap, alpha=1)
plt.colorbar()
plt.title('Beta (with drift) values for brain voxel related to ' \
+ str(reg_str[k]) + '\n' + d_path['type'] + str(name))
plt.savefig(project_path+'fig/linear_model/mosaic/%s_withdrift_%s'\
%(d_path['type'] + str(name), str(reg_str[k]))+'.png')
plt.close()
#plt.show()
plt.clf()
#Show the middle slice only
plt.imshow(betas_vols[:, :, 18, k], cmap='gray', alpha=0.5)
plt.colorbar()
plt.title('In brain voxel - Slice 18 Projection on %s\n%s'\
%(str(reg_str[k]), d_path['type'] + str(name)))
plt.savefig(\
project_path+'fig/linear_model/mosaic/middle_slice/%s_withdrift_middleslice_%s'\
%(d_path['type'] + str(name), str(k))+'.png')
#plt.show()
plt.clf()
plt.close()
# PCA Analysis
Y_demeaned = Y - np.mean(Y, axis=1).reshape([-1, 1])
unscaled_cov = Y_demeaned.dot(Y_demeaned.T)
U, S, V = npl.svd(unscaled_cov)
projections = U.T.dot(Y_demeaned)
projection_vols = np.zeros(data.shape)
projection_vols[in_brain_mask, :] = projections.T
# Plot the projection of the data on the 5 first principal component
# from SVD
for i in range(1,5):
plt.plot(U[:, i])
plt.title('U' + str(i) + ' vector from SVD \n' + str(name))
plt.imshow(projection_vols[:, :, 18, i])
plt.colorbar()
plt.title('PCA - 18th slice projection on PC#' + str(i) + ' from SVD \n ' +\
d_path['type'] + str(name))
plt.savefig(project_path+'fig/pca/projections/%s_PC#%s.png' \
%((d_path['type'] + str(name),str(i))))
#plt.show()
plt.clf()
plt.close()
# Variance Explained analysis
s = []
#S is diag -> trace = sum of the elements of S
for i in S:
s.append(i/np.sum(S))
np.savetxt(project_path+\
'txt_output/pca/%s_variance_explained' % (d_path['type'] + str(name)) +\
'.txt', np.array(s[:40]))
ind = np.arange(len(s[1:40]))
plt.bar(ind, s[1:40], width=0.5)
plt.xlabel('Principal Components indices')
plt.ylabel('Explained variance in percent')
plt.title('Variance explained graph \n' + (d_path['type'] + str(name)))
plt.savefig(project_path+\
'fig/pca/%s_variance_explained.png' %(d_path['type'] + str(name)))
#plt.show()
plt.close()
# Linear Model - including PCs from PCA analysis
PC = 3 # Number of PCs to include in the design matrix
P_pca = P + PC
X_pca = np.ones((n_trs, P_pca))
for i in range(1,5):
X_pca[:,i] = convolved[:,i]
linear_drift = np.linspace(-1, 1, n_trs)
X_pca[:,5] = linear_drift
quadratic_drift = linear_drift ** 2
quadratic_drift -= np.mean(quadratic_drift)
X_pca[:,6] = quadratic_drift
for i in range(3):
X_pca[:,7+i] = U[:, i]
# Save the design matrix - with PCs
np.savetxt(project_path+'txt_output/pca/%s_design_matrix_pca.txt'\
%(d_path['type'] + str(name)), X_pca)
#plt.imshow(X_pca, aspect=0.25)
B_pca = npl.pinv(X_pca).dot(Y)
np.savetxt(project_path+'txt_output/pca/%s_betas_pca.txt'\
%(d_path['type'] + str(name)), B_pca)
b_pca_vols = np.zeros(vol_shape + (P_pca,))
b_pca_vols[in_brain_mask, :] = B_pca.T
# Save betas as nii files
# Plot - with PCs
# Set regions outside mask as missing with np.nan
mean_data[~in_brain_mask] = np.nan
b_pca_vols[~in_brain_mask] = np.nan
# Plot each slice on the 3rd dimension of the image in a mosaic
for k in range(1,P_pca):
fig = plt.figure(figsize = (8, 5))
#plt.imshow(plot_mosaic(b_pca_vols[...,k], transpose=Transpose), cmap='gray', alpha=0.5)
plt.imshow(plot_mosaic(mean_data, transpose=Transpose), cmap='gray', alpha=1)
plt.imshow(plot_mosaic(b_pca_vols[...,k], transpose=Transpose), cmap=nice_cmap, alpha=1)
plt.colorbar()
plt.title('Beta (with PCA) values for brain voxel related to ' \
+ str(reg_str[k]) + '\n' + d_path['type'] + str(name))
plt.savefig(project_path+'fig/linear_model/mosaic/%s_withPCA_%s'\
%(d_path['type'] + str(name), str(reg_str[k]))+'.png')
#plt.show()
plt.close()
#Show the middle slice only
plt.imshow(b_pca_vols[:, :, 18, k], cmap='gray', alpha=0.5)
plt.colorbar()
plt.title('In brain voxel model - Slice 18 \n' \
'Projection on X%s \n %s'\
%(str(reg_str[k]),d_path['type'] + str(name)))
plt.savefig(\
project_path+\
'fig/linear_model/mosaic/middle_slice/%s_withPCA_middle_slice_%s'\
%(d_path['type'] + str(name), str(k))+'.png')
#plt.show()
plt.clf()
plt.close()
# Residuals
MRSS_dict = {}
MRSS_dict['ds005' + d_path['type']] = {}
MRSS_dict['ds005' + d_path['type']]['drifts'] = {}
MRSS_dict['ds005' + d_path['type']]['pca'] = {}
for z in MRSS_dict['ds005' + d_path['type']]:
MRSS_dict['ds005' + d_path['type']][z]['MRSS'] = []
residuals = Y - X.dot(betas)
df = X.shape[0] - npl.matrix_rank(X)
MRSS = np.sum(residuals ** 2 , axis=0) / df
residuals_pca = Y - X_pca.dot(B_pca)
df_pca = X_pca.shape[0] - npl.matrix_rank(X_pca)
MRSS_pca = np.sum(residuals_pca ** 2 , axis=0) / df_pca
MRSS_dict['ds005' + d_path['type']]['drifts']['mean_MRSS'] = np.mean(MRSS)
MRSS_dict['ds005' + d_path['type']]['pca']['mean_MRSS'] = np.mean(MRSS_pca)
# Save the mean MRSS values to compare the performance
# of the design matrices
for design_matrix, beta, mrss, name in \
[(X, betas, MRSS, 'drifts'), (X_pca, B_pca, MRSS_pca, 'pca')]:
MRSS_dict['ds005' + d_path['type']][name]['p-values'] = []
MRSS_dict['ds005' + d_path['type']][name]['t-test'] = []
with open(project_path+'txt_output/MRSS/ds005%s_MRSS.json'\
%(d_path['type']), 'w') as file_out:
json.dump(MRSS_dict, file_out)
# SE = np.zeros(beta.shape)
# for i in range(design_matrix.shape[-1]):
# c = np.zeros(design_matrix.shape[-1])
# c[i]=1
# c = np.atleast_2d(c).T
# SE[i,:]= np.sqrt(\
# mrss* c.T.dot(npl.pinv(design_matrix.T.dot(design_matrix)).dot(c)))
# zeros = np.where(SE==0)
# SE[zeros] = 1
# t = beta / SE
# t[:,zeros] = 0
# # Get p value for t value using CDF of t didstribution
# ltp = t_dist.cdf(abs(t), df)
# p = 1 - ltp # upper tail
# t_brain = t[in_brain_mask]
# p_brain = p[in_brain_mask]
#
# # Save 3D data in .nii files
# for k in range(1,4):
# t_nib = nib.Nifti1Image(t_brain[..., k], affine)
# nib.save(t-test, project_path+'txt_output/%s/%s_t-test_%s.nii.gz'\
# %(name, d_path['type'] + str(name),str(reg_str[k])))
# p_nib = nib.Nifti1Image(p_brain[..., k], affine)
# nib.save(p-values,project_path+'txt_output/%s/%s_p-values_%s.nii.gz'\
# %(name, d_path['type'] + str(name),str(reg_str[k])))
# pdb.set_trace()
# pdb.set_trace()
print("======================================")
print("\n Noise and PCA analysis done")
print("Design Matrix including drift terms stored in project_epsilon/txt_output/drifts/ \n\n")
print("Design Matrix including PCs terms stored in project_epsilon/txt_output/pca/\n\n")
print("Mean MRSS models results in project_epsilon/txt_output/MRSS/ds005_MRSS.json\n\n")
| bsd-3-clause |
durai145/xbmc | lib/gtest/test/gtest_break_on_failure_unittest.py | 1050 | 7214 | #!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for Google Test's break-on-failure mode.
A user can ask Google Test to seg-fault when an assertion fails, using
either the GTEST_BREAK_ON_FAILURE environment variable or the
--gtest_break_on_failure flag. This script tests such functionality
by invoking gtest_break_on_failure_unittest_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
# Constants.
IS_WINDOWS = os.name == 'nt'
# The environment variable for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
# The command line flag for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
# The environment variable for enabling/disabling the throw-on-failure mode.
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
# The environment variable for enabling/disabling the catch-exceptions mode.
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
# Path to the gtest_break_on_failure_unittest_ program.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_break_on_failure_unittest_')
# Utilities.
environ = os.environ.copy()
def SetEnvVar(env_var, value):
"""Sets an environment variable to a given value; unsets it when the
given value is None.
"""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var]
def Run(command):
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
p = gtest_test_utils.Subprocess(command, env=environ)
if p.terminated_by_signal:
return 1
else:
return 0
# The tests.
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
the --gtest_break_on_failure flag to turn assertion failures into
segmentation faults.
"""
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
(or does not) have a seg-fault.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
variable; None if the variable should be unset.
flag_value: value of the --gtest_break_on_failure flag;
None if the flag should not be present.
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
0 otherwise.
"""
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
if env_var_value is None:
env_var_value_msg = ' is not set'
else:
env_var_value_msg = '=' + env_var_value
if flag_value is None:
flag = ''
elif flag_value == '0':
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
else:
flag = '--%s' % BREAK_ON_FAILURE_FLAG
command = [EXE_PATH]
if flag:
command.append(flag)
if expect_seg_fault:
should_or_not = 'should'
else:
should_or_not = 'should not'
has_seg_fault = Run(command)
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
should_or_not))
self.assert_(has_seg_fault == expect_seg_fault, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(env_var_value=None,
flag_value=None,
expect_seg_fault=0)
def testEnvVar(self):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value=None,
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value=None,
expect_seg_fault=1)
def testFlag(self):
"""Tests using the --gtest_break_on_failure flag."""
self.RunAndVerify(env_var_value=None,
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value=None,
flag_value='1',
expect_seg_fault=1)
def testFlagOverridesEnvVar(self):
"""Tests that the flag overrides the environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='0',
flag_value='1',
expect_seg_fault=1)
self.RunAndVerify(env_var_value='1',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value='1',
expect_seg_fault=1)
def testBreakOnFailureOverridesThrowOnFailure(self):
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
try:
self.RunAndVerify(env_var_value=None,
flag_value='1',
expect_seg_fault=1)
finally:
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
if IS_WINDOWS:
def testCatchExceptionsDoesNotInterfere(self):
"""Tests that gtest_catch_exceptions doesn't interfere."""
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
try:
self.RunAndVerify(env_var_value='1',
flag_value='1',
expect_seg_fault=1)
finally:
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
if __name__ == '__main__':
gtest_test_utils.Main()
| gpl-2.0 |
Zouyiran/ryu | ryu/tests/unit/ofproto/test_ofproto.py | 36 | 3093 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp>
#
# 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.
# vim: tabstop=4 shiftwidth=4 softtabstop=4
try:
# Python 3
from imp import reload
except ImportError:
# Python 2
pass
import unittest
import logging
from nose.tools import eq_
LOG = logging.getLogger('test_ofproto')
class TestOfprotCommon(unittest.TestCase):
""" Test case for ofproto
"""
def test_ofp_event(self):
import ryu.ofproto
reload(ryu.ofproto)
import ryu.controller.ofp_event
reload(ryu.controller.ofp_event)
def test_ofproto(self):
# When new version of OFP support is added,
# this test must be updated.
import ryu.ofproto
reload(ryu.ofproto)
ofp_modules = ryu.ofproto.get_ofp_modules()
import ryu.ofproto.ofproto_v1_0
import ryu.ofproto.ofproto_v1_2
import ryu.ofproto.ofproto_v1_3
import ryu.ofproto.ofproto_v1_4
import ryu.ofproto.ofproto_v1_5
eq_(set(ofp_modules.keys()), set([ryu.ofproto.ofproto_v1_0.OFP_VERSION,
ryu.ofproto.ofproto_v1_2.OFP_VERSION,
ryu.ofproto.ofproto_v1_3.OFP_VERSION,
ryu.ofproto.ofproto_v1_4.OFP_VERSION,
ryu.ofproto.ofproto_v1_5.OFP_VERSION,
]))
consts_mods = set([ofp_mod[0] for ofp_mod in ofp_modules.values()])
eq_(consts_mods, set([ryu.ofproto.ofproto_v1_0,
ryu.ofproto.ofproto_v1_2,
ryu.ofproto.ofproto_v1_3,
ryu.ofproto.ofproto_v1_4,
ryu.ofproto.ofproto_v1_5,
]))
parser_mods = set([ofp_mod[1] for ofp_mod in ofp_modules.values()])
import ryu.ofproto.ofproto_v1_0_parser
import ryu.ofproto.ofproto_v1_2_parser
import ryu.ofproto.ofproto_v1_3_parser
import ryu.ofproto.ofproto_v1_4_parser
import ryu.ofproto.ofproto_v1_5_parser
eq_(parser_mods, set([ryu.ofproto.ofproto_v1_0_parser,
ryu.ofproto.ofproto_v1_2_parser,
ryu.ofproto.ofproto_v1_3_parser,
ryu.ofproto.ofproto_v1_4_parser,
ryu.ofproto.ofproto_v1_5_parser,
]))
| apache-2.0 |
msimacek/freeipa | ipalib/plugins/selinuxusermap.py | 4 | 19598 | # Authors:
# Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2011 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.
from ipalib import api, errors
from ipalib import Str, StrEnum, Bool
from ipalib.plugable import Registry
from ipalib.plugins.baseldap import *
from ipalib import _, ngettext
from ipalib.plugins.hbacrule import is_all
__doc__ = _("""
SELinux User Mapping
Map IPA users to SELinux users by host.
Hosts, hostgroups, users and groups can be either defined within
the rule or it may point to an existing HBAC rule. When using
--hbacrule option to selinuxusermap-find an exact match is made on the
HBAC rule name, so only one or zero entries will be returned.
EXAMPLES:
Create a rule, "test1", that sets all users to xguest_u:s0 on the host "server":
ipa selinuxusermap-add --usercat=all --selinuxuser=xguest_u:s0 test1
ipa selinuxusermap-add-host --hosts=server.example.com test1
Create a rule, "test2", that sets all users to guest_u:s0 and uses an existing HBAC rule for users and hosts:
ipa selinuxusermap-add --usercat=all --hbacrule=webserver --selinuxuser=guest_u:s0 test2
Display the properties of a rule:
ipa selinuxusermap-show test2
Create a rule for a specific user. This sets the SELinux context for
user john to unconfined_u:s0-s0:c0.c1023 on any machine:
ipa selinuxusermap-add --hostcat=all --selinuxuser=unconfined_u:s0-s0:c0.c1023 john_unconfined
ipa selinuxusermap-add-user --users=john john_unconfined
Disable a rule:
ipa selinuxusermap-disable test1
Enable a rule:
ipa selinuxusermap-enable test1
Find a rule referencing a specific HBAC rule:
ipa selinuxusermap-find --hbacrule=allow_some
Remove a rule:
ipa selinuxusermap-del john_unconfined
SEEALSO:
The list controlling the order in which the SELinux user map is applied
and the default SELinux user are available in the config-show command.
""")
register = Registry()
notboth_err = _('HBAC rule and local members cannot both be set')
def validate_selinuxuser(ugettext, user):
"""
An SELinux user has 3 components: user:MLS:MCS. user and MLS are required.
user traditionally ends with _u but this is not mandatory.
The regex is ^[a-zA-Z][a-zA-Z_]*
The MLS part can only be:
Level: s[0-15](-s[0-15])
Then MCS could be c[0-1023].c[0-1023] and/or c[0-1023]-c[0-c0123]
Meaning
s0 s0-s1 s0-s15:c0.c1023 s0-s1:c0,c2,c15.c26 s0-s0:c0.c1023
Returns a message on invalid, returns nothing on valid.
"""
regex_name = re.compile(r'^[a-zA-Z][a-zA-Z_]*$')
regex_mls = re.compile(r'^s[0-9][1-5]{0,1}(-s[0-9][1-5]{0,1}){0,1}$')
regex_mcs = re.compile(r'^c(\d+)([.,-]c(\d+))*?$')
# If we add in ::: we don't have to check to see if some values are
# empty
(name, mls, mcs, ignore) = (user + ':::').split(':', 3)
if not regex_name.match(name):
return _('Invalid SELinux user name, only a-Z and _ are allowed')
if not mls or not regex_mls.match(mls):
return _('Invalid MLS value, must match s[0-15](-s[0-15])')
m = regex_mcs.match(mcs)
if mcs and (not m or (m.group(3) and (int(m.group(3)) > 1023))):
return _('Invalid MCS value, must match c[0-1023].c[0-1023] '
'and/or c[0-1023]-c[0-c0123]')
return None
def validate_selinuxuser_inlist(ldap, user):
"""
Ensure the user is in the list of allowed SELinux users.
Returns nothing if the user is found, raises an exception otherwise.
"""
config = ldap.get_ipa_config()
item = config.get('ipaselinuxusermaporder', [])
if len(item) != 1:
raise errors.NotFound(reason=_('SELinux user map list not '
'found in configuration'))
userlist = item[0].split('$')
if user not in userlist:
raise errors.NotFound(
reason=_('SELinux user %(user)s not found in '
'ordering list (in config)') % dict(user=user))
return
@register()
class selinuxusermap(LDAPObject):
"""
SELinux User Map object.
"""
container_dn = api.env.container_selinux
object_name = _('SELinux User Map rule')
object_name_plural = _('SELinux User Map rules')
object_class = ['ipaassociation', 'ipaselinuxusermap']
permission_filter_objectclasses = ['ipaselinuxusermap']
default_attributes = [
'cn', 'ipaenabledflag',
'description', 'usercategory', 'hostcategory',
'ipaenabledflag', 'memberuser', 'memberhost',
'seealso', 'ipaselinuxuser',
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
attribute_members = {
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
}
managed_permissions = {
'System: Read SELinux User Maps': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'accesstime', 'cn', 'description', 'hostcategory',
'ipaenabledflag', 'ipaselinuxuser', 'ipauniqueid',
'memberhost', 'memberuser', 'seealso', 'usercategory',
'objectclass', 'member',
},
},
'System: Add SELinux User Maps': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Add SELinux User Maps";allow (add) groupdn = "ldap:///cn=Add SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
'System: Modify SELinux User Maps': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cn', 'ipaenabledflag', 'ipaselinuxuser', 'memberhost',
'memberuser', 'seealso'
},
'replaces': [
'(targetattr = "cn || memberuser || memberhost || seealso || ipaselinuxuser || ipaenabledflag")(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Modify SELinux User Maps";allow (write) groupdn = "ldap:///cn=Modify SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
'System: Remove SELinux User Maps': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Remove SELinux User Maps";allow (delete) groupdn = "ldap:///cn=Remove SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
}
# These maps will not show as members of other entries
label = _('SELinux User Maps')
label_singular = _('SELinux User Map')
takes_params = (
Str('cn',
cli_name='name',
label=_('Rule name'),
primary_key=True,
),
Str('ipaselinuxuser', validate_selinuxuser,
cli_name='selinuxuser',
label=_('SELinux User'),
),
Str('seealso?',
cli_name='hbacrule',
label=_('HBAC Rule'),
doc=_('HBAC Rule that defines the users, groups and hostgroups'),
),
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the rule applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the rule applies to'),
values=(u'all', ),
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Bool('ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
),
Str('memberuser_user?',
label=_('Users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_group?',
label=_('User Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_host?',
label=_('Hosts'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_hostgroup?',
label=_('Host Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
)
def _normalize_seealso(self, seealso):
"""
Given a HBAC rule name verify its existence and return the dn.
"""
if not seealso:
return None
try:
dn = DN(seealso)
return str(dn)
except ValueError:
try:
entry_attrs = self.backend.find_entry_by_attr(
self.api.Object['hbacrule'].primary_key.name,
seealso,
self.api.Object['hbacrule'].object_class,
[''],
DN(self.api.Object['hbacrule'].container_dn, api.env.basedn))
seealso = entry_attrs.dn
except errors.NotFound:
raise errors.NotFound(reason=_('HBAC rule %(rule)s not found') % dict(rule=seealso))
return seealso
def _convert_seealso(self, ldap, entry_attrs, **options):
"""
Convert an HBAC rule dn into a name
"""
if options.get('raw', False):
return
if 'seealso' in entry_attrs:
hbac_attrs = ldap.get_entry(entry_attrs['seealso'][0], ['cn'])
entry_attrs['seealso'] = hbac_attrs['cn'][0]
@register()
class selinuxusermap_add(LDAPCreate):
__doc__ = _('Create a new SELinux User Map.')
msg_summary = _('Added SELinux User Map "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# rules are enabled by default
entry_attrs['ipaenabledflag'] = 'TRUE'
validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])
# hbacrule is not allowed when usercat or hostcat is set
is_to_be_set = lambda x: x in entry_attrs and entry_attrs[x] != None
are_local_members_to_be_set = any(is_to_be_set(attr)
for attr in ('usercategory',
'hostcategory'))
is_hbacrule_to_be_set = is_to_be_set('seealso')
if is_hbacrule_to_be_set and are_local_members_to_be_set:
raise errors.MutuallyExclusiveError(reason=notboth_err)
if is_hbacrule_to_be_set:
entry_attrs['seealso'] = self.obj._normalize_seealso(entry_attrs['seealso'])
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_del(LDAPDelete):
__doc__ = _('Delete a SELinux User Map.')
msg_summary = _('Deleted SELinux User Map "%(value)s"')
@register()
class selinuxusermap_mod(LDAPUpdate):
__doc__ = _('Modify a SELinux User Map.')
msg_summary = _('Modified SELinux User Map "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, attrs_list)
except errors.NotFound:
self.obj.handle_not_found(*keys)
is_to_be_deleted = lambda x: (x in _entry_attrs and x in entry_attrs) and \
entry_attrs[x] == None
# makes sure the local members and hbacrule is not set at the same time
# memberuser or memberhost could have been set using --setattr
is_to_be_set = lambda x: ((x in _entry_attrs and _entry_attrs[x] != None) or \
(x in entry_attrs and entry_attrs[x] != None)) and \
not is_to_be_deleted(x)
are_local_members_to_be_set = any(is_to_be_set(attr)
for attr in ('usercategory',
'hostcategory',
'memberuser',
'memberhost'))
is_hbacrule_to_be_set = is_to_be_set('seealso')
# this can disable all modifications if hbacrule and local members were
# set at the same time bypassing this commad, e.g. using ldapmodify
if are_local_members_to_be_set and is_hbacrule_to_be_set:
raise errors.MutuallyExclusiveError(reason=notboth_err)
if is_all(entry_attrs, 'usercategory') and 'memberuser' in entry_attrs:
raise errors.MutuallyExclusiveError(reason="user category "
"cannot be set to 'all' while there are allowed users")
if is_all(entry_attrs, 'hostcategory') and 'memberhost' in entry_attrs:
raise errors.MutuallyExclusiveError(reason="host category "
"cannot be set to 'all' while there are allowed hosts")
if 'ipaselinuxuser' in entry_attrs:
validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])
if 'seealso' in entry_attrs:
entry_attrs['seealso'] = self.obj._normalize_seealso(entry_attrs['seealso'])
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_find(LDAPSearch):
__doc__ = _('Search for SELinux User Maps.')
msg_summary = ngettext(
'%(count)d SELinux User Map matched', '%(count)d SELinux User Maps matched', 0
)
def execute(self, *args, **options):
# If searching on hbacrule we need to find the uuid to search on
if options.get('seealso'):
hbacrule = options['seealso']
try:
hbac = api.Command['hbacrule_show'](hbacrule,
all=True)['result']
dn = hbac['dn']
except errors.NotFound:
return dict(count=0, result=[], truncated=False)
options['seealso'] = dn
return super(selinuxusermap_find, self).execute(*args, **options)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
for attrs in entries:
self.obj._convert_seealso(ldap, attrs, **options)
return truncated
@register()
class selinuxusermap_show(LDAPRetrieve):
__doc__ = _('Display the properties of a SELinux User Map rule.')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_enable(LDAPQuery):
__doc__ = _('Enable an SELinux User Map rule.')
msg_summary = _('Enabled SELinux User Map "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = ['TRUE']
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
raise errors.AlreadyActive()
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class selinuxusermap_disable(LDAPQuery):
__doc__ = _('Disable an SELinux User Map rule.')
msg_summary = _('Disabled SELinux User Map "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = ['FALSE']
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
raise errors.AlreadyInactive()
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class selinuxusermap_add_user(LDAPAddMember):
__doc__ = _('Add users and groups to an SELinux User Map rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
self.obj.handle_not_found(*keys)
if 'usercategory' in entry_attrs and \
entry_attrs['usercategory'][0].lower() == 'all':
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when user category='all'"))
if 'seealso' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=notboth_err)
return dn
@register()
class selinuxusermap_remove_user(LDAPRemoveMember):
__doc__ = _('Remove users and groups from an SELinux User Map rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class selinuxusermap_add_host(LDAPAddMember):
__doc__ = _('Add target hosts and hostgroups to an SELinux User Map rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
self.obj.handle_not_found(*keys)
if 'hostcategory' in entry_attrs and \
entry_attrs['hostcategory'][0].lower() == 'all':
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be added when host category='all'"))
if 'seealso' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=notboth_err)
return dn
@register()
class selinuxusermap_remove_host(LDAPRemoveMember):
__doc__ = _('Remove target hosts and hostgroups from an SELinux User Map rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object removed.', '%i objects removed.')
| gpl-3.0 |
dfunckt/django | tests/gis_tests/geoapp/test_sitemaps.py | 123 | 2631 | from __future__ import unicode_literals
import zipfile
from io import BytesIO
from xml.dom import minidom
from django.conf import settings
from django.contrib.sites.models import Site
from django.test import (
TestCase, modify_settings, override_settings, skipUnlessDBFeature,
)
from .models import City, Country
@modify_settings(INSTALLED_APPS={'append': ['django.contrib.sites', 'django.contrib.sitemaps']})
@override_settings(ROOT_URLCONF='gis_tests.geoapp.urls')
@skipUnlessDBFeature("gis_enabled")
class GeoSitemapTest(TestCase):
def setUp(self):
super(GeoSitemapTest, self).setUp()
Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
def assertChildNodes(self, elem, expected):
"Taken from syndication/tests.py."
actual = set(n.nodeName for n in elem.childNodes)
expected = set(expected)
self.assertEqual(actual, expected)
def test_geositemap_kml(self):
"Tests KML/KMZ geographic sitemaps."
for kml_type in ('kml', 'kmz'):
doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
# Ensuring the right sitemaps namespace is present.
urlset = doc.firstChild
self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9')
urls = urlset.getElementsByTagName('url')
self.assertEqual(2, len(urls)) # Should only be 2 sitemaps.
for url in urls:
self.assertChildNodes(url, ['loc'])
# Getting the relative URL since we don't have a real site.
kml_url = url.getElementsByTagName('loc')[0].childNodes[0].data.split('http://example.com')[1]
if kml_type == 'kml':
kml_doc = minidom.parseString(self.client.get(kml_url).content)
elif kml_type == 'kmz':
# Have to decompress KMZ before parsing.
buf = BytesIO(self.client.get(kml_url).content)
with zipfile.ZipFile(buf) as zf:
self.assertEqual(1, len(zf.filelist))
self.assertEqual('doc.kml', zf.filelist[0].filename)
kml_doc = minidom.parseString(zf.read('doc.kml'))
# Ensuring the correct number of placemarks are in the KML doc.
if 'city' in kml_url:
model = City
elif 'country' in kml_url:
model = Country
self.assertEqual(model.objects.count(), len(kml_doc.getElementsByTagName('Placemark')))
| bsd-3-clause |
af1rst/bite-project | deps/closure/closure-library/closure/bin/build/depswriter.py | 247 | 6208 | #!/usr/bin/env python
#
# Copyright 2009 The Closure Library 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.
"""Generates out a Closure deps.js file given a list of JavaScript sources.
Paths can be specified as arguments or (more commonly) specifying trees
with the flags (call with --help for descriptions).
Usage: depswriter.py [path/to/js1.js [path/to/js2.js] ...]
"""
import logging
import optparse
import os
import posixpath
import shlex
import sys
import source
import treescan
__author__ = 'nnaze@google.com (Nathan Naze)'
def MakeDepsFile(source_map):
"""Make a generated deps file.
Args:
source_map: A dict map of the source path to source.Source object.
Returns:
str, A generated deps file source.
"""
# Write in path alphabetical order
paths = sorted(source_map.keys())
lines = []
for path in paths:
js_source = source_map[path]
# We don't need to add entries that don't provide anything.
if js_source.provides:
lines.append(_GetDepsLine(path, js_source))
return ''.join(lines)
def _GetDepsLine(path, js_source):
"""Get a deps.js file string for a source."""
provides = sorted(js_source.provides)
requires = sorted(js_source.requires)
return 'goog.addDependency(\'%s\', %s, %s);\n' % (path, provides, requires)
def _GetOptionsParser():
"""Get the options parser."""
parser = optparse.OptionParser(__doc__)
parser.add_option('--output_file',
dest='output_file',
action='store',
help=('If specified, write output to this path instead of '
'writing to standard output.'))
parser.add_option('--root',
dest='roots',
default=[],
action='append',
help='A root directory to scan for JS source files. '
'Paths of JS files in generated deps file will be '
'relative to this path. This flag may be specified '
'multiple times.')
parser.add_option('--root_with_prefix',
dest='roots_with_prefix',
default=[],
action='append',
help='A root directory to scan for JS source files, plus '
'a prefix (if either contains a space, surround with '
'quotes). Paths in generated deps file will be relative '
'to the root, but preceded by the prefix. This flag '
'may be specified multiple times.')
parser.add_option('--path_with_depspath',
dest='paths_with_depspath',
default=[],
action='append',
help='A path to a source file and an alternate path to '
'the file in the generated deps file (if either contains '
'a space, surround with whitespace). This flag may be '
'specified multiple times.')
return parser
def _NormalizePathSeparators(path):
"""Replaces OS-specific path separators with POSIX-style slashes.
Args:
path: str, A file path.
Returns:
str, The path with any OS-specific path separators (such as backslash on
Windows) replaced with URL-compatible forward slashes. A no-op on systems
that use POSIX paths.
"""
return path.replace(os.sep, posixpath.sep)
def _GetRelativePathToSourceDict(root, prefix=''):
"""Scans a top root directory for .js sources.
Args:
root: str, Root directory.
prefix: str, Prefix for returned paths.
Returns:
dict, A map of relative paths (with prefix, if given), to source.Source
objects.
"""
# Remember and restore the cwd when we're done. We work from the root so
# that paths are relative from the root.
start_wd = os.getcwd()
os.chdir(root)
path_to_source = {}
for path in treescan.ScanTreeForJsFiles('.'):
prefixed_path = _NormalizePathSeparators(os.path.join(prefix, path))
path_to_source[prefixed_path] = source.Source(source.GetFileContents(path))
os.chdir(start_wd)
return path_to_source
def _GetPair(s):
"""Return a string as a shell-parsed tuple. Two values expected."""
try:
# shlex uses '\' as an escape character, so they must be escaped.
s = s.replace('\\', '\\\\')
first, second = shlex.split(s)
return (first, second)
except:
raise Exception('Unable to parse input line as a pair: %s' % s)
def main():
"""CLI frontend to MakeDepsFile."""
logging.basicConfig(format=(sys.argv[0] + ': %(message)s'),
level=logging.INFO)
options, args = _GetOptionsParser().parse_args()
path_to_source = {}
# Roots without prefixes
for root in options.roots:
path_to_source.update(_GetRelativePathToSourceDict(root))
# Roots with prefixes
for root_and_prefix in options.roots_with_prefix:
root, prefix = _GetPair(root_and_prefix)
path_to_source.update(_GetRelativePathToSourceDict(root, prefix=prefix))
# Source paths
for path in args:
path_to_source[path] = source.Source(source.GetFileContents(path))
# Source paths with alternate deps paths
for path_with_depspath in options.paths_with_depspath:
srcpath, depspath = _GetPair(path_with_depspath)
path_to_source[depspath] = source.Source(source.GetFileContents(srcpath))
# Make our output pipe.
if options.output_file:
out = open(options.output_file, 'w')
else:
out = sys.stdout
out.write('// This file was autogenerated by %s.\n' % sys.argv[0])
out.write('// Please do not edit.\n')
out.write(MakeDepsFile(path_to_source))
if __name__ == '__main__':
main()
| apache-2.0 |
nadeemat/namebench | nb_third_party/dns/edns.py | 248 | 4312 | # Copyright (C) 2009 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""EDNS Options"""
NSID = 3
class Option(object):
"""Base class for all EDNS option types.
"""
def __init__(self, otype):
"""Initialize an option.
@param rdtype: The rdata type
@type rdtype: int
"""
self.otype = otype
def to_wire(self, file):
"""Convert an option to wire format.
"""
raise NotImplementedError
def from_wire(cls, otype, wire, current, olen):
"""Build an EDNS option object from wire format
@param otype: The option type
@type otype: int
@param wire: The wire-format message
@type wire: string
@param current: The offet in wire of the beginning of the rdata.
@type current: int
@param olen: The length of the wire-format option data
@type olen: int
@rtype: dns.ends.Option instance"""
raise NotImplementedError
from_wire = classmethod(from_wire)
def _cmp(self, other):
"""Compare an ENDS option with another option of the same type.
Return < 0 if self < other, 0 if self == other, and > 0 if self > other.
"""
raise NotImplementedError
def __eq__(self, other):
if not isinstance(other, Option):
return False
if self.otype != other.otype:
return False
return self._cmp(other) == 0
def __ne__(self, other):
if not isinstance(other, Option):
return False
if self.otype != other.otype:
return False
return self._cmp(other) != 0
def __lt__(self, other):
if not isinstance(other, Option) or \
self.otype != other.otype:
return NotImplemented
return self._cmp(other) < 0
def __le__(self, other):
if not isinstance(other, Option) or \
self.otype != other.otype:
return NotImplemented
return self._cmp(other) <= 0
def __ge__(self, other):
if not isinstance(other, Option) or \
self.otype != other.otype:
return NotImplemented
return self._cmp(other) >= 0
def __gt__(self, other):
if not isinstance(other, Option) or \
self.otype != other.otype:
return NotImplemented
return self._cmp(other) > 0
class GenericOption(Option):
"""Generate Rdata Class
This class is used for EDNS option types for which we have no better
implementation.
"""
def __init__(self, otype, data):
super(GenericOption, self).__init__(otype)
self.data = data
def to_wire(self, file):
file.write(self.data)
def from_wire(cls, otype, wire, current, olen):
return cls(otype, wire[current : current + olen])
from_wire = classmethod(from_wire)
def _cmp(self, other):
return cmp(self.data, other.data)
_type_to_class = {
}
def get_option_class(otype):
cls = _type_to_class.get(otype)
if cls is None:
cls = GenericOption
return cls
def option_from_wire(otype, wire, current, olen):
"""Build an EDNS option object from wire format
@param otype: The option type
@type otype: int
@param wire: The wire-format message
@type wire: string
@param current: The offet in wire of the beginning of the rdata.
@type current: int
@param olen: The length of the wire-format option data
@type olen: int
@rtype: dns.ends.Option instance"""
cls = get_option_class(otype)
return cls.from_wire(otype, wire, current, olen)
| apache-2.0 |
pizzapanther/Super-Neutron-Drive | build_zip.py | 1 | 1591 | #!/usr/bin/env python
import os
import json
import types
import subprocess
exclude_files = ()
exclude_dirs = ()
if __name__ == "__main__":
os.chdir('chrome-app')
print("Generating extension in super-neutron.zip\n")
ziplist = ''
for root, dirs, files in os.walk('./'):
for file in files:
skip = False
path = os.path.join(root, file)
if file in exclude_files:
skip = True
for d in exclude_dirs:
if '/' + d + '/' in path:
skip = True
if skip:
continue
if file == 'manifest.json':
fh = open(path, 'r')
manifest = json.loads(fh.read())
fh.close()
remove_perm = []
for i in range(0, len(manifest['permissions'])):
perm = manifest['permissions'][i]
if type(perm) in types.StringTypes:
if 'http://' in perm:
remove_perm.append(perm)
for perm in remove_perm:
manifest['permissions'].remove(perm)
del manifest['server_url']
fh = open('/tmp/manifest.json', 'w')
fh.write(json.dumps(manifest, indent=2))
fh.close()
else:
ziplist += ' ' + path
subprocess.call("rm ../super-neutron.zip", shell=True)
subprocess.call("zip -r ../super-neutron.zip" + ziplist, shell=True)
subprocess.call("zip -r ../super-neutron.zip -j /tmp/manifest.json", shell=True)
subprocess.call("rm /tmp/manifest.json", shell=True)
print("\nSo long and thanks for all the fish!")
| mit |
ppwwyyxx/tensorflow | tensorflow/python/data/experimental/kernel_tests/serialization/prefetch_dataset_serialization_test.py | 15 | 1726 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the PrefetchDataset serialization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from tensorflow.python.data.experimental.kernel_tests.serialization import dataset_serialization_test_base
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import combinations
from tensorflow.python.platform import test
class PrefetchDatasetSerializationTest(
dataset_serialization_test_base.DatasetSerializationTestBase,
parameterized.TestCase):
def build_dataset(self, seed):
return dataset_ops.Dataset.range(100).prefetch(10).shuffle(
buffer_size=10, seed=seed, reshuffle_each_iteration=False)
@combinations.generate(test_base.default_test_combinations())
def testCore(self):
num_outputs = 100
self.run_core_tests(lambda: self.build_dataset(10), num_outputs)
if __name__ == "__main__":
test.main()
| apache-2.0 |
playfulgod/kernel-M865 | scripts/rt-tester/rt-tester.py | 1094 | 5362 | #!/usr/bin/python
#
# rt-mutex tester
#
# (C) 2006 Thomas Gleixner <tglx@linutronix.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
import os
import sys
import getopt
import shutil
import string
# Globals
quiet = 0
test = 0
comments = 0
sysfsprefix = "/sys/devices/system/rttest/rttest"
statusfile = "/status"
commandfile = "/command"
# Command opcodes
cmd_opcodes = {
"schedother" : "1",
"schedfifo" : "2",
"lock" : "3",
"locknowait" : "4",
"lockint" : "5",
"lockintnowait" : "6",
"lockcont" : "7",
"unlock" : "8",
"lockbkl" : "9",
"unlockbkl" : "10",
"signal" : "11",
"resetevent" : "98",
"reset" : "99",
}
test_opcodes = {
"prioeq" : ["P" , "eq" , None],
"priolt" : ["P" , "lt" , None],
"priogt" : ["P" , "gt" , None],
"nprioeq" : ["N" , "eq" , None],
"npriolt" : ["N" , "lt" , None],
"npriogt" : ["N" , "gt" , None],
"unlocked" : ["M" , "eq" , 0],
"trylock" : ["M" , "eq" , 1],
"blocked" : ["M" , "eq" , 2],
"blockedwake" : ["M" , "eq" , 3],
"locked" : ["M" , "eq" , 4],
"opcodeeq" : ["O" , "eq" , None],
"opcodelt" : ["O" , "lt" , None],
"opcodegt" : ["O" , "gt" , None],
"eventeq" : ["E" , "eq" , None],
"eventlt" : ["E" , "lt" , None],
"eventgt" : ["E" , "gt" , None],
}
# Print usage information
def usage():
print "rt-tester.py <-c -h -q -t> <testfile>"
print " -c display comments after first command"
print " -h help"
print " -q quiet mode"
print " -t test mode (syntax check)"
print " testfile: read test specification from testfile"
print " otherwise from stdin"
return
# Print progress when not in quiet mode
def progress(str):
if not quiet:
print str
# Analyse a status value
def analyse(val, top, arg):
intval = int(val)
if top[0] == "M":
intval = intval / (10 ** int(arg))
intval = intval % 10
argval = top[2]
elif top[0] == "O":
argval = int(cmd_opcodes.get(arg, arg))
else:
argval = int(arg)
# progress("%d %s %d" %(intval, top[1], argval))
if top[1] == "eq" and intval == argval:
return 1
if top[1] == "lt" and intval < argval:
return 1
if top[1] == "gt" and intval > argval:
return 1
return 0
# Parse the commandline
try:
(options, arguments) = getopt.getopt(sys.argv[1:],'chqt')
except getopt.GetoptError, ex:
usage()
sys.exit(1)
# Parse commandline options
for option, value in options:
if option == "-c":
comments = 1
elif option == "-q":
quiet = 1
elif option == "-t":
test = 1
elif option == '-h':
usage()
sys.exit(0)
# Select the input source
if arguments:
try:
fd = open(arguments[0])
except Exception,ex:
sys.stderr.write("File not found %s\n" %(arguments[0]))
sys.exit(1)
else:
fd = sys.stdin
linenr = 0
# Read the test patterns
while 1:
linenr = linenr + 1
line = fd.readline()
if not len(line):
break
line = line.strip()
parts = line.split(":")
if not parts or len(parts) < 1:
continue
if len(parts[0]) == 0:
continue
if parts[0].startswith("#"):
if comments > 1:
progress(line)
continue
if comments == 1:
comments = 2
progress(line)
cmd = parts[0].strip().lower()
opc = parts[1].strip().lower()
tid = parts[2].strip()
dat = parts[3].strip()
try:
# Test or wait for a status value
if cmd == "t" or cmd == "w":
testop = test_opcodes[opc]
fname = "%s%s%s" %(sysfsprefix, tid, statusfile)
if test:
print fname
continue
while 1:
query = 1
fsta = open(fname, 'r')
status = fsta.readline().strip()
fsta.close()
stat = status.split(",")
for s in stat:
s = s.strip()
if s.startswith(testop[0]):
# Seperate status value
val = s[2:].strip()
query = analyse(val, testop, dat)
break
if query or cmd == "t":
break
progress(" " + status)
if not query:
sys.stderr.write("Test failed in line %d\n" %(linenr))
sys.exit(1)
# Issue a command to the tester
elif cmd == "c":
cmdnr = cmd_opcodes[opc]
# Build command string and sys filename
cmdstr = "%s:%s" %(cmdnr, dat)
fname = "%s%s%s" %(sysfsprefix, tid, commandfile)
if test:
print fname
continue
fcmd = open(fname, 'w')
fcmd.write(cmdstr)
fcmd.close()
except Exception,ex:
sys.stderr.write(str(ex))
sys.stderr.write("\nSyntax error in line %d\n" %(linenr))
if not test:
fd.close()
sys.exit(1)
# Normal exit pass
print "Pass"
sys.exit(0)
| gpl-2.0 |
lixiangning888/whole_project | modules/signatures_merge_tmp/ek_silverlight.py | 2 | 1071 | # -*- coding: utf-8 -*-
try:
import re2 as re
except ImportError:
import re
from lib.cuckoo.common.abstracts import Signature
class Silverlight_JS(Signature):
name = "silverlight_js"
description = "执行伪装过的包含一个Silverlight对象的JavaScript,可能被用于漏洞攻击尝试"
weight = 3
severity = 3
categories = ["exploit_kit", "silverlight"]
authors = ["Kevin Ross"]
minimum = "1.3"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_categories = set(["browser"])
# backward compat
filter_apinames = set(["JsEval", "COleScript_Compile", "COleScript_ParseScriptText"])
def on_call(self, call, process):
if call["api"] == "JsEval":
buf = self.get_argument(call, "Javascript")
else:
buf = self.get_argument(call, "Script")
if re.search("application\/x\-silverlight.*?\<param name[ \t\n]*=.*?value[ \t\n]*=.*?\<\/object\>.*", buf, re.IGNORECASE|re.DOTALL):
return True
| lgpl-3.0 |
tmerrick1/spack | lib/spack/spack/test/packages.py | 2 | 6675 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os.path
import pytest
import spack.repo
from spack.paths import mock_packages_path
from spack.util.naming import mod_to_class
from spack.spec import Spec
from spack.util.package_hash import package_content
@pytest.mark.usefixtures('config', 'mock_packages')
class TestPackage(object):
def test_load_package(self):
spack.repo.get('mpich')
def test_package_name(self):
pkg = spack.repo.get('mpich')
assert pkg.name == 'mpich'
def test_package_filename(self):
repo = spack.repo.Repo(mock_packages_path)
filename = repo.filename_for_package_name('mpich')
assert filename == os.path.join(
mock_packages_path,
'packages',
'mpich',
'package.py'
)
def test_nonexisting_package_filename(self):
repo = spack.repo.Repo(mock_packages_path)
filename = repo.filename_for_package_name('some-nonexisting-package')
assert filename == os.path.join(
mock_packages_path,
'packages',
'some-nonexisting-package',
'package.py'
)
def test_package_class_names(self):
assert 'Mpich' == mod_to_class('mpich')
assert 'PmgrCollective' == mod_to_class('pmgr_collective')
assert 'PmgrCollective' == mod_to_class('pmgr-collective')
assert 'Pmgrcollective' == mod_to_class('PmgrCollective')
assert '_3db' == mod_to_class('3db')
def test_content_hash_all_same_but_patch_contents(self):
spec1 = Spec("hash-test1@1.1")
spec2 = Spec("hash-test2@1.1")
spec1.concretize()
spec2.concretize()
content1 = package_content(spec1)
content1 = content1.replace(spec1.package.__class__.__name__, '')
content2 = package_content(spec2)
content2 = content2.replace(spec2.package.__class__.__name__, '')
assert spec1.package.content_hash(content=content1) != \
spec2.package.content_hash(content=content2)
def test_content_hash_different_variants(self):
spec1 = Spec("hash-test1@1.2 +variantx")
spec2 = Spec("hash-test2@1.2 ~variantx")
spec1.concretize()
spec2.concretize()
content1 = package_content(spec1)
content1 = content1.replace(spec1.package.__class__.__name__, '')
content2 = package_content(spec2)
content2 = content2.replace(spec2.package.__class__.__name__, '')
assert spec1.package.content_hash(content=content1) == \
spec2.package.content_hash(content=content2)
def test_all_same_but_archive_hash(self):
spec1 = Spec("hash-test1@1.3")
spec2 = Spec("hash-test2@1.3")
spec1.concretize()
spec2.concretize()
content1 = package_content(spec1)
content1 = content1.replace(spec1.package.__class__.__name__, '')
content2 = package_content(spec2)
content2 = content2.replace(spec2.package.__class__.__name__, '')
assert spec1.package.content_hash(content=content1) != \
spec2.package.content_hash(content=content2)
# Below tests target direct imports of spack packages from the
# spack.pkg namespace
def test_import_package(self):
import spack.pkg.builtin.mock.mpich # noqa
def test_import_package_as(self):
import spack.pkg.builtin.mock.mpich as mp # noqa
import spack.pkg.builtin.mock # noqa
import spack.pkg.builtin.mock as m # noqa
from spack.pkg.builtin import mock # noqa
def test_inheritance_of_diretives(self):
p = spack.repo.get('simple-inheritance')
# Check dictionaries that should have been filled by directives
assert len(p.dependencies) == 3
assert 'cmake' in p.dependencies
assert 'openblas' in p.dependencies
assert 'mpi' in p.dependencies
assert len(p.provided) == 2
# Check that Spec instantiation behaves as we expect
s = Spec('simple-inheritance')
s.concretize()
assert '^cmake' in s
assert '^openblas' in s
assert '+openblas' in s
assert 'mpi' in s
s = Spec('simple-inheritance~openblas')
s.concretize()
assert '^cmake' in s
assert '^openblas' not in s
assert '~openblas' in s
assert 'mpi' in s
def test_dependency_extensions(self):
s = Spec('extension2')
s.concretize()
deps = set(x.name for x in s.package.dependency_activations())
assert deps == set(['extension1'])
def test_import_class_from_package(self):
from spack.pkg.builtin.mock.mpich import Mpich # noqa
def test_import_module_from_package(self):
from spack.pkg.builtin.mock import mpich # noqa
def test_import_namespace_container_modules(self):
import spack.pkg # noqa
import spack.pkg as p # noqa
from spack import pkg # noqa
import spack.pkg.builtin # noqa
import spack.pkg.builtin as b # noqa
from spack.pkg import builtin # noqa
import spack.pkg.builtin.mock # noqa
import spack.pkg.builtin.mock as m # noqa
from spack.pkg.builtin import mock # noqa
| lgpl-2.1 |
koobonil/Boss2D | Boss2D/addon/tensorflow-1.2.1_for_boss/tensorflow/contrib/distributions/python/ops/normal_conjugate_posteriors.py | 120 | 5530 | # 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.
# ==============================================================================
"""The Normal distribution: conjugate posterior closed form calculations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.distributions import normal
def normal_conjugates_known_scale_posterior(prior, scale, s, n):
"""Posterior Normal distribution with conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known scale posterior" is
the distribution of the unknown `loc`.
Accepts a prior Normal distribution object, having parameters
`loc0` and `scale0`, as well as known `scale` values of the predictive
distribution(s) (also assumed Normal),
and statistical estimates `s` (the sum(s) of the observations) and
`n` (the number(s) of observations).
Returns a posterior (also Normal) distribution object, with parameters
`(loc', scale'**2)`, where:
```
mu ~ N(mu', sigma'**2)
sigma'**2 = 1/(1/sigma0**2 + n/sigma**2),
mu' = (mu0/sigma0**2 + s/sigma**2) * sigma'**2.
```
Distribution parameters from `prior`, as well as `scale`, `s`, and `n`.
will broadcast in the case of multidimensional sets of parameters.
Args:
prior: `Normal` object of type `dtype`:
the prior distribution having parameters `(loc0, scale0)`.
scale: tensor of type `dtype`, taking values `scale > 0`.
The known stddev parameter(s).
s: Tensor of type `dtype`. The sum(s) of observations.
n: Tensor of type `int`. The number(s) of observations.
Returns:
A new Normal posterior distribution object for the unknown observation
mean `loc`.
Raises:
TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a
Normal object.
"""
if not isinstance(prior, normal.Normal):
raise TypeError("Expected prior to be an instance of type Normal")
if s.dtype != prior.dtype:
raise TypeError(
"Observation sum s.dtype does not match prior dtype: %s vs. %s"
% (s.dtype, prior.dtype))
n = math_ops.cast(n, prior.dtype)
scale0_2 = math_ops.square(prior.scale)
scale_2 = math_ops.square(scale)
scalep_2 = 1.0/(1/scale0_2 + n/scale_2)
return normal.Normal(
loc=(prior.loc/scale0_2 + s/scale_2) * scalep_2,
scale=math_ops.sqrt(scalep_2))
def normal_conjugates_known_scale_predictive(prior, scale, s, n):
"""Posterior predictive Normal distribution w. conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known scale predictive"
is the distribution of new observations, conditioned on the existing
observations and our prior.
Accepts a prior Normal distribution object, having parameters
`loc0` and `scale0`, as well as known `scale` values of the predictive
distribution(s) (also assumed Normal),
and statistical estimates `s` (the sum(s) of the observations) and
`n` (the number(s) of observations).
Calculates the Normal distribution(s) `p(x | sigma**2)`:
```
p(x | sigma**2) = int N(x | mu, sigma**2)N(mu | prior.loc, prior.scale**2) dmu
= N(x | prior.loc, 1 / (sigma**2 + prior.scale**2))
```
Returns the predictive posterior distribution object, with parameters
`(loc', scale'**2)`, where:
```
sigma_n**2 = 1/(1/sigma0**2 + n/sigma**2),
mu' = (mu0/sigma0**2 + s/sigma**2) * sigma_n**2.
sigma'**2 = sigma_n**2 + sigma**2,
```
Distribution parameters from `prior`, as well as `scale`, `s`, and `n`.
will broadcast in the case of multidimensional sets of parameters.
Args:
prior: `Normal` object of type `dtype`:
the prior distribution having parameters `(loc0, scale0)`.
scale: tensor of type `dtype`, taking values `scale > 0`.
The known stddev parameter(s).
s: Tensor of type `dtype`. The sum(s) of observations.
n: Tensor of type `int`. The number(s) of observations.
Returns:
A new Normal predictive distribution object.
Raises:
TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a
Normal object.
"""
if not isinstance(prior, normal.Normal):
raise TypeError("Expected prior to be an instance of type Normal")
if s.dtype != prior.dtype:
raise TypeError(
"Observation sum s.dtype does not match prior dtype: %s vs. %s"
% (s.dtype, prior.dtype))
n = math_ops.cast(n, prior.dtype)
scale0_2 = math_ops.square(prior.scale)
scale_2 = math_ops.square(scale)
scalep_2 = 1.0/(1/scale0_2 + n/scale_2)
return normal.Normal(
loc=(prior.loc/scale0_2 + s/scale_2) * scalep_2,
scale=math_ops.sqrt(scalep_2 + scale_2))
| mit |
jimsize/PySolFC | pysollib/pysolgtk/soundoptionsdialog.py | 1 | 5541 | #!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
# ---------------------------------------------------------------------------##
#
# Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer
# Copyright (C) 2003 Mt. Hood Playing Card Co.
# Copyright (C) 2005-2009 Skomoroh
#
# 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/>.
#
# ---------------------------------------------------------------------------##
# imports
import gtk
# PySol imports
from pysollib.mygettext import _
# Toolkit imports
# ************************************************************************
# *
# ************************************************************************
class SoundOptionsDialog:
def __init__(self, parent, title, app, **kw):
saved_opt = app.opt.copy()
glade_file = app.dataloader.findFile('pysolfc.glade')
self.widgets_tree = gtk.glade.XML(glade_file)
keys = [
('areyousure', _('Are You Sure')),
('deal', _('Deal')),
('dealwaste', _('Deal waste')),
('turnwaste', _('Turn waste')),
('startdrag', _('Start drag')),
('drop', _('Drop')),
('droppair', _('Drop pair')),
('autodrop', _('Auto drop')),
('flip', _('Flip')),
('autoflip', _('Auto flip')),
('move', _('Move')),
('nomove', _('No move')),
('undo', _('Undo')),
('redo', _('Redo')),
('autopilotlost', _('Autopilot lost')),
('autopilotwon', _('Autopilot won')),
('gamefinished', _('Game finished')),
('gamelost', _('Game lost')),
('gamewon', _('Game won')),
('gameperfect', _('Perfect game')),
]
table = self.widgets_tree.get_widget('samples_table')
samples_checkbuttons = {}
row = 0
col = 0
for n, t in keys:
check = gtk.CheckButton(t)
check.show()
check.set_active(app.opt.sound_samples[n])
samples_checkbuttons[n] = check
table.attach(check,
col, col+1, row, row+1,
gtk.FILL | gtk.EXPAND, gtk.FILL,
4, 4)
if col == 1:
col = 0
row += 1
else:
col = 1
w = self.widgets_tree.get_widget('enable_checkbutton')
w.set_active(app.opt.sound)
dic = {}
for n in 'sample', 'music':
def callback(w, n=n):
sp = self.widgets_tree.get_widget(n+'_spinbutton')
sc = self.widgets_tree.get_widget(n+'_scale')
sp.set_value(sc.get_value())
dic[n+'_scale_value_changed'] = callback
def callback(w, n=n):
sp = self.widgets_tree.get_widget(n+'_spinbutton')
sc = self.widgets_tree.get_widget(n+'_scale')
sc.set_value(sp.get_value())
dic[n+'_spinbutton_value_changed'] = callback
self.widgets_tree.signal_autoconnect(dic)
w = self.widgets_tree.get_widget('sample_spinbutton')
w.set_value(app.opt.sound_sample_volume)
w = self.widgets_tree.get_widget('music_spinbutton')
w.set_value(app.opt.sound_music_volume)
self._translateLabels()
dialog = self.widgets_tree.get_widget('sounds_dialog')
dialog.set_title(title)
dialog.set_transient_for(parent)
while True: # for `apply'
response = dialog.run()
if response in (gtk.RESPONSE_OK, gtk.RESPONSE_APPLY):
w = self.widgets_tree.get_widget('enable_checkbutton')
app.opt.sound = w.get_active()
w = self.widgets_tree.get_widget('sample_spinbutton')
app.opt.soun_sample_volume = w.get_value()
w = self.widgets_tree.get_widget('music_spinbutton')
app.opt.sound_music_volume = w.get_value()
for n, t in keys:
w = samples_checkbuttons[n]
app.opt.sound_samples[n] = w.get_active()
else:
app.opt = saved_opt
if app.audio:
app.audio.updateSettings()
if response == gtk.RESPONSE_APPLY:
app.audio.playSample('drop', priority=1000)
if response != gtk.RESPONSE_APPLY:
dialog.destroy()
break
def _translateLabels(self):
for n in (
'label76',
'label77',
'label78',
):
w = self.widgets_tree.get_widget(n)
w.set_text(_(w.get_text()))
w = self.widgets_tree.get_widget('enable_checkbutton')
w.set_label(_(w.get_label()))
| gpl-3.0 |
Gabriel-p/mcs_rot_angles | aux_modules/MCs_plane.py | 1 | 38946 |
import numpy as np
from astropy.coordinates import Distance, Angle, SkyCoord
from astropy import units as u
import numpy.linalg as la
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define main path.
import os
import sys
r_path = os.path.realpath(__file__)[:-24]
# print r_path
sys.path.insert(0, r_path + '/modules/')
from MCs_data import MCs_data
def rho_phi(coord, glx_ctr):
# Angular distance between point and center of galaxy.
rho = coord.separation(glx_ctr)
# Position angle between center and coordinates. This is the angle between
# the positive y axis (North) counter-clockwise towards the negative x
# axis (East).
Phi = glx_ctr.position_angle(coord)
# This is the angle measured counter-clockwise from the x positive axis
# (West).
phi = Phi + Angle('90d')
return rho, phi
def dist_filter(r_min, r_max, ra_g, dec_g, dm_g, e_dm_g, gal_cent):
"""
Filter clusters based on their projected angular distances 'rho'.
Values are used as: (r_min, r_max]
"""
# Obtain angular projected distance and position angle for the
# clusters in the galaxy.
coords = SkyCoord(list(zip(*[ra_g, dec_g])), unit=(u.deg, u.deg))
rho_g, phi_g = rho_phi(coords, gal_cent)
# age_f, d_d_f, e_dd_f
ra_f, dec_f, dm_f, e_dm_f, rho_f, phi_f = [], [], [], [], [], []
dm_nf, rho_nf, phi_nf = [], [], []
for i, d in enumerate(ra_g):
if r_min < rho_g[i].degree <= r_max:
ra_f.append(ra_g[i])
dec_f.append(dec_g[i])
dm_f.append(dm_g[i])
e_dm_f.append(e_dm_g[i])
rho_f.append(rho_g[i].degree)
phi_f.append(phi_g[i].degree)
else:
dm_nf.append(dm_g[i])
rho_nf.append(rho_g[i].degree)
phi_nf.append(phi_g[i].degree)
rho_f = Angle(rho_f, unit=u.deg)
phi_f = Angle(phi_f, unit=u.deg)
rho_nf = Angle(rho_nf, unit=u.deg)
phi_nf = Angle(phi_nf, unit=u.deg)
return ra_f, dec_f, rho_f, phi_f, dm_f, e_dm_f, rho_nf, phi_nf, dm_nf
def xyz_coords(rho, phi, D_0, r_dist):
'''
Obtain coordinates in the (x,y,z) system of van der Marel & Cioni (2001)
'''
d_kpc = Distance((10**(0.2 * (np.asarray(r_dist) + 5.))) / 1000.,
unit=u.kpc)
x = d_kpc * np.sin(rho.radian) * np.cos(phi.radian)
y = d_kpc * np.sin(rho.radian) * np.sin(phi.radian)
z = D_0 - d_kpc * np.cos(rho.radian)
x, y, z = x.value, y.value, z.value
return np.array([x, y, z])
def mvee(points, tol=0.001):
"""
Find the minimum volume ellipse.
Return A, c where the equation for the ellipse given in "center form" is
(x-c).T * A * (x-c) = 1
http://stackoverflow.com/a/14025140/1391441
"""
points = np.asmatrix(points)
N, d = points.shape
Q = np.column_stack((points, np.ones(N))).T
err = tol + 1.0
u = np.ones(N) / N
while err > tol:
# assert u.sum() == 1 # invariant
X = Q * np.diag(u) * Q.T
M = np.diag(Q.T * la.inv(X) * Q)
jdx = np.argmax(M)
step_size = (M[jdx] - d - 1.0) / ((d + 1) * (M[jdx] - 1.))
new_u = (1 - step_size) * u
new_u[jdx] += step_size
err = la.norm(new_u - u)
u = new_u
c = u * points
A = la.inv(points.T * np.diag(u) * points - c.T * c) / d
return np.asarray(A), np.squeeze(np.asarray(c))
def ellipse(rx, ry, rz, u, v):
x = rx * np.cos(u) * np.cos(v)
y = ry * np.sin(u) * np.cos(v)
z = rz * np.sin(v)
return x, y, z
def get_ellipse(N_ran, rho, phi, D_0, dm_g, e_dm_g):
"""
See: http://stackoverflow.com/a/14025140/1391441
"""
ellip_matrix, centers = [], []
for _ in range(N_ran):
print(_)
# Random draw.
r_dist = np.random.normal(np.asarray(dm_g), np.asarray(e_dm_g))
# r_dist = np.asarray(dm_g) # DEL
x, y, z = xyz_coords(rho, phi, D_0, r_dist)
coords = np.asarray(list(zip(*[x, y, z])))
# A : (d x d) matrix of the ellipse equation in the 'center form':
# (x-c)' * A * (x-c) = 1
# 'centroid' is the center coordinates of the ellipse.
A, centroid = mvee(coords)
ellip_matrix.append(A)
centers.append(centroid)
A = np.mean(ellip_matrix, axis=0)
centroid = np.mean(centers, axis=0)
# V is the rotation matrix that gives the orientation of the ellipsoid.
# https://en.wikipedia.org/wiki/Rotation_matrix
# http://mathworld.wolfram.com/RotationMatrix.html
U, D, V = la.svd(A)
# x, y, z radii.
rx, ry, rz = 1. / np.sqrt(D)
# print 'rads', rx/2., ry/2., rz/2.
u_small, v_small = np.mgrid[0:2 * np.pi:20j, -np.pi / 2:np.pi / 2:10j]
E = np.dstack(ellipse(rx, ry, rz, u_small, v_small))
E = np.dot(E, V) + centroid
x_e, y_e, z_e = np.rollaxis(E, axis=-1)
return x_e, y_e, z_e
def inv_trans_eqs(x_p, y_p, z_p, theta, inc):
"""
Inverse set of equations. Transform inclined plane system (x',y',z')
into face on sky system (x,y,z).
"""
x = x_p * np.cos(theta.radian) -\
y_p * np.cos(inc.radian) * np.sin(theta.radian) -\
z_p * np.sin(inc.radian) * np.sin(theta.radian)
y = x_p * np.sin(theta.radian) +\
y_p * np.cos(inc.radian) * np.cos(theta.radian) +\
z_p * np.sin(inc.radian) * np.cos(theta.radian)
z = -1. * y_p * np.sin(inc.radian) + z_p * np.cos(inc.radian)
return x, y, z
def make_plot(D_0, inc, theta, cl_xyz, cl_xyz_nf, dm_f, x_e, y_e, z_e):
"""
Original link for plotting intersecting planes:
http://stackoverflow.com/a/14825951/1391441
"""
# Make plot.
fig = plt.figure()
ax = Axes3D(fig)
# Plot ellipse.
# ax.plot_surface(x_e, z_e, y_e, cstride=1, rstride=1, alpha=0.05)
# Plot points inside the ellipse, with no random displacement.
x_cl, y_cl, z_cl = cl_xyz
if cl_xyz.size:
SC = ax.scatter(x_cl, z_cl, y_cl, c=dm_f, s=50)
min_X, max_X = min(x_cl) - 2., max(x_cl) + 2.
min_Y, max_Y = min(y_cl) - 2., max(y_cl) + 2.
# # Plot points *outside* the ellipse, with no random displacement.
# x_cl_nf, y_cl_nf, z_cl_nf = cl_xyz_nf
# if cl_xyz_nf.size:
# SC = ax.scatter(x_cl, z_cl_nf, y_cl_nf, c=dm_f, s=50)
# x,y plane.
X, Y = np.meshgrid([min_X, max_X], [min_Y, max_Y])
Z = np.zeros((2, 2))
# Plot x,y plane.
ax.plot_surface(X, Z, Y, color='gray', alpha=.2, linewidth=0, zorder=1)
# Axis of x,y plane.
# x axis.
ax.plot([min_X, max_X], [0., 0.], [0., 0.], ls='--', c='k', zorder=4)
# Arrow head pointing in the positive x direction.
ax.quiver(max_X, 0., 0., max_X, 0., 0., length=0.3,
arrow_length_ratio=1., color='k')
# y axis.
ax.plot([0., 0.], [0., 0.], [0., max_Y], ls='--', c='k')
# Arrow head pointing in the positive y direction.
ax.quiver(0., 0., max_Y, 0., 0., max_Y, length=0.3,
arrow_length_ratio=1., color='k')
ax.plot([0., 0.], [0., 0.], [min_Y, 0.], ls='--', c='k')
#
#
# A plane is a*x+b*y+c*z+d=0, [a,b,c] is the normal.
a, b, c, d = -1. * np.sin(theta.radian) * np.sin(inc.radian),\
np.cos(theta.radian) * np.sin(inc.radian),\
np.cos(inc.radian), 0.
print('a/c,b/c,1,d/c:', a / c, b / c, 1., d / c)
# Rotated plane.
X2_t, Y2_t = np.meshgrid([min_X, max_X], [0, max_Y])
Z2_t = (-a * X2_t - b * Y2_t) / c
X2_b, Y2_b = np.meshgrid([min_X, max_X], [min_Y, 0])
Z2_b = (-a * X2_b - b * Y2_b) / c
# Top half of first x',y' inclined plane.
ax.plot_surface(X2_t, Z2_t, Y2_t, color='red', alpha=.2, lw=0, zorder=3)
# Bottom half of inclined plane.
ax.plot_surface(X2_t, Z2_b, Y2_b, color='red', alpha=.2, lw=0, zorder=-1)
# Axis of x',y' plane.
# x' axis.
x_min, y_min, z_min = inv_trans_eqs(min_X, 0., 0., theta, inc)
x_max, y_max, z_max = inv_trans_eqs(max_X, 0., 0., theta, inc)
ax.plot([x_min, x_max], [z_min, z_max], [y_min, y_max], ls='--', c='b')
# Arrow head pointing in the positive x' direction.
ax.quiver(x_max, z_max, y_max, x_max, z_max, y_max, length=0.3,
arrow_length_ratio=1.2)
# y' axis.
x_min, y_min, z_min = inv_trans_eqs(0., min_Y, 0., theta, inc)
x_max, y_max, z_max = inv_trans_eqs(0., max_Y, 0., theta, inc)
ax.plot([x_min, x_max], [z_min, z_max], [y_min, y_max], ls='--', c='g')
# Arrow head pointing in the positive y' direction.
ax.quiver(x_max, z_max, y_max, x_max, z_max, y_max, length=0.3,
arrow_length_ratio=1.2, color='g')
#
#
# a, b, c, d = pts123_abcd
# print 'a/c,b/c,1,d/c:', a / c, b / c, 1., d / c
# # Plane obtained fitting cloud of clusters.
# X3_t, Y3_t = np.meshgrid([min_X, max_X], [0, max_Y])
# Z3_t = (-a*X3_t - b*Y3_t - d) / c
# X3_b, Y3_b = np.meshgrid([min_X, max_X], [min_Y, 0])
# Z3_b = (-a*X3_b - b*Y3_b - d) / c
# # Top half of second x',y' inclined plane.
# ax.plot_surface(X3_t, Z3_t, Y3_t, color='g', alpha=.2, lw=0, zorder=3)
# # Bottom half of inclined plane.
# ax.plot_surface(X3_b, Z3_b, Y3_b, color='g', alpha=.2, lw=0, zorder=-1)
# # Axis of x',y' plane.
# # x' axis.
# x_min, y_min, z_min = inv_trans_eqs(min_X, 0., 0., theta_pl, inc_pl)
# x_max, y_max, z_max = inv_trans_eqs(max_X, 0., 0., theta_pl, inc_pl)
# ax.plot([x_min, x_max], [z_min, z_max], [y_min, y_max], ls='--', c='b')
# # Arrow head pointing in the positive x' direction.
# ax.quiver(x_max, z_max, y_max, x_max, z_max, y_max, length=0.3,
# arrow_length_ratio=1.2)
# # y' axis.
# x_min, y_min, z_min = inv_trans_eqs(0., min_Y, 0., theta_pl, inc_pl)
# x_max, y_max, z_max = inv_trans_eqs(0., max_Y, 0., theta_pl, inc_pl)
# ax.plot([x_min, x_max], [z_min, z_max], [y_min, y_max], ls='--', c='g')
# # Arrow head pointing in the positive y' direction.
# ax.quiver(x_max, z_max, y_max, x_max, z_max, y_max, length=0.3,
# arrow_length_ratio=1.2, color='g')
ax.set_xlabel('x (Kpc)')
ax.set_ylabel('z (Kpc)')
ax.set_ylim(max_Y, min_Y)
ax.set_zlabel('y (Kpc)')
plt.colorbar(SC, shrink=0.9, aspect=25)
ax.axis('equal')
ax.axis('tight')
# ax.view_init(elev=35., azim=-25.)
plt.show()
# plt.savefig('MCs_bulge_plane.png', dpi=150)
def plot_bulge_plane(ra_g, dec_g, dm_g, e_dm_g, D_0, gal_cent, glx_inc, theta):
"""
"""
# Projected angular distance filter.
r_min, r_max = 0., 20.
ra_f, dec_f, rho_f, phi_f, dm_f, e_dm_f, rho_nf, phi_nf, dm_nf =\
dist_filter(r_min, r_max, ra_g, dec_g, dm_g, e_dm_g, gal_cent)
cl_xyz = xyz_coords(rho_f, phi_f, D_0, dm_f)
cl_xyz_nf = xyz_coords(rho_nf, phi_nf, D_0, dm_nf)
# Number of times the error ellipse will be obtained after randomly
# shifting the distance moduli.
N_ran = 2
x_e, y_e, z_e = get_ellipse(N_ran, rho_f, phi_f, D_0, dm_f, e_dm_f)
make_plot(D_0, glx_inc, theta, cl_xyz, cl_xyz_nf, dm_f, x_e, y_e, z_e)
if __name__ == "__main__":
"""
3D plot of bulge, clusters, and fitted planes.
"""
ra = [[15.5958333333333, 12.1375, 10.9333333333333, 17.225, 15.1416666666667, 15.0041666666667, 14.3416666666667, 13.5625, 357.245833333333, 15.1041666666667, 11.3583333333333, 16.0916666666667, 14.4583333333333, 16.8333333333333, 22.6583333333333, 9.425, 18.875, 18.2583333333333, 13.3541666666667, 24.0041666666667, 11.6833333333333, 23.75, 23.3083333333333, 17.5541666666667, 25.4291666666667, 4.60416666666667, 19.5666666666667, 25.5916666666667, 11.8, 15.2833333333333, 21.2333333333333, 11.475, 29.1833333333333, 18.0166666666667, 5.66666666666667, 14.45, 22.8833333333333, 14.4458333333333, 13.275, 25.6166666666667, 11.2166666666667, 13.1458333333333, 10.7458333333333, 13.8875, 15.9708333333333, 14.425, 6.17916666666667, 20.7, 18.2125, 27.3666666666667, 5.3625, 10.35, 23.6083333333333, 5.76666666666667, 17.0791666666667, 15.1458333333333, 27.5791666666667, 11.9583333333333, 16.0166666666667, 12.3625, 17.6958333333333, 15.2333333333333, 15.4916666666667, 11.5041666666667, 14.325, 15.2041666666667, 17.0583333333333, 14.0583333333333, 16.8791666666667, 16.7375, 13.6291666666667, 12.5875, 14.3333333333333, 15.35, 17.2583333333333, 12.325, 15.1375, 10.8875, 12.1541666666667, 11.775, 16.2583333333333, 11.7291666666667, 10.9083333333333, 12.05, 11.8541666666667, 12.0041666666667, 15.7958333333333, 17.2541666666667, 15.0583333333333], [76.4166666666667, 74.225, 82.9916666666667, 78.8541666666667, 76.1416666666667, 88.0458333333333, 72.3083333333333, 76.5083333333333, 78.8125, 87.7, 76.9458333333333, 77.3, 76.1375, 77.2208333333333, 73.9208333333333, 86.4583333333333, 76.9833333333333, 83.3333333333333, 72.7958333333333, 77.7333333333333, 86.0458333333333, 72.2791666666667, 72.5875, 77.625, 86.7166666666667, 71.8583333333333, 72.6208333333333, 78.9458333333333, 76.975, 74.725, 86.7125, 73.7625, 72.25, 94.3291666666667, 76.5375, 91.8708333333333, 74.5583333333333, 93.4833333333333, 72.1541666666667, 70.8083333333333, 73.4625, 79.7583333333333, 76.55, 82.9416666666667, 74.5416666666667, 76.9416666666667, 78.1041666666667, 74.3916666666667, 76.6416666666667, 85.9833333333333, 81.55, 74.9416666666667, 69.925, 79.5208333333333, 82.6416666666667, 74.9083333333333, 82.2083333333333, 95.3916666666667, 79.4541666666667, 67.6666666666667, 77.7958333333333, 85.375, 77.3958333333333, 76.4708333333333, 69.4125, 76.5125, 74.8083333333333, 76.6041666666667, 85.8958333333333, 82.4833333333333, 79.1666666666667, 77.7875, 78.45, 76.125, 82.925, 73.1875, 82.85, 72.7, 92.2208333333333, 93.9875, 88.8958333333333, 85.8333333333333, 74.1208333333333, 84.7833333333333, 80.05, 72.4125, 73.55, 71.5166666666667, 77.3458333333333, 77.9208333333333, 77.65, 81.3625, 74.7125, 81.1166666666667, 79.2333333333333, 81.125, 68.9083333333333, 93.6166666666667, 91.6291666666667, 74.3583333333333, 73.7541666666667, 83.0125, 86.55, 93.6708333333333, 74.9708333333333, 76.8958333333333, 79.2208333333333, 79.0708333333333, 77.9166666666667, 82.4416666666667, 77.3125, 83.2541666666667, 77.5083333333333, 83.6625, 74.5625, 80.4375, 79.6708333333333, 85.4916666666667, 71.6041666666667, 73.225, 76.9041666666667, 76.4, 86.4833333333333, 85.1083333333333, 77.6666666666667, 74.5916666666667, 77.7208333333333, 73.9666666666667, 82.3333333333333, 85.4541666666667, 77.6333333333333, 79.1125, 80.0083333333333, 71.875, 88.925, 85.6208333333333, 84.4416666666667, 86.3625, 80.8, 83.0958333333333, 77.2125, 82.9625, 76.8375, 76.6708333333333, 83.5541666666667, 82.4958333333333, 85.4125, 82.4125, 76.3541666666667, 76.6416666666667]]
dec = [[-72.0030555555556, -73.3069444444444, -72.9766666666667, -73.2416666666667, -72.3655555555556, -72.3688888888889, -71.8913888888889, -72.2413888888889, -72.9452777777778, -71.2947222222222, -73.4813888888889, -72.8477777777778, -72.9436111111111, -73.3775, -76.0544444444444, -73.9083333333333, -71.1788888888889, -70.9627777777778, -72.1963888888889, -75.4577777777778, -72.0630555555556, -75.5566666666667, -74.1672222222222, -73.2091666666667, -71.1611111111111, -74.3186111111111, -72.0016666666667, -74.1733333333333, -73.4772222222222, -74.0736111111111, -71.1836111111111, -73.5066666666667, -74.2194444444445, -75.1975, -75.0747222222222, -73.4216666666667, -71.9527777777778, -74.3266666666667, -73.3802777777778, -71.2791666666667, -73.0019444444445, -72.1930555555556, -72.5886111111111, -74.0636111111111, -72.8261111111111, -74.4727777777778, -73.755, -75.0016666666667, -73.1194444444444, -73.7283333333333, -73.7486111111111, -72.8908333333333, -72.8744444444444, -73.6697222222222, -72.8841666666667, -71.4608333333333, -74.3561111111111, -73.4783333333333, -74.6191666666667, -73.3980555555556, -72.7919444444444, -73.1516666666667, -71.0202777777778, -73.3955555555556, -72.9327777777778, -73.3488888888889, -73.2569444444444, -74.1561111111111, -73.1197222222222, -73.235, -74.1852777777778, -73.3872222222222, -71.1702777777778, -73.2402777777778, -73.0863888888889, -73.3716666666667, -72.2583333333333, -73.4388888888889, -73.4155555555556, -73.3730555555556, -73.0427777777778, -73.4233333333333, -73.4405555555556, -73.4463888888889, -73.4580555555556, -73.4861111111111, -72.2736111111111, -73.2066666666667, -72.4583333333333], [-68.6394444444445, -68.0022222222222, -67.9716666666667, -68.6811111111111, -68.2083333333333, -71.8583333333333, -72.0566666666667, -68.0263888888889, -68.8825, -71.7077777777778, -66.7980555555556, -68.4441666666667, -67.9755555555556, -68.0836111111111, -67.7833333333333, -69.3802777777778, -67.3577777777778, -68.1522222222222, -67.5347222222222, -67.6266666666667, -69.3333333333333, -67.3416666666667, -72.8275, -68.4005555555556, -69.1897222222222, -67.6597222222222, -67.3258333333333, -69.1919444444445, -67.9288888888889, -67.8469444444445, -69.4197222222222, -67.9644444444444, -72.64, -70.0608333333333, -68.4458333333333, -72.4941666666667, -67.7683333333333, -72.5052777777778, -68.5594444444444, -73.8119444444444, -69.5719444444444, -69.0011111111111, -68.0630555555556, -68.2355555555556, -68.0602777777778, -67.8613888888889, -68.7719444444444, -65.2677777777778, -68.3630555555556, -69.1805555555556, -70.9813888888889, -69.8011111111111, -74.0172222222222, -69.1716666666667, -63.2033333333333, -69.5575, -71.6327777777778, -72.79, -68.4727777777778, -66.9569444444444, -67.6266666666667, -69.185, -67.8105555555556, -67.0494444444445, -66.1994444444444, -68.6283333333333, -67.9083333333333, -68.375, -66.2086111111111, -72.0547222222222, -70.5408333333333, -67.6825, -66.62, -68.3497222222222, -72.1461111111111, -72.5177777777778, -72.0425, -72.5766666666667, -72.3838888888889, -70.0730555555556, -62.3452777777778, -66.2622222222222, -67.6227777777778, -74.8533333333333, -68.9041666666667, -72.2480555555556, -69.8069444444444, -66.9113888888889, -67.7783333333333, -67.5655555555556, -70.4875, -73.5702777777778, -69.9577777777778, -67.7286111111111, -68.6827777777778, -67.6780555555556, -73.7316666666667, -72.6094444444445, -72.2263888888889, -67.6852777777778, -67.7141666666667, -64.2422222222222, -69.0825, -69.8019444444445, -67.9236111111111, -67.4608333333333, -69.15, -69.1541666666667, -68.7266666666667, -71.0005555555556, -67.6997222222222, -67.8491666666667, -66.6991666666667, -68.3055555555556, -68.0491666666667, -68.9172222222222, -69.0794444444444, -69.0475, -72.5683333333333, -72.1725, -68.5419444444444, -68.6286111111111, -69.2719444444444, -69.2486111111111, -68.7536111111111, -69.8030555555556, -67.4711111111111, -69.7058333333333, -70.5794444444445, -68.9208333333333, -66.94, -69.0802777777778, -69.2611111111111, -72.5883333333333, -74.3538888888889, -65.3627777777778, -74.7827777777778, -69.3452777777778, -70.7777777777778, -67.9969444444444, -67.9802777777778, -67.9911111111111, -66.8291666666667, -67.8422222222222, -67.8563888888889, -67.8788888888889, -69.2294444444444, -70.9838888888889, -68.5005555555556, -68.4272222222222]]
dist_cent = [[1633.20060682, 2320.18925372, 2441.9621715, 1471.75739309, 2376.23276698, 769.377260812, 1217.10160803, 1804.52411396, 5941.22951677, 2131.04017704, 909.015121115, 3069.45508982, 2364.25345255, 2670.26753775, 4890.13489057, 2343.49016847, 3159.23688725, 2711.83412564, 1818.55754823, 4455.35179015, 1123.62228704, 4757.29044595, 3641.00953753, 2648.4875134, 4474.93618064, 3141.57483709, 3560.24707724, 4473.53808798, 1395.16822521, 1590.48289743, 4018.53487003, 1077.40931903, 5110.49822201, 3786.85646257, 4265.8368639, 949.628191291, 3943.07061992, 1767.67615703, 1299.74797416, 4641.567255, 2418.05685486, 897.32557739, 3039.33043949, 1461.11210457, 1901.98375256, 2165.3084445, 2985.15151754, 3722.76959311, 2000.6292342, 4885.31051319, 2625.48765461, 1076.03465615, 3317.63420596, 2482.45477321, 1670.70686978, 1704.67888631, 4679.63812859, 3032.23144391, 2116.49256805, 2422.17347074, 1542.38398274, 3014.72270399, 2369.65890352, 1867.37485958, 688.161984621, 2390.12368317, 1417.8418462, 2759.56312304, 1647.94174103, 2532.76451148, 2666.69527657, 1799.77351614, 1911.04658283, 2378.98229824, 1319.33831563, 646.650576733, 1952.83158151, 2437.45811475, 1828.61711731, 1838.06758207, 1147.07949676, 2459.7173664, 1123.54113051, 1845.94527547, 2373.7888037, 2374.78095982, 1177.87078532, 1347.286255, 724.047475304], [2094.92442356, 2592.17806506, 1926.01374032, 1393.13441938, 2375.35464572, 3301.57725704, 3191.52180512, 1846.0135317, 716.76297379, 3154.98748878, 3076.59112567, 2026.05665608, 2404.83900491, 1555.09594563, 2707.74040478, 2869.88446607, 2126.74995801, 1875.64558761, 3013.12651671, 1938.91000725, 2787.32652108, 3248.71116208, 3895.8901948, 2000.81445911, 2338.12168352, 3264.69637398, 3074.99893799, 2636.47366843, 2026.34617439, 2555.05591583, 1987.45137574, 2962.78454192, 3645.08442741, 4482.58313968, 1839.78891743, 4308.71233216, 2341.82811636, 4655.60143549, 2645.31421226, 4649.97712828, 2659.06169124, 495.958510033, 1712.84745196, 2951.12877171, 2751.29010002, 1869.62116249, 1815.09401991, 4178.76760298, 1500.54520148, 1794.75124939, 2529.48578966, 1640.54629482, 5595.45850131, 776.552314833, 5577.42226175, 2249.44973927, 3280.94442372, 5192.25922245, 2306.05901115, 4799.58913132, 1930.71867668, 1618.96956185, 2738.38874315, 2453.83795634, 4563.65453258, 1390.93463993, 2210.73606753, 2156.22099955, 3489.11690674, 2339.47934036, 1913.24925842, 1765.47926278, 2664.78715134, 1747.9825195, 2559.15521594, 3985.98208869, 2470.42710796, 3449.61772162, 4247.88799427, 4176.76382235, 6981.56554962, 3438.49595369, 2544.39520164, 4846.09325026, 859.207154012, 4248.51583614, 3334.30573069, 3728.40654495, 1759.97165254, 2178.23559988, 1194.19833024, 3858.08899466, 1864.27857663, 1561.90783843, 2706.82540924, 1747.18252909, 4836.99690823, 4641.18832985, 4140.00763706, 2964.26958036, 3078.63612913, 4672.26090061, 2310.20822426, 4180.41248267, 2162.15029365, 2072.33397643, 1238.51032921, 832.357478845, 1488.41649353, 2593.59405836, 1824.3311299, 2309.75855988, 2853.29775447, 2151.58363423, 2434.44194297, 2082.03137409, 1198.78596379, 1997.28834526, 3626.80120077, 3532.99815015, 2924.8945852, 2101.1318558, 2466.86972041, 2506.56843199, 2352.67147924, 2754.38598176, 1932.30496879, 2459.48921061, 1639.6977746, 1695.42812081, 2380.69363485, 2640.55720245, 2121.15585755, 3588.5380412, 4855.28448834, 4857.60200313, 4765.37072491, 1887.71370931, 1942.00303845, 1926.04452804, 2570.73288389, 1574.74408319, 3067.96627803, 1827.77703955, 1778.39064842, 2280.49016348, 1949.46253097, 2136.73909356, 1495.06656829, 1870.72119252]]
e_d_cent = [[1039.173740299393, 1435.9536198970777, 1778.3059807875993, 833.5600644307985, 944.8627199983013, 9.540124318824205, 823.8633204223586, 1401.4181419730958, 827.5312450161011, 1163.202855888643, 13.237829767759157, 1792.3207837264274, 1560.168479675753, 1148.1705423534424, 755.9245287150616, 892.191969353227, 884.4665374591882, 415.35433225392086, 1875.7404289875428, 442.41685887935273, 797.3852853246149, 893.6966802217544, 715.515865771003, 1468.0163280348056, 180.07593240624257, 310.93678012208176, 1539.3048577844493, 645.5935589311879, 1221.0569425039175, 622.8771608179757, 777.3761195766289, 830.7302823568057, 74.42330047098997, 821.8292306571432, 1103.510336489361, 940.0405957271148, 822.4108254121722, 608.4887378615729, 1148.9388310016825, 587.5570422769338, 1526.421120290217, 1168.2108316701813, 1273.2683945252095, 393.432086570192, 1557.4353087829875, 844.2681890359437, 770.8856764819485, 760.2515378456518, 910.6248838134877, 598.6815415818562, 38.23452198067387, 978.0345113217967, 34.163250596628764, 36.151558902120726, 1015.1877769341709, 494.3376980922027, 68.14875955525937, 1541.2904129789106, 17.571308861202773, 1792.3673345822394, 458.22021965535055, 1283.3482722452554, 825.5956710209496, 1353.1526557220127, 1291.585217521375, 1159.6867266474756, 599.8811014721533, 1580.683975865727, 857.1852247427792, 1537.8170745504758, 1243.6395933750302, 1169.2812348399343, 365.9048145832149, 1640.885818719533, 13.585851453369786, 5.368550393503098, 1899.2919526321182, 1839.912870204379, 1621.6520186557234, 1144.4604372844262, 875.8209539282942, 1765.885395992803, 762.8973515574974, 1847.1410426886998, 1644.595816646902, 1643.8858310928317, 489.95206768810164, 16.70608038529138, 10.544177978144234], [1785.2629840823188, 1041.566284758639, 1467.6674047933768, 1923.8136494672647, 1716.0321102312591, 915.244895489895, 221.1675461512587, 861.867312378096, 840.6042035290191, 844.2414907308923, 1314.2330413768143, 1770.5151998468243, 1633.4007149260217, 368.65492682278284, 1058.123240416804, 1840.4439280460017, 284.2266672489778, 1506.0332777066492, 514.4581837549737, 878.2567435346746, 1708.3601232217165, 472.68214070414155, 997.4875266424194, 1954.127788865912, 1228.248441899879, 856.8220621495436, 221.15248443469196, 2353.736947917064, 1397.013963090411, 1120.4495754771256, 299.74838064309364, 1170.9093515493155, 414.38923232920945, 912.2142994105723, 1534.6450360693136, 645.6729294664426, 264.5515241024804, 345.43316624042524, 247.75738755022581, 653.3364213144663, 1445.3983698014852, 1050.9281645823662, 344.67425076422523, 1995.0077769507548, 1475.4497099997725, 825.5266504486219, 2150.14206872408, 454.5676595110679, 368.51923389480214, 336.38429850370164, 1890.5055794165903, 351.828770708083, 994.9605893924067, 2229.0283582517486, 548.3166216178901, 1742.920966906669, 1984.4888736732746, 566.106410249732, 2434.639259730216, 622.6818281879467, 936.9663122493897, 318.60972914001735, 1931.1872592082586, 165.28422562460204, 89.07313767059404, 423.11626224110586, 243.6303481764325, 1816.3310639967779, 435.7639805821094, 270.7290811126059, 2139.7993528686457, 310.6312946105225, 629.1766510798647, 907.0254731098203, 580.6065658166992, 1309.0795526339405, 681.692149849808, 155.04438853570673, 92.31684124911177, 136.71413051358266, 630.9594773060937, 443.11461492136965, 209.3880413379435, 110.5204345895767, 2013.1230449025077, 1518.1460692179344, 1951.8103229039705, 762.6417741189457, 290.3259190547951, 1400.7507173640981, 442.85762169709034, 1086.835709620925, 914.7013000175225, 367.2400890475026, 2182.627764031268, 1037.4172952821752, 110.51264193361975, 198.1143051051561, 698.273859249986, 1365.9485757880254, 1122.979469109, 413.50630387776516, 1243.5706321936586, 692.719607065467, 229.5825564846332, 261.3031238931711, 2347.1190868041, 2194.0422166832936, 1670.1045987321418, 1841.9016208506491, 299.8714988772865, 1624.557624100974, 1063.2981681602307, 1820.151128560012, 1081.256744265969, 2280.823993202776, 2062.179945562474, 1302.6619137307714, 206.9994601689073, 1212.1724246853282, 2013.6803279587316, 1956.0130420885787, 1593.5985662002408, 1725.1768982775568, 2138.5128286813383, 1919.6897087683137, 315.76110544137276, 1470.8243533267491, 1766.3716811308943, 332.203147610922, 224.8820964437035, 2478.4850127560644, 2377.8401976977834, 207.7094605398353, 132.62699690261672, 1238.1214902654456, 110.50946129093892, 293.3991946533112, 2113.9358140607815, 1403.4104181381058, 1943.7259970491498, 351.0171521341531, 1318.071612339641, 331.1161250625808, 286.95452010783447, 1695.0764266614954, 1387.1609196274565, 1682.152980716172, 395.94052375974496, 1337.190585009628]]
aarr = [[[9.0, 8.9, 8.75, 9.9, 8.2, 8.1, 9.1, 7.9, 9.6, 9.6, 8.9, 9.6, 9.1, 9.2, 9.2, 9.45, 9.1, 9.3, 7.4, 9.6, 9.85, 9.1, 9.7, 9.55, 9.35, 9.15, 9.4, 9.0, 8.45, 9.7, 8.95, 8.0, 7.95, 9.45, 9.45, 9.65, 9.0, 9.05, 8.8, 9.3, 9.05, 8.0, 8.9, 9.5, 7.8, 9.8, 9.15, 9.8, 9.6, 9.55, 9.6, 9.45, 9.7, 9.75, 8.95, 9.6, 8.2, 8.8, 9.2, 8.7, 8.3, 8.4, 9.1, 8.5, 8.8, 8.35, 8.75, 9.6, 8.8, 8.3, 9.4, 8.3, 8.4, 8.0, 8.0, 8.5, 7.8, 8.7, 8.0, 8.4, 8.0, 8.1, 8.0, 8.0, 8.2, 6.9, 7.0, 7.2, 6.7], [9.20411998265592, 9.14612803567824, 8.79934054945358, 9.82607480270083, 8.04139268515822, 8.09691001300806, 8.79934054945358, 7.90308998699194, 9.77815125038364, 9.73239375982297, 9.17609125905568, 9.36172783601759, 9.30102999566398, 9.39794000867204, 9.20411998265592, 9.32221929473392, 9.10037054511756, 9.44715803134222, 7.39794000867204, 9.81291335664286, 9.77815125038364, 9.04139268515822, 9.47712125471966, 9.73239375982297, 9.07918124604762, 9.06069784035361, 9.32221929473392, 9.04139268515822, 8.39794000867204, 9.96848294855393, 8.77815125038364, 8.20411998265593, 8.04139268515822, 9.57978359661681, 9.61278385671973, 9.49136169383427, 9.14612803567824, 9.30102999566398, 8.5051499783199, 9.25527250510331, 9.07918124604762, 8.14612803567824, 9.0, 9.68124123737559, 7.39794000867204, 9.73239375982297, 9.30102999566398, 9.67209785793572, 9.63346845557959, 9.77815125038364, 9.49136169383427, 9.32221929473392, 9.80617997398389, 9.51851393987789, 9.07918124604762, 9.77815125038364, 8.14612803567824, 8.69897000433602, 9.44715803134222, 8.35, 8.25, 8.4, 9.15, 8.4, 8.65, 8.1, 8.65, 9.45, 8.45, 8.1, 9.25, 8.4, 7.9, 8.1, 8.3, 8.05, 7.7, 8.35, 7.9, 8.1, 8.0, 7.9, 7.8, 8.1, 8.4, 8.34242268082221, 7.9, 8.15, 8.1]], [[8.45, 8.2, 8.2, 8.7, 8.9, 9.3, 8.9, 9.15, 8.4, 8.6, 8.8, 9.1, 8.95, 8.8, 8.3, 8.6, 9.0, 9.5, 8.8, 8.6, 8.7, 9.1, 9.05, 9.1, 9.2, 8.6, 9.0, 8.7, 8.3, 9.05, 9.1, 9.1, 9.0, 9.0, 8.2, 9.2, 8.9, 9.05, 9.05, 9.3, 9.1, 9.15, 8.65, 9.4, 9.2, 9.05, 8.8, 9.5, 7.9, 9.0, 8.4, 8.95, 9.2, 8.3, 9.4, 8.3, 8.9, 9.05, 9.5, 9.2, 9.05, 8.0, 8.2, 9.1, 9.15, 8.3, 8.9, 8.65, 9.1, 8.85, 9.1, 8.7, 8.8, 9.0, 9.3, 9.25, 8.75, 9.05, 9.3, 9.4, 9.3, 9.45, 8.95, 9.3, 8.0, 9.3, 9.1, 8.65, 9.1, 8.6, 8.95, 9.4, 9.15, 9.5, 8.75, 8.8, 9.55, 9.15, 9.2, 9.1, 9.15, 9.2, 9.45, 9.2, 9.15, 9.0, 8.8, 8.0, 8.0, 9.5, 7.9, 9.0, 8.3, 8.8, 8.4, 8.8, 8.85, 8.1, 9.55, 8.3, 9.15, 8.8, 8.2, 7.9, 8.8, 8.3, 8.9, 8.1, 8.3, 8.0, 8.4, 8.7, 8.6, 9.25, 9.2, 9.45, 9.25, 8.8, 9.1, 8.8, 9.55, 7.9, 8.6, 9.1, 7.0, 6.7, 7.7, 7.3, 8.85, 7.5], [8.0, 8.1, 8.25, 8.69897000433602, 9.14612803567824, 9.30102999566398, 9.14612803567824, 9.11394335230684, 8.20411998265593, 8.5051499783199, 8.95424250943932, 9.1, 8.75, 8.60205999132796, 8.35, 8.45, 9.04139268515822, 9.39794000867204, 8.60205999132796, 8.69897000433602, 8.7, 9.09691001300805, 9.11394335230684, 8.89762709129044, 9.30102999566398, 8.55, 8.9, 8.75, 8.25, 9.23044892137827, 9.0, 8.89762709129044, 9.04139268515822, 9.14612803567824, 8.0, 9.25527250510331, 8.69897000433602, 9.0, 8.84509804001426, 9.20411998265592, 9.0, 9.11394335230684, 8.55, 9.23044892137827, 9.14612803567824, 9.17609125905568, 8.69897000433602, 9.34242268082221, 7.9, 9.09691001300805, 8.4, 9.20411998265592, 9.39794000867204, 8.3, 9.41497334797082, 8.05, 8.95424250943932, 8.79934054945358, 9.20411998265592, 9.20411998265592, 9.04139268515822, 8.25, 8.25, 9.14612803567824, 9.17609125905568, 8.09691001300806, 8.69897000433602, 8.5051499783199, 9.17609125905568, 8.84509804001426, 9.17609125905568, 8.60205999132796, 8.79934054945358, 8.7481880270062, 9.27875360095283, 9.20411998265592, 8.60205999132796, 8.95424250943932, 9.23044892137827, 9.14612803567824, 9.38021124171161, 9.36172783601759, 8.85125834871907, 9.25527250510331, 8.2, 9.20411998265592, 9.11394335230684, 8.6, 9.14612803567824, 8.60205999132796, 9.07918124604762, 9.25527250510331, 9.17609125905568, 9.34242268082221, 8.65321251377534, 8.69897000433602, 9.39794000867204, 9.04139268515822, 9.25527250510331, 9.20411998265592, 9.20411998265592, 9.23044892137827, 9.36172783601759, 9.23044892137827, 9.17609125905568, 9.14612803567824, 8.3, 8.3, 7.69897000433602, 9.25527250510331, 8.14612803567824, 9.0, 8.14612803567824, 8.60205999132796, 8.45, 8.55, 8.9, 8.2, 9.30102999566398, 8.39794000867204, 9.07918124604762, 8.60205999132796, 8.1, 8.25, 8.39794000867204, 8.45, 8.65321251377534, 7.95, 8.11394335230684, 8.39794000867204, 8.0, 8.20411998265593, 8.1, 9.11394335230684, 9.04139268515822, 9.47712125471966, 9.20411998265592, 8.60205999132796, 9.20411998265592, 8.79934054945358, 9.25527250510331, 8.15, 8.34242268082221, 9.0, 8.15, 8.3, 8.25, 7.9, 7.69897000433602, 8.35]]]
darr = [[[18.92, 18.88, 19.04, 18.98, 18.88, 18.96, 18.94, 18.9, 19.06, 19.0, 18.96, 19.06, 19.04, 19.04, 18.88, 18.9, 19.02, 18.98, 18.9, 19.0, 18.98, 18.88, 19.0, 18.88, 18.94, 18.98, 18.86, 19.02, 18.92, 18.94, 19.04, 18.98, 18.96, 19.04, 18.86, 18.98, 18.88, 18.98, 19.0, 19.0, 19.04, 18.98, 19.06, 18.94, 18.9, 19.0, 19.02, 19.02, 19.0, 19.02, 18.96, 18.98, 18.96, 18.96, 18.92, 18.94, 18.96, 19.06, 18.96, 19.04, 18.94, 19.06, 18.92, 18.9, 18.98, 18.88, 18.94, 19.04, 18.92, 18.88, 18.88, 18.9, 18.94, 18.88, 18.96, 18.96, 19.02, 18.88, 18.9, 18.9, 18.94, 19.04, 18.94, 18.9, 18.88, 18.88, 18.94, 18.96, 18.96], [18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9, 18.9]], [[18.42, 18.54, 18.44, 18.44, 18.56, 18.54, 18.48, 18.46, 18.48, 18.54, 18.56, 18.42, 18.42, 18.48, 18.44, 18.58, 18.48, 18.44, 18.52, 18.52, 18.58, 18.52, 18.42, 18.42, 18.54, 18.44, 18.48, 18.6, 18.44, 18.54, 18.48, 18.56, 18.52, 18.42, 18.44, 18.44, 18.48, 18.52, 18.48, 18.44, 18.56, 18.48, 18.5, 18.6, 18.56, 18.46, 18.42, 18.46, 18.48, 18.48, 18.58, 18.48, 18.6, 18.52, 18.44, 18.42, 18.6, 18.44, 18.58, 18.54, 18.52, 18.5, 18.58, 18.5, 18.5, 18.48, 18.5, 18.42, 18.52, 18.48, 18.56, 18.5, 18.52, 18.46, 18.52, 18.58, 18.52, 18.5, 18.5, 18.5, 18.42, 18.52, 18.5, 18.5, 18.52, 18.6, 18.6, 18.44, 18.5, 18.54, 18.5, 18.42, 18.52, 18.48, 18.6, 18.52, 18.5, 18.48, 18.44, 18.56, 18.56, 18.46, 18.54, 18.44, 18.5, 18.5, 18.54, 18.52, 18.44, 18.58, 18.5, 18.42, 18.54, 18.42, 18.44, 18.4, 18.44, 18.44, 18.48, 18.56, 18.6, 18.42, 18.42, 18.4, 18.58, 18.58, 18.48, 18.42, 18.54, 18.48, 18.5, 18.6, 18.58, 18.48, 18.5, 18.6, 18.5, 18.48, 18.42, 18.44, 18.4, 18.5, 18.56, 18.48, 18.5, 18.56, 18.44, 18.42, 18.48, 18.54], [18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, -9999999999.9, -9999999999.9, -9999999999.9, 18.5, 18.5, 18.5, -9999999999.9, 18.5, -9999999999.9, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, 18.5, 18.5, -9999999999.9, 18.5, -9999999999.9, -9999999999.9, -9999999999.9, 18.5, -9999999999.9, -9999999999.9, -9999999999.9, -9999999999.9, 18.5, 18.5, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, -9999999999.9, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5, 18.5]]]
dsigma = [[[0.05, 0.05, 0.06, 0.07, 0.03, 0.05, 0.06, 0.05, 0.05, 0.07, 0.06, 0.06, 0.05, 0.04, 0.06, 0.04, 0.05, 0.06, 0.07, 0.05, 0.05, 0.07, 0.07, 0.06, 0.06, 0.05, 0.07, 0.05, 0.05, 0.06, 0.04, 0.05, 0.06, 0.04, 0.06, 0.05, 0.05, 0.06, 0.04, 0.07, 0.05, 0.06, 0.04, 0.03, 0.06, 0.05, 0.04, 0.05, 0.05, 0.05, 0.06, 0.06, 0.04, 0.06, 0.05, 0.05, 0.06, 0.05, 0.03, 0.06, 0.04, 0.04, 0.06, 0.05, 0.05, 0.04, 0.05, 0.06, 0.04, 0.06, 0.05, 0.04, 0.04, 0.06, 0.04, 0.03, 0.07, 0.07, 0.06, 0.04, 0.06, 0.06, 0.05, 0.07, 0.06, 0.06, 0.03, 0.05, 0.06], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]], [[0.05, 0.05, 0.06, 0.05, 0.06, 0.07, 0.06, 0.04, 0.07, 0.05, 0.06, 0.04, 0.06, 0.05, 0.06, 0.06, 0.05, 0.06, 0.05, 0.06, 0.04, 0.05, 0.05, 0.06, 0.06, 0.05, 0.04, 0.05, 0.06, 0.06, 0.05, 0.03, 0.05, 0.06, 0.06, 0.03, 0.05, 0.06, 0.06, 0.06, 0.05, 0.04, 0.07, 0.04, 0.06, 0.03, 0.06, 0.06, 0.04, 0.06, 0.04, 0.05, 0.04, 0.06, 0.04, 0.06, 0.06, 0.03, 0.07, 0.07, 0.07, 0.05, 0.06, 0.03, 0.04, 0.06, 0.06, 0.06, 0.05, 0.06, 0.06, 0.06, 0.06, 0.04, 0.04, 0.06, 0.06, 0.06, 0.04, 0.06, 0.05, 0.05, 0.06, 0.05, 0.06, 0.06, 0.06, 0.05, 0.05, 0.07, 0.05, 0.07, 0.06, 0.05, 0.04, 0.07, 0.05, 0.07, 0.05, 0.06, 0.03, 0.05, 0.06, 0.05, 0.05, 0.06, 0.06, 0.07, 0.03, 0.04, 0.06, 0.05, 0.07, 0.06, 0.04, 0.05, 0.03, 0.04, 0.04, 0.07, 0.04, 0.07, 0.06, 0.02, 0.05, 0.06, 0.06, 0.04, 0.06, 0.04, 0.06, 0.06, 0.05, 0.04, 0.06, 0.05, 0.05, 0.02, 0.07, 0.05, 0.06, 0.06, 0.06, 0.06, 0.05, 0.05, 0.05, 0.04, 0.06, 0.03], [0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, -9999999999.9, -9999999999.9, -9999999999.9, 0.1, 0.1, 0.1, -9999999999.9, 0.1, -9999999999.9, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, 0.1, 0.1, -9999999999.9, 0.1, -9999999999.9, -9999999999.9, -9999999999.9, 0.1, -9999999999.9, -9999999999.9, -9999999999.9, -9999999999.9, 0.1, 0.1, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, -9999999999.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]]]
j = 1
inc_pa_fit_angles = [[Angle('40.d'), Angle('108.d')],
[Angle('18.336d'), Angle('153.06d')]]
glx_inc, glx_PA = inc_pa_fit_angles[j]
# Equatorial coordinates for clusters in this galaxy.
ra_g, dec_g = ra[j], dec[j]
# ASteCA distance moduli and their errors.
dm_g, e_dm_g = darr[j][0], dsigma[j][0]
# Retrieve center coordinates and distance (in parsecs) to galaxy.
gal_cent, gal_dist, e_dm_dist = MCs_data(j)
gal_dist = gal_dist.kpc * u.kpc
theta = glx_PA + Angle('90d')
plot_bulge_plane(ra_g, dec_g, dm_g, e_dm_g, gal_dist, gal_cent,
glx_inc, theta)
| gpl-3.0 |
piotroxp/scibibscan | scib/lib/python3.6/site-packages/pip/req/req_install.py | 335 | 46487 | from __future__ import absolute_import
import logging
import os
import re
import shutil
import sys
import tempfile
import traceback
import warnings
import zipfile
from distutils import sysconfig
from distutils.util import change_root
from email.parser import FeedParser
from pip._vendor import pkg_resources, six
from pip._vendor.packaging import specifiers
from pip._vendor.packaging.markers import Marker
from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.packaging.version import Version, parse as parse_version
from pip._vendor.six.moves import configparser
import pip.wheel
from pip.compat import native_str, get_stdlib, WINDOWS
from pip.download import is_url, url_to_path, path_to_url, is_archive_file
from pip.exceptions import (
InstallationError, UninstallationError,
)
from pip.locations import (
bin_py, running_under_virtualenv, PIP_DELETE_MARKER_FILENAME, bin_user,
)
from pip.utils import (
display_path, rmtree, ask_path_exists, backup_dir, is_installable_dir,
dist_in_usersite, dist_in_site_packages, egg_link_path,
call_subprocess, read_text_file, FakeFile, _make_build_dir, ensure_dir,
get_installed_version, normalize_path, dist_is_local,
)
from pip.utils.hashes import Hashes
from pip.utils.deprecation import RemovedInPip10Warning
from pip.utils.logging import indent_log
from pip.utils.setuptools_build import SETUPTOOLS_SHIM
from pip.utils.ui import open_spinner
from pip.req.req_uninstall import UninstallPathSet
from pip.vcs import vcs
from pip.wheel import move_wheel_files, Wheel
logger = logging.getLogger(__name__)
operators = specifiers.Specifier._operators.keys()
def _strip_extras(path):
m = re.match(r'^(.+)(\[[^\]]+\])$', path)
extras = None
if m:
path_no_extras = m.group(1)
extras = m.group(2)
else:
path_no_extras = path
return path_no_extras, extras
def _safe_extras(extras):
return set(pkg_resources.safe_extra(extra) for extra in extras)
class InstallRequirement(object):
def __init__(self, req, comes_from, source_dir=None, editable=False,
link=None, as_egg=False, update=True,
pycompile=True, markers=None, isolated=False, options=None,
wheel_cache=None, constraint=False):
self.extras = ()
if isinstance(req, six.string_types):
try:
req = Requirement(req)
except InvalidRequirement:
if os.path.sep in req:
add_msg = "It looks like a path. Does it exist ?"
elif '=' in req and not any(op in req for op in operators):
add_msg = "= is not a valid operator. Did you mean == ?"
else:
add_msg = traceback.format_exc()
raise InstallationError(
"Invalid requirement: '%s'\n%s" % (req, add_msg))
self.extras = _safe_extras(req.extras)
self.req = req
self.comes_from = comes_from
self.constraint = constraint
self.source_dir = source_dir
self.editable = editable
self._wheel_cache = wheel_cache
self.link = self.original_link = link
self.as_egg = as_egg
if markers is not None:
self.markers = markers
else:
self.markers = req and req.marker
self._egg_info_path = None
# This holds the pkg_resources.Distribution object if this requirement
# is already available:
self.satisfied_by = None
# This hold the pkg_resources.Distribution object if this requirement
# conflicts with another installed distribution:
self.conflicts_with = None
# Temporary build location
self._temp_build_dir = None
# Used to store the global directory where the _temp_build_dir should
# have been created. Cf _correct_build_location method.
self._ideal_build_dir = None
# True if the editable should be updated:
self.update = update
# Set to True after successful installation
self.install_succeeded = None
# UninstallPathSet of uninstalled distribution (for possible rollback)
self.uninstalled = None
# Set True if a legitimate do-nothing-on-uninstall has happened - e.g.
# system site packages, stdlib packages.
self.nothing_to_uninstall = False
self.use_user_site = False
self.target_dir = None
self.options = options if options else {}
self.pycompile = pycompile
# Set to True after successful preparation of this requirement
self.prepared = False
self.isolated = isolated
@classmethod
def from_editable(cls, editable_req, comes_from=None, default_vcs=None,
isolated=False, options=None, wheel_cache=None,
constraint=False):
from pip.index import Link
name, url, extras_override = parse_editable(
editable_req, default_vcs)
if url.startswith('file:'):
source_dir = url_to_path(url)
else:
source_dir = None
res = cls(name, comes_from, source_dir=source_dir,
editable=True,
link=Link(url),
constraint=constraint,
isolated=isolated,
options=options if options else {},
wheel_cache=wheel_cache)
if extras_override is not None:
res.extras = _safe_extras(extras_override)
return res
@classmethod
def from_line(
cls, name, comes_from=None, isolated=False, options=None,
wheel_cache=None, constraint=False):
"""Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
"""
from pip.index import Link
if is_url(name):
marker_sep = '; '
else:
marker_sep = ';'
if marker_sep in name:
name, markers = name.split(marker_sep, 1)
markers = markers.strip()
if not markers:
markers = None
else:
markers = Marker(markers)
else:
markers = None
name = name.strip()
req = None
path = os.path.normpath(os.path.abspath(name))
link = None
extras = None
if is_url(name):
link = Link(name)
else:
p, extras = _strip_extras(path)
if (os.path.isdir(p) and
(os.path.sep in name or name.startswith('.'))):
if not is_installable_dir(p):
raise InstallationError(
"Directory %r is not installable. File 'setup.py' "
"not found." % name
)
link = Link(path_to_url(p))
elif is_archive_file(p):
if not os.path.isfile(p):
logger.warning(
'Requirement %r looks like a filename, but the '
'file does not exist',
name
)
link = Link(path_to_url(p))
# it's a local file, dir, or url
if link:
# Handle relative file URLs
if link.scheme == 'file' and re.search(r'\.\./', link.url):
link = Link(
path_to_url(os.path.normpath(os.path.abspath(link.path))))
# wheel file
if link.is_wheel:
wheel = Wheel(link.filename) # can raise InvalidWheelFilename
req = "%s==%s" % (wheel.name, wheel.version)
else:
# set the req to the egg fragment. when it's not there, this
# will become an 'unnamed' requirement
req = link.egg_fragment
# a requirement specifier
else:
req = name
options = options if options else {}
res = cls(req, comes_from, link=link, markers=markers,
isolated=isolated, options=options,
wheel_cache=wheel_cache, constraint=constraint)
if extras:
res.extras = _safe_extras(
Requirement('placeholder' + extras).extras)
return res
def __str__(self):
if self.req:
s = str(self.req)
if self.link:
s += ' from %s' % self.link.url
else:
s = self.link.url if self.link else None
if self.satisfied_by is not None:
s += ' in %s' % display_path(self.satisfied_by.location)
if self.comes_from:
if isinstance(self.comes_from, six.string_types):
comes_from = self.comes_from
else:
comes_from = self.comes_from.from_path()
if comes_from:
s += ' (from %s)' % comes_from
return s
def __repr__(self):
return '<%s object: %s editable=%r>' % (
self.__class__.__name__, str(self), self.editable)
def populate_link(self, finder, upgrade, require_hashes):
"""Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times.
"""
if self.link is None:
self.link = finder.find_requirement(self, upgrade)
if self._wheel_cache is not None and not require_hashes:
old_link = self.link
self.link = self._wheel_cache.cached_wheel(self.link, self.name)
if old_link != self.link:
logger.debug('Using cached wheel link: %s', self.link)
@property
def specifier(self):
return self.req.specifier
@property
def is_pinned(self):
"""Return whether I am pinned to an exact version.
For example, some-package==1.2 is pinned; some-package>1.2 is not.
"""
specifiers = self.specifier
return (len(specifiers) == 1 and
next(iter(specifiers)).operator in ('==', '==='))
def from_path(self):
if self.req is None:
return None
s = str(self.req)
if self.comes_from:
if isinstance(self.comes_from, six.string_types):
comes_from = self.comes_from
else:
comes_from = self.comes_from.from_path()
if comes_from:
s += '->' + comes_from
return s
def build_location(self, build_dir):
if self._temp_build_dir is not None:
return self._temp_build_dir
if self.req is None:
# for requirement via a path to a directory: the name of the
# package is not available yet so we create a temp directory
# Once run_egg_info will have run, we'll be able
# to fix it via _correct_build_location
# Some systems have /tmp as a symlink which confuses custom
# builds (such as numpy). Thus, we ensure that the real path
# is returned.
self._temp_build_dir = os.path.realpath(
tempfile.mkdtemp('-build', 'pip-')
)
self._ideal_build_dir = build_dir
return self._temp_build_dir
if self.editable:
name = self.name.lower()
else:
name = self.name
# FIXME: Is there a better place to create the build_dir? (hg and bzr
# need this)
if not os.path.exists(build_dir):
logger.debug('Creating directory %s', build_dir)
_make_build_dir(build_dir)
return os.path.join(build_dir, name)
def _correct_build_location(self):
"""Move self._temp_build_dir to self._ideal_build_dir/self.req.name
For some requirements (e.g. a path to a directory), the name of the
package is not available until we run egg_info, so the build_location
will return a temporary directory and store the _ideal_build_dir.
This is only called by self.egg_info_path to fix the temporary build
directory.
"""
if self.source_dir is not None:
return
assert self.req is not None
assert self._temp_build_dir
assert self._ideal_build_dir
old_location = self._temp_build_dir
self._temp_build_dir = None
new_location = self.build_location(self._ideal_build_dir)
if os.path.exists(new_location):
raise InstallationError(
'A package already exists in %s; please remove it to continue'
% display_path(new_location))
logger.debug(
'Moving package %s from %s to new location %s',
self, display_path(old_location), display_path(new_location),
)
shutil.move(old_location, new_location)
self._temp_build_dir = new_location
self._ideal_build_dir = None
self.source_dir = new_location
self._egg_info_path = None
@property
def name(self):
if self.req is None:
return None
return native_str(pkg_resources.safe_name(self.req.name))
@property
def setup_py_dir(self):
return os.path.join(
self.source_dir,
self.link and self.link.subdirectory_fragment or '')
@property
def setup_py(self):
assert self.source_dir, "No source dir for %s" % self
try:
import setuptools # noqa
except ImportError:
if get_installed_version('setuptools') is None:
add_msg = "Please install setuptools."
else:
add_msg = traceback.format_exc()
# Setuptools is not available
raise InstallationError(
"Could not import setuptools which is required to "
"install from a source distribution.\n%s" % add_msg
)
setup_py = os.path.join(self.setup_py_dir, 'setup.py')
# Python2 __file__ should not be unicode
if six.PY2 and isinstance(setup_py, six.text_type):
setup_py = setup_py.encode(sys.getfilesystemencoding())
return setup_py
def run_egg_info(self):
assert self.source_dir
if self.name:
logger.debug(
'Running setup.py (path:%s) egg_info for package %s',
self.setup_py, self.name,
)
else:
logger.debug(
'Running setup.py (path:%s) egg_info for package from %s',
self.setup_py, self.link,
)
with indent_log():
script = SETUPTOOLS_SHIM % self.setup_py
base_cmd = [sys.executable, '-c', script]
if self.isolated:
base_cmd += ["--no-user-cfg"]
egg_info_cmd = base_cmd + ['egg_info']
# We can't put the .egg-info files at the root, because then the
# source code will be mistaken for an installed egg, causing
# problems
if self.editable:
egg_base_option = []
else:
egg_info_dir = os.path.join(self.setup_py_dir, 'pip-egg-info')
ensure_dir(egg_info_dir)
egg_base_option = ['--egg-base', 'pip-egg-info']
call_subprocess(
egg_info_cmd + egg_base_option,
cwd=self.setup_py_dir,
show_stdout=False,
command_desc='python setup.py egg_info')
if not self.req:
if isinstance(parse_version(self.pkg_info()["Version"]), Version):
op = "=="
else:
op = "==="
self.req = Requirement(
"".join([
self.pkg_info()["Name"],
op,
self.pkg_info()["Version"],
])
)
self._correct_build_location()
else:
metadata_name = canonicalize_name(self.pkg_info()["Name"])
if canonicalize_name(self.req.name) != metadata_name:
logger.warning(
'Running setup.py (path:%s) egg_info for package %s '
'produced metadata for project name %s. Fix your '
'#egg=%s fragments.',
self.setup_py, self.name, metadata_name, self.name
)
self.req = Requirement(metadata_name)
def egg_info_data(self, filename):
if self.satisfied_by is not None:
if not self.satisfied_by.has_metadata(filename):
return None
return self.satisfied_by.get_metadata(filename)
assert self.source_dir
filename = self.egg_info_path(filename)
if not os.path.exists(filename):
return None
data = read_text_file(filename)
return data
def egg_info_path(self, filename):
if self._egg_info_path is None:
if self.editable:
base = self.source_dir
else:
base = os.path.join(self.setup_py_dir, 'pip-egg-info')
filenames = os.listdir(base)
if self.editable:
filenames = []
for root, dirs, files in os.walk(base):
for dir in vcs.dirnames:
if dir in dirs:
dirs.remove(dir)
# Iterate over a copy of ``dirs``, since mutating
# a list while iterating over it can cause trouble.
# (See https://github.com/pypa/pip/pull/462.)
for dir in list(dirs):
# Don't search in anything that looks like a virtualenv
# environment
if (
os.path.lexists(
os.path.join(root, dir, 'bin', 'python')
) or
os.path.exists(
os.path.join(
root, dir, 'Scripts', 'Python.exe'
)
)):
dirs.remove(dir)
# Also don't search through tests
elif dir == 'test' or dir == 'tests':
dirs.remove(dir)
filenames.extend([os.path.join(root, dir)
for dir in dirs])
filenames = [f for f in filenames if f.endswith('.egg-info')]
if not filenames:
raise InstallationError(
'No files/directories in %s (from %s)' % (base, filename)
)
assert filenames, \
"No files/directories in %s (from %s)" % (base, filename)
# if we have more than one match, we pick the toplevel one. This
# can easily be the case if there is a dist folder which contains
# an extracted tarball for testing purposes.
if len(filenames) > 1:
filenames.sort(
key=lambda x: x.count(os.path.sep) +
(os.path.altsep and x.count(os.path.altsep) or 0)
)
self._egg_info_path = os.path.join(base, filenames[0])
return os.path.join(self._egg_info_path, filename)
def pkg_info(self):
p = FeedParser()
data = self.egg_info_data('PKG-INFO')
if not data:
logger.warning(
'No PKG-INFO file found in %s',
display_path(self.egg_info_path('PKG-INFO')),
)
p.feed(data or '')
return p.close()
_requirements_section_re = re.compile(r'\[(.*?)\]')
@property
def installed_version(self):
return get_installed_version(self.name)
def assert_source_matches_version(self):
assert self.source_dir
version = self.pkg_info()['version']
if self.req.specifier and version not in self.req.specifier:
logger.warning(
'Requested %s, but installing version %s',
self,
self.installed_version,
)
else:
logger.debug(
'Source in %s has version %s, which satisfies requirement %s',
display_path(self.source_dir),
version,
self,
)
def update_editable(self, obtain=True):
if not self.link:
logger.debug(
"Cannot update repository at %s; repository location is "
"unknown",
self.source_dir,
)
return
assert self.editable
assert self.source_dir
if self.link.scheme == 'file':
# Static paths don't get updated
return
assert '+' in self.link.url, "bad url: %r" % self.link.url
if not self.update:
return
vc_type, url = self.link.url.split('+', 1)
backend = vcs.get_backend(vc_type)
if backend:
vcs_backend = backend(self.link.url)
if obtain:
vcs_backend.obtain(self.source_dir)
else:
vcs_backend.export(self.source_dir)
else:
assert 0, (
'Unexpected version control type (in %s): %s'
% (self.link, vc_type))
def uninstall(self, auto_confirm=False):
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages.
"""
if not self.check_if_exists():
raise UninstallationError(
"Cannot uninstall requirement %s, not installed" % (self.name,)
)
dist = self.satisfied_by or self.conflicts_with
dist_path = normalize_path(dist.location)
if not dist_is_local(dist):
logger.info(
"Not uninstalling %s at %s, outside environment %s",
dist.key,
dist_path,
sys.prefix,
)
self.nothing_to_uninstall = True
return
if dist_path in get_stdlib():
logger.info(
"Not uninstalling %s at %s, as it is in the standard library.",
dist.key,
dist_path,
)
self.nothing_to_uninstall = True
return
paths_to_remove = UninstallPathSet(dist)
develop_egg_link = egg_link_path(dist)
develop_egg_link_egg_info = '{0}.egg-info'.format(
pkg_resources.to_filename(dist.project_name))
egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info)
# Special case for distutils installed package
distutils_egg_info = getattr(dist._provider, 'path', None)
# Uninstall cases order do matter as in the case of 2 installs of the
# same package, pip needs to uninstall the currently detected version
if (egg_info_exists and dist.egg_info.endswith('.egg-info') and
not dist.egg_info.endswith(develop_egg_link_egg_info)):
# if dist.egg_info.endswith(develop_egg_link_egg_info), we
# are in fact in the develop_egg_link case
paths_to_remove.add(dist.egg_info)
if dist.has_metadata('installed-files.txt'):
for installed_file in dist.get_metadata(
'installed-files.txt').splitlines():
path = os.path.normpath(
os.path.join(dist.egg_info, installed_file)
)
paths_to_remove.add(path)
# FIXME: need a test for this elif block
# occurs with --single-version-externally-managed/--record outside
# of pip
elif dist.has_metadata('top_level.txt'):
if dist.has_metadata('namespace_packages.txt'):
namespaces = dist.get_metadata('namespace_packages.txt')
else:
namespaces = []
for top_level_pkg in [
p for p
in dist.get_metadata('top_level.txt').splitlines()
if p and p not in namespaces]:
path = os.path.join(dist.location, top_level_pkg)
paths_to_remove.add(path)
paths_to_remove.add(path + '.py')
paths_to_remove.add(path + '.pyc')
paths_to_remove.add(path + '.pyo')
elif distutils_egg_info:
warnings.warn(
"Uninstalling a distutils installed project ({0}) has been "
"deprecated and will be removed in a future version. This is "
"due to the fact that uninstalling a distutils project will "
"only partially uninstall the project.".format(self.name),
RemovedInPip10Warning,
)
paths_to_remove.add(distutils_egg_info)
elif dist.location.endswith('.egg'):
# package installed by easy_install
# We cannot match on dist.egg_name because it can slightly vary
# i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
paths_to_remove.add(dist.location)
easy_install_egg = os.path.split(dist.location)[1]
easy_install_pth = os.path.join(os.path.dirname(dist.location),
'easy-install.pth')
paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg)
elif egg_info_exists and dist.egg_info.endswith('.dist-info'):
for path in pip.wheel.uninstallation_paths(dist):
paths_to_remove.add(path)
elif develop_egg_link:
# develop egg
with open(develop_egg_link, 'r') as fh:
link_pointer = os.path.normcase(fh.readline().strip())
assert (link_pointer == dist.location), (
'Egg-link %s does not match installed location of %s '
'(at %s)' % (link_pointer, self.name, dist.location)
)
paths_to_remove.add(develop_egg_link)
easy_install_pth = os.path.join(os.path.dirname(develop_egg_link),
'easy-install.pth')
paths_to_remove.add_pth(easy_install_pth, dist.location)
else:
logger.debug(
'Not sure how to uninstall: %s - Check: %s',
dist, dist.location)
# find distutils scripts= scripts
if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'):
for script in dist.metadata_listdir('scripts'):
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
paths_to_remove.add(os.path.join(bin_dir, script))
if WINDOWS:
paths_to_remove.add(os.path.join(bin_dir, script) + '.bat')
# find console_scripts
if dist.has_metadata('entry_points.txt'):
if six.PY2:
options = {}
else:
options = {"delimiters": ('=', )}
config = configparser.SafeConfigParser(**options)
config.readfp(
FakeFile(dist.get_metadata_lines('entry_points.txt'))
)
if config.has_section('console_scripts'):
for name, value in config.items('console_scripts'):
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
paths_to_remove.add(os.path.join(bin_dir, name))
if WINDOWS:
paths_to_remove.add(
os.path.join(bin_dir, name) + '.exe'
)
paths_to_remove.add(
os.path.join(bin_dir, name) + '.exe.manifest'
)
paths_to_remove.add(
os.path.join(bin_dir, name) + '-script.py'
)
paths_to_remove.remove(auto_confirm)
self.uninstalled = paths_to_remove
def rollback_uninstall(self):
if self.uninstalled:
self.uninstalled.rollback()
else:
logger.error(
"Can't rollback %s, nothing uninstalled.", self.name,
)
def commit_uninstall(self):
if self.uninstalled:
self.uninstalled.commit()
elif not self.nothing_to_uninstall:
logger.error(
"Can't commit %s, nothing uninstalled.", self.name,
)
def archive(self, build_dir):
assert self.source_dir
create_archive = True
archive_name = '%s-%s.zip' % (self.name, self.pkg_info()["version"])
archive_path = os.path.join(build_dir, archive_name)
if os.path.exists(archive_path):
response = ask_path_exists(
'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)bort ' %
display_path(archive_path), ('i', 'w', 'b', 'a'))
if response == 'i':
create_archive = False
elif response == 'w':
logger.warning('Deleting %s', display_path(archive_path))
os.remove(archive_path)
elif response == 'b':
dest_file = backup_dir(archive_path)
logger.warning(
'Backing up %s to %s',
display_path(archive_path),
display_path(dest_file),
)
shutil.move(archive_path, dest_file)
elif response == 'a':
sys.exit(-1)
if create_archive:
zip = zipfile.ZipFile(
archive_path, 'w', zipfile.ZIP_DEFLATED,
allowZip64=True
)
dir = os.path.normcase(os.path.abspath(self.setup_py_dir))
for dirpath, dirnames, filenames in os.walk(dir):
if 'pip-egg-info' in dirnames:
dirnames.remove('pip-egg-info')
for dirname in dirnames:
dirname = os.path.join(dirpath, dirname)
name = self._clean_zip_name(dirname, dir)
zipdir = zipfile.ZipInfo(self.name + '/' + name + '/')
zipdir.external_attr = 0x1ED << 16 # 0o755
zip.writestr(zipdir, '')
for filename in filenames:
if filename == PIP_DELETE_MARKER_FILENAME:
continue
filename = os.path.join(dirpath, filename)
name = self._clean_zip_name(filename, dir)
zip.write(filename, self.name + '/' + name)
zip.close()
logger.info('Saved %s', display_path(archive_path))
def _clean_zip_name(self, name, prefix):
assert name.startswith(prefix + os.path.sep), (
"name %r doesn't start with prefix %r" % (name, prefix)
)
name = name[len(prefix) + 1:]
name = name.replace(os.path.sep, '/')
return name
def match_markers(self, extras_requested=None):
if not extras_requested:
# Provide an extra to safely evaluate the markers
# without matching any extra
extras_requested = ('',)
if self.markers is not None:
return any(
self.markers.evaluate({'extra': extra})
for extra in extras_requested)
else:
return True
def install(self, install_options, global_options=[], root=None,
prefix=None):
if self.editable:
self.install_editable(
install_options, global_options, prefix=prefix)
return
if self.is_wheel:
version = pip.wheel.wheel_version(self.source_dir)
pip.wheel.check_compatibility(version, self.name)
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
self.install_succeeded = True
return
# Extend the list of global and install options passed on to
# the setup.py call with the ones from the requirements file.
# Options specified in requirements file override those
# specified on the command line, since the last option given
# to setup.py is the one that is used.
global_options += self.options.get('global_options', [])
install_options += self.options.get('install_options', [])
if self.isolated:
global_options = list(global_options) + ["--no-user-cfg"]
temp_location = tempfile.mkdtemp('-record', 'pip-')
record_filename = os.path.join(temp_location, 'install-record.txt')
try:
install_args = self.get_install_args(
global_options, record_filename, root, prefix)
msg = 'Running setup.py install for %s' % (self.name,)
with open_spinner(msg) as spinner:
with indent_log():
call_subprocess(
install_args + install_options,
cwd=self.setup_py_dir,
show_stdout=False,
spinner=spinner,
)
if not os.path.exists(record_filename):
logger.debug('Record file %s not found', record_filename)
return
self.install_succeeded = True
if self.as_egg:
# there's no --always-unzip option we can pass to install
# command so we unable to save the installed-files.txt
return
def prepend_root(path):
if root is None or not os.path.isabs(path):
return path
else:
return change_root(root, path)
with open(record_filename) as f:
for line in f:
directory = os.path.dirname(line)
if directory.endswith('.egg-info'):
egg_info_dir = prepend_root(directory)
break
else:
logger.warning(
'Could not find .egg-info directory in install record'
' for %s',
self,
)
# FIXME: put the record somewhere
# FIXME: should this be an error?
return
new_lines = []
with open(record_filename) as f:
for line in f:
filename = line.strip()
if os.path.isdir(filename):
filename += os.path.sep
new_lines.append(
os.path.relpath(
prepend_root(filename), egg_info_dir)
)
inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt')
with open(inst_files_path, 'w') as f:
f.write('\n'.join(new_lines) + '\n')
finally:
if os.path.exists(record_filename):
os.remove(record_filename)
rmtree(temp_location)
def ensure_has_source_dir(self, parent_dir):
"""Ensure that a source_dir is set.
This will create a temporary build dir if the name of the requirement
isn't known yet.
:param parent_dir: The ideal pip parent_dir for the source_dir.
Generally src_dir for editables and build_dir for sdists.
:return: self.source_dir
"""
if self.source_dir is None:
self.source_dir = self.build_location(parent_dir)
return self.source_dir
def get_install_args(self, global_options, record_filename, root, prefix):
install_args = [sys.executable, "-u"]
install_args.append('-c')
install_args.append(SETUPTOOLS_SHIM % self.setup_py)
install_args += list(global_options) + \
['install', '--record', record_filename]
if not self.as_egg:
install_args += ['--single-version-externally-managed']
if root is not None:
install_args += ['--root', root]
if prefix is not None:
install_args += ['--prefix', prefix]
if self.pycompile:
install_args += ["--compile"]
else:
install_args += ["--no-compile"]
if running_under_virtualenv():
py_ver_str = 'python' + sysconfig.get_python_version()
install_args += ['--install-headers',
os.path.join(sys.prefix, 'include', 'site',
py_ver_str, self.name)]
return install_args
def remove_temporary_source(self):
"""Remove the source files from this requirement, if they are marked
for deletion"""
if self.source_dir and os.path.exists(
os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
logger.debug('Removing source in %s', self.source_dir)
rmtree(self.source_dir)
self.source_dir = None
if self._temp_build_dir and os.path.exists(self._temp_build_dir):
rmtree(self._temp_build_dir)
self._temp_build_dir = None
def install_editable(self, install_options,
global_options=(), prefix=None):
logger.info('Running setup.py develop for %s', self.name)
if self.isolated:
global_options = list(global_options) + ["--no-user-cfg"]
if prefix:
prefix_param = ['--prefix={0}'.format(prefix)]
install_options = list(install_options) + prefix_param
with indent_log():
# FIXME: should we do --install-headers here too?
call_subprocess(
[
sys.executable,
'-c',
SETUPTOOLS_SHIM % self.setup_py
] +
list(global_options) +
['develop', '--no-deps'] +
list(install_options),
cwd=self.setup_py_dir,
show_stdout=False)
self.install_succeeded = True
def check_if_exists(self):
"""Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately.
"""
if self.req is None:
return False
try:
# get_distribution() will resolve the entire list of requirements
# anyway, and we've already determined that we need the requirement
# in question, so strip the marker so that we don't try to
# evaluate it.
no_marker = Requirement(str(self.req))
no_marker.marker = None
self.satisfied_by = pkg_resources.get_distribution(str(no_marker))
if self.editable and self.satisfied_by:
self.conflicts_with = self.satisfied_by
# when installing editables, nothing pre-existing should ever
# satisfy
self.satisfied_by = None
return True
except pkg_resources.DistributionNotFound:
return False
except pkg_resources.VersionConflict:
existing_dist = pkg_resources.get_distribution(
self.req.name
)
if self.use_user_site:
if dist_in_usersite(existing_dist):
self.conflicts_with = existing_dist
elif (running_under_virtualenv() and
dist_in_site_packages(existing_dist)):
raise InstallationError(
"Will not install to the user site because it will "
"lack sys.path precedence to %s in %s" %
(existing_dist.project_name, existing_dist.location)
)
else:
self.conflicts_with = existing_dist
return True
@property
def is_wheel(self):
return self.link and self.link.is_wheel
def move_wheel_files(self, wheeldir, root=None, prefix=None):
move_wheel_files(
self.name, self.req, wheeldir,
user=self.use_user_site,
home=self.target_dir,
root=root,
prefix=prefix,
pycompile=self.pycompile,
isolated=self.isolated,
)
def get_dist(self):
"""Return a pkg_resources.Distribution built from self.egg_info_path"""
egg_info = self.egg_info_path('').rstrip('/')
base_dir = os.path.dirname(egg_info)
metadata = pkg_resources.PathMetadata(base_dir, egg_info)
dist_name = os.path.splitext(os.path.basename(egg_info))[0]
return pkg_resources.Distribution(
os.path.dirname(egg_info),
project_name=dist_name,
metadata=metadata)
@property
def has_hash_options(self):
"""Return whether any known-good hashes are specified as options.
These activate --require-hashes mode; hashes specified as part of a
URL do not.
"""
return bool(self.options.get('hashes', {}))
def hashes(self, trust_internet=True):
"""Return a hash-comparer that considers my option- and URL-based
hashes to be known-good.
Hashes in URLs--ones embedded in the requirements file, not ones
downloaded from an index server--are almost peers with ones from
flags. They satisfy --require-hashes (whether it was implicitly or
explicitly activated) but do not activate it. md5 and sha224 are not
allowed in flags, which should nudge people toward good algos. We
always OR all hashes together, even ones from URLs.
:param trust_internet: Whether to trust URL-based (#md5=...) hashes
downloaded from the internet, as by populate_link()
"""
good_hashes = self.options.get('hashes', {}).copy()
link = self.link if trust_internet else self.original_link
if link and link.hash:
good_hashes.setdefault(link.hash_name, []).append(link.hash)
return Hashes(good_hashes)
def _strip_postfix(req):
"""
Strip req postfix ( -dev, 0.2, etc )
"""
# FIXME: use package_to_requirement?
match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req)
if match:
# Strip off -dev, -0.2, etc.
req = match.group(1)
return req
def parse_editable(editable_req, default_vcs=None):
"""Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
"""
from pip.index import Link
url = editable_req
extras = None
# If a file path is specified with extras, strip off the extras.
m = re.match(r'^(.+)(\[[^\]]+\])$', url)
if m:
url_no_extras = m.group(1)
extras = m.group(2)
else:
url_no_extras = url
if os.path.isdir(url_no_extras):
if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
raise InstallationError(
"Directory %r is not installable. File 'setup.py' not found." %
url_no_extras
)
# Treating it as code that has already been checked out
url_no_extras = path_to_url(url_no_extras)
if url_no_extras.lower().startswith('file:'):
package_name = Link(url_no_extras).egg_fragment
if extras:
return (
package_name,
url_no_extras,
Requirement("placeholder" + extras.lower()).extras,
)
else:
return package_name, url_no_extras, None
for version_control in vcs:
if url.lower().startswith('%s:' % version_control):
url = '%s+%s' % (version_control, url)
break
if '+' not in url:
if default_vcs:
warnings.warn(
"--default-vcs has been deprecated and will be removed in "
"the future.",
RemovedInPip10Warning,
)
url = default_vcs + '+' + url
else:
raise InstallationError(
'%s should either be a path to a local project or a VCS url '
'beginning with svn+, git+, hg+, or bzr+' %
editable_req
)
vc_type = url.split('+', 1)[0].lower()
if not vcs.get_backend(vc_type):
error_message = 'For --editable=%s only ' % editable_req + \
', '.join([backend.name + '+URL' for backend in vcs.backends]) + \
' is currently supported'
raise InstallationError(error_message)
package_name = Link(url).egg_fragment
if not package_name:
raise InstallationError(
"Could not detect requirement name, please specify one with #egg="
)
if not package_name:
raise InstallationError(
'--editable=%s is not the right format; it must have '
'#egg=Package' % editable_req
)
return _strip_postfix(package_name), url, None
| mit |
jmouriz/sanaviron | sanaviron/objects/charts/bar.py | 3 | 8480 | # Copyright(c) 2007-2009 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of PyCha.
#
# PyCha is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyCha 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PyCha. If not, see <http://www.gnu.org/licenses/>.
from objects.charts.chart import Chart, uniqueIndices
from objects.charts.color import hex2rgb
class BarChart(Chart):
def __init__(self, surface=None, options={}):
super(BarChart, self).__init__(surface, options)
self.bars = []
self.minxdelta = 0.0
self.barWidthForSet = 0.0
self.barMargin = 0.0
def _updateXY(self):
super(BarChart, self)._updateXY()
# each dataset is centered around a line segment. that's why we
# need n + 1 divisions on the x axis
self.xscale = 1 / (self.xrange + 1.0)
def _updateChart(self):
"""Evaluates measures for vertical bars"""
stores = self._getDatasetsValues()
uniqx = uniqueIndices(stores)
if len(uniqx) == 1:
self.minxdelta = 1.0
else:
self.minxdelta = min([abs(uniqx[j] - uniqx[j - 1])
for j in range(1, len(uniqx))])
k = self.minxdelta * self.xscale
barWidth = k * self.options.barWidthFillFraction
self.barWidthForSet = barWidth / len(stores)
self.barMargin = k * (1.0 - self.options.barWidthFillFraction) / 2
self.bars = []
def _renderChart(self, cx):
"""Renders a horizontal/vertical bar chart"""
def drawBar(bar):
stroke_width = self.options.stroke.width
ux, uy = cx.device_to_user_distance(stroke_width, stroke_width)
if ux < uy:
ux = uy
cx.set_line_width(ux)
# gather bar proportions
x = self.area.x + self.area.w * bar.x
y = self.area.y + self.area.h * bar.y
w = self.area.w * bar.w
h = self.area.h * bar.h
if w < 1 or h < 1:
return # don't draw when the bar is too small
if self.options.stroke.shadow:
cx.set_source_rgba(0, 0, 0, 0.15)
rectangle = self._getShadowRectangle(x, y, w, h)
cx.rectangle(*rectangle)
cx.fill()
if self.options.shouldFill or (not self.options.stroke.hide):
if self.options.shouldFill:
cx.set_source_rgb(*self.colorScheme[bar.name])
cx.rectangle(x, y, w, h)
cx.fill()
if not self.options.stroke.hide:
cx.set_source_rgb(*hex2rgb(self.options.stroke.color))
cx.rectangle(x, y, w, h)
cx.stroke()
# render yvals above/beside bars
if self.options.yvals.show:
cx.save()
cx.set_font_size(self.options.yvals.fontSize)
cx.set_source_rgb(*hex2rgb(self.options.yvals.fontColor))
label = unicode(bar.yval)
extents = cx.text_extents(label)
labelW = extents[2]
labelH = extents[3]
self._renderYVal(cx, label, labelW, labelH, x, y, w, h)
cx.restore()
cx.save()
for bar in self.bars:
drawBar(bar)
cx.restore()
def _renderYVal(self, cx, label, width, height, x, y, w, h):
raise NotImplementedError
class VerticalBarChart(BarChart):
def _updateChart(self):
"""Evaluates measures for vertical bars"""
super(VerticalBarChart, self)._updateChart()
for i, (name, store) in enumerate(self.datasets):
for item in store:
xval, yval = item
x = (((xval - self.minxval) * self.xscale)
+ self.barMargin + (i * self.barWidthForSet))
w = self.barWidthForSet
h = abs(yval) * self.yscale
if yval > 0:
y = (1.0 - h) - self.area.origin
else:
y = 1 - self.area.origin
rect = Rect(x, y, w, h, xval, yval, name)
if (0.0 <= rect.x <= 1.0) and (0.0 <= rect.y <= 1.0):
self.bars.append(rect)
def _updateTicks(self):
"""Evaluates bar ticks"""
super(BarChart, self)._updateTicks()
offset = (self.minxdelta * self.xscale) / 2
self.xticks = [(tick[0] + offset, tick[1]) for tick in self.xticks]
def _getShadowRectangle(self, x, y, w, h):
return (x - 2, y - 2, w + 4, h + 2)
def _renderYVal(self, cx, label, labelW, labelH, barX, barY, barW, barH):
x = barX + (barW / 2.0) - (labelW / 2.0)
if self.options.yvals.inside:
y = barY + (1.5 * labelH)
else:
y = barY - 0.5 * labelH
# if the label doesn't fit below the bar, put it above the bar
if y > (barY + barH):
y = barY - 0.5 * labelH
cx.move_to(x, y)
cx.show_text(label)
class HorizontalBarChart(BarChart):
def _updateChart(self):
"""Evaluates measures for horizontal bars"""
super(HorizontalBarChart, self)._updateChart()
for i, (name, store) in enumerate(self.datasets):
for item in store:
xval, yval = item
y = (((xval - self.minxval) * self.xscale)
+ self.barMargin + (i * self.barWidthForSet))
h = self.barWidthForSet
w = abs(yval) * self.yscale
if yval > 0:
x = self.area.origin
else:
x = self.area.origin - w
rect = Rect(x, y, w, h, xval, yval, name)
if (0.0 <= rect.x <= 1.0) and (0.0 <= rect.y <= 1.0):
self.bars.append(rect)
def _updateTicks(self):
"""Evaluates bar ticks"""
super(BarChart, self)._updateTicks()
offset = (self.minxdelta * self.xscale) / 2
tmp = self.xticks
self.xticks = [(1.0 - tick[0], tick[1]) for tick in self.yticks]
self.yticks = [(tick[0] + offset, tick[1]) for tick in tmp]
def _renderLines(self, cx):
"""Aux function for _renderBackground"""
ticks = self.xticks
for tick in ticks:
self._renderLine(cx, tick, True)
def _getShadowRectangle(self, x, y, w, h):
return (x, y - 2, w + 2, h + 4)
def _renderXAxis(self, cx):
"""Draws the horizontal line representing the X axis"""
cx.new_path()
cx.move_to(self.area.x, self.area.y + self.area.h)
cx.line_to(self.area.x + self.area.w, self.area.y + self.area.h)
cx.close_path()
cx.stroke()
def _renderYAxis(self, cx):
# draws the vertical line representing the Y axis
cx.new_path()
cx.move_to(self.area.x + self.area.origin * self.area.w,
self.area.y)
cx.line_to(self.area.x + self.area.origin * self.area.w,
self.area.y + self.area.h)
cx.close_path()
cx.stroke()
def _renderYVal(self, cx, label, labelW, labelH, barX, barY, barW, barH):
y = barY + (barH / 2.0) + (labelH / 2.0)
if self.options.yvals.inside:
x = barX + barW - (1.2 * labelW)
else:
x = barX + barW + 0.2 * labelW
# if the label doesn't fit to the left of the bar, put it to the right
if x < barX:
x = barX + barW + 0.2 * labelW
cx.move_to(x, y)
cx.show_text(label)
class Rect(object):
def __init__(self, x, y, w, h, xval, yval, name):
self.x, self.y, self.w, self.h = x, y, w, h
self.xval, self.yval = xval, yval
self.name = name
def __str__(self):
return ("<bar.Rect@(%.2f, %.2f) %.2fx%.2f (%.2f, %.2f) %s>"
% (self.x, self.y, self.w, self.h, self.xval, self.yval,
self.name))
| apache-2.0 |
nodish/pexpect | pexpect/__init__.py | 2 | 3904 | '''Pexpect is a Python module for spawning child applications and controlling
them automatically. Pexpect can be used for automating interactive applications
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different servers. It
can be used for automated software testing. Pexpect is in the spirit of Don
Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
require TCL and Expect or require C extensions to be compiled. Pexpect does not
use C, Expect, or TCL extensions. It should work on any platform that supports
the standard Python pty module. The Pexpect interface focuses on ease of use so
that simple tasks are easy.
There are two main interfaces to the Pexpect system; these are the function,
run() and the class, spawn. The spawn class is more powerful. The run()
function is simpler than spawn, and is good for quickly calling program. When
you call the run() function it executes a given program and then returns the
output. This is a handy replacement for os.system().
For example::
pexpect.run('ls -la')
The spawn class is the more powerful interface to the Pexpect system. You can
use this to spawn a child program then interact with it by sending input and
expecting responses (waiting for patterns in the child's output).
For example::
child = pexpect.spawn('scp foo user@example.com:.')
child.expect('Password:')
child.sendline(mypassword)
This works even for commands that ask for passwords or other input outside of
the normal stdio streams. For example, ssh reads input directly from the TTY
device which bypasses stdin.
Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
Spiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.
Pexpect is free, open source, and all that good stuff.
http://pexpect.sourceforge.net/
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
import sys
PY3 = (sys.version_info[0] >= 3)
from .exceptions import ExceptionPexpect, EOF, TIMEOUT
from .utils import split_command_line, which, is_executable_file
from .expect import Expecter, searcher_re, searcher_string
if sys.platform != 'win32':
# On Unix, these are available at the top level for backwards compatibility
from .pty_spawn import spawn, spawnu
from .run import run, runu
__version__ = '4.1.dev'
__revision__ = ''
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'run', 'runu',
'which', 'split_command_line', '__version__', '__revision__']
# vim: set shiftround expandtab tabstop=4 shiftwidth=4 ft=python autoindent :
| isc |
MicrosoftGenomics/FaST-LMM | fastlmm/association/LeaveOneChromosomeOut.py | 2 | 2547 | #!/usr/bin/env python2.7
#
# Written (W) 2014 Christian Widmer
# Copyright (C) 2014 Microsoft Research
"""
Created on 2014-03-11
@author: Christian Widmer
@summary: Module for performing GWAS
"""
import logging
import numpy as np
import scipy as sp
import pandas as pd
from scipy import stats
import pylab
import time
import fastlmm.inference as fastlmm
import fastlmm.util.util as util
from fastlmm.pyplink.snpreader.Bed import Bed
from fastlmm.util.pickle_io import load, save
from fastlmm.util.util import argintersect_left
class LeaveOneChromosomeOut(object):
"""LeaveOneChromosomeOut cross validation iterator (based on sklearn).
Provides train/test indices to split data in train test sets. Split
dataset into k consecutive folds according to which chromosome they belong to.
Each fold is then used a validation set once while the k - 1 remaining
fold form the training set.
Parameters
----------
chr : list
List of chromosome identifiers
indices : boolean, optional (default True)
Return train/test split as arrays of indices, rather than a boolean
mask array. Integer indices are required when dealing with sparse
matrices, since those cannot be indexed by boolean masks.
random_state : int or RandomState
Pseudo number generator state used for random sampling.
"""
def __init__(self, chr_names, indices=True, random_state=None):
#random_state = check_random_state(random_state)
self.chr_names = np.array(chr_names)
self.unique_chr_names = list(set(chr_names))
self.unique_chr_names.sort()
assert len(self.unique_chr_names) > 1
self.n = len(self.chr_names)
self.n_folds = len(self.unique_chr_names)
self.indices = indices
self.idxs = np.arange(self.n)
def __iter__(self):
if self.indices:
ind = np.arange(self.n)
for chr_name in self.unique_chr_names:
test_index = self.chr_names == chr_name
train_index = np.logical_not(test_index)
if self.indices:
train_index = ind[train_index]
test_index = ind[test_index]
yield train_index, test_index
def __repr__(self):
return '%s.%s(n=%i, n_folds=%i)' % (
self.__class__.__module__,
self.__class__.__name__,
self.n,
self.n_folds,
)
def __len__(self):
return self.n_folds
| apache-2.0 |
apdavison/IzhikevichModel | PyNN/old/test_Izhikevich.py | 2 | 6043 |
from pyNN.random import RandomDistribution, NumpyRNG
#from pyNN.neuron import *
from pyNN.nest import *
from pyNN.utility import get_script_args, Timer, ProgressBar, init_logging, normalized_filename
import matplotlib.pyplot as plt
import numpy as np
globalTimeStep = 0.01
timeStep = globalTimeStep
setup(timestep=timeStep, min_delay=0.5)
a = 0.02
b = -0.1
c = -55.0
d = 6.0
I = 0
v_init = -70
u_init = b * v_init
neuronParameters = {
'a': a,
'b': b,
'c': c,
'd': d,
'i_offset': I
}
initialValues = {'u': u_init, 'v': v_init}
cell_type = Izhikevich(**neuronParameters)
neuron = create(cell_type)
neuron.initialize(**initialValues)
neuron.record('v')
totalTimes = np.zeros(0)
totalAmps = np.zeros(0)
times = np.linspace(0.0, 30.0, int(1 + (30.0 - 0.0) / timeStep))
amps = np.linspace(0.0, 0.0, int(1 + (30.0 - 0.0) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
times = np.linspace(30 + timeStep, 300, int((300 - 30) / timeStep))
amps = np.linspace(0.075 * timeStep, 0.075 * (300 - 30), int((300 - 30) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
injectedCurrent = StepCurrentSource(times=totalTimes, amplitudes=totalAmps)
injectedCurrent.inject_into(neuron)
#neuron.set(i_offset = 30)
run(300)
data = neuron.get_data().segments[0]
plt.ion()
fig = plt.figure(1, facecolor='white')
ax1 = fig.add_subplot(5, 4, 7)
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)
ax1.spines['left'].set_color('None')
ax1.spines['right'].set_color('None')
ax1.spines['bottom'].set_color('None')
ax1.spines['top'].set_color('None')
ax1.set_title('(G) Class 1 excitable')
vm = data.filter(name='v')[0]
plt.plot(vm.times, vm, [0, 30, 300, 300],[-90, -90, -70, -90])
plt.show(block=False)
fig.canvas.draw()
############################################
## Sub-plot H: Class 2 excitable
############################################
timeStep = globalTimeStep
setup(timestep=timeStep, min_delay=0.5)
a = 0.2
b = 0.26
c = -65.0
d = 0.0
I = -0.5
v_init = -64.0
u_init = b * v_init
neuronParameters = {
'a': a,
'b': b,
'c': c,
'd': d,
'i_offset': I
}
initialValues = {'u': u_init, 'v': v_init}
cell_type = Izhikevich(**neuronParameters)
neuron = create(cell_type)
neuron.initialize(**initialValues)
neuron.record('v')
totalTimes = np.zeros(0)
totalAmps = np.zeros(0)
times = np.linspace(0.0, 30.0, int(1 + (30.0 - 0.0) / timeStep))
amps = np.linspace(-0.5, -0.5, int(1 + (30.0 - 0.0) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
times = np.linspace(30 + timeStep, 300, int((300 - 30) / timeStep))
amps = np.linspace(-0.5 + 0.015 * timeStep, -0.5 + 0.015 * (300 - 30), int((300 - 30) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
injectedCurrent = StepCurrentSource(times=totalTimes, amplitudes=totalAmps)
injectedCurrent.inject_into(neuron)
run(300)
data = neuron.get_data().segments[0]
plt.ion()
fig = plt.figure(1, facecolor='white')
ax1 = fig.add_subplot(5, 4, 8)
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)
ax1.spines['left'].set_color('None')
ax1.spines['right'].set_color('None')
ax1.spines['bottom'].set_color('None')
ax1.spines['top'].set_color('None')
ax1.set_title('(H) Class 1 excitable')
vm = data.filter(name='v')[0]
plt.plot(vm.times, vm, [0, 30, 300, 300],[-90, -90,-70, -90]);
plt.show(block=False)
fig.canvas.draw()
#####################################################
## Sub-plot R: Accomodation
#####################################################
timeStep = globalTimeStep
setup(timestep=timeStep, min_delay=0.5)
a = 0.02
b = 1.0
c = -55.0
d = 4.0
I = 0.0
v_init = -65.0
u_init = -16.0
neuronParameters = {
'a': a,
'b': b,
'c': c,
'd': d,
'i_offset': I
}
initialValues = {'u': u_init, 'v': v_init}
cell_type = Izhikevich(**neuronParameters)
neuron = create(cell_type)
neuron.initialize(**initialValues)
neuron.record('v')
totalTimes = np.zeros(0)
totalAmps = np.zeros(0)
times = np.linspace(0.0, 200.0, int(1 + (200.0 - 0.0) / timeStep))
amps = np.linspace(0.0, 8.0, int(1 + (200.0 - 0.0) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
times = np.linspace(200 + timeStep, 300, int((300 - 200) / timeStep))
amps = np.linspace(0.0, 0.0, int((300 - 200) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
times = np.linspace(300 + timeStep, 312.5, int((312.5 - 300) / timeStep))
amps = np.linspace(0.0, 4.0, int((312.5 - 300) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
times = np.linspace(312.5 + timeStep, 400, int((400 - 312.5) / timeStep))
amps = np.linspace(0.0, 0.0, int((400 - 312.5) / timeStep))
totalTimes = np.append(totalTimes, times)
totalAmps = np.append(totalAmps, amps)
injectedCurrent = StepCurrentSource(times=totalTimes, amplitudes=totalAmps)
injectedCurrent.inject_into(neuron)
run(400.0)
data = neuron.get_data().segments[0]
plt.ion()
fig = plt.figure(1, facecolor='white')
ax1 = fig.add_subplot(5, 4, 18)
#plt.xlabel("Time (ms)")
#plt.ylabel("Vm (mV)")
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)
ax1.spines['left'].set_color('None')
ax1.spines['right'].set_color('None')
ax1.spines['bottom'].set_color('None')
ax1.spines['top'].set_color('None')
ax1.set_title('(R) Accomodation')
vm = data.filter(name='v')[0]
plt.plot(vm.times, vm, totalTimes,1.5 * totalAmps - 90);
plt.show(block=False)
fig.canvas.draw()
raw_input("Simulation finished... Press enter to exit...")
| bsd-3-clause |
tf-czu/EFD | image.py | 1 | 4172 | #!/usr/bin/python
"""
Simple tools for images
usage:
python image.py <input img> <color> <treshold value>
"""
import sys
import numpy as np
import cv2
from matplotlib import pyplot as plt
from contours import *
ker1 = 10
CUTING = False
Xi = 100
Yi = 200
Xe = 3900
Ye = 2600
def cutImage(img, xi, yi, xe, ye, imShow = False ):
img = img[yi:ye, xi:xe]
if imShow == True:
showImg( img )
return img
def writeLabelsInImg( img, referencePoints1, outFileName, referencePoints2 = None, resize = None ):
num1 = 0
#offset = np.array([100,0]) #for tae2016 only
color1 = (0,0,255)
font = cv2.FONT_HERSHEY_SIMPLEX
for point in referencePoints1:
point = tuple(point)
#point = tuple(point - offset) #for tae2016 only
cv2.putText(img, str(num1),point, font, 3,color1,2 )
num1 += 1
if referencePoints2:
offset = np.array([150, 0])
num2 = 0
color2 = (255, 0, 0)
for point2 in referencePoints2:
#print point2
point2 = point2 + offset
#print"point", point2
point2 = tuple(point2)
cv2.putText(img, str(num2),point2, font, 2,color2,2 )
num2 += 1
if resize:
img = cv2.resize(img, None, fx = resize, fy = resize, interpolation = cv2.INTER_CUBIC)
cv2.imwrite( outFileName, img )
return img
def writeImg( img, fileName ):
cv2.imwrite( fileName, img )
def showImg( img ):
cv2.imshow( 'image', img )
cv2.waitKey(0)
cv2.destroyAllWindows()
def getHist( grayImg ):
# showImg( grayImg )
plt.hist( grayImg.ravel(), 256,[0,256])
plt.show()
def getGrayImg( img, color = "g" ):
gray = None
b,g,r = cv2.split( img )
if color == "g":
gray = g
elif color == "b":
gray = b
elif color == "r":
gray = r
else:
print "color is not defined!"
return gray
def getThreshold( gray, thrValue ):
ret, binaryImg = cv2.threshold( gray, thrValue, 255,cv2.THRESH_BINARY_INV)
return binaryImg
def openingClosing( binaryImg, ker1 = 10, ker2 = 5 ):
newBinaryImg = None
kernel = np.ones( ( ker1, ker1 ), np.uint8 )
newBinaryImg = cv2.morphologyEx( binaryImg, cv2.MORPH_OPEN, kernel)
if ker2 != None:
kernel = np.ones( ( ker2, ker2 ), np.uint8 )
newBinaryImg = cv2.morphologyEx( newBinaryImg, cv2.MORPH_CLOSE, kernel)
return newBinaryImg
def imageMain( imageFile, tresh, color, cuting = True ):
img = cv2.imread( imageFile, 1 )
if cuting == True:
img = cutImage(img, Xi, Yi, Xe, Ye, imShow = False )
cv2.imwrite( "cutedImg.png", img )
gray = getGrayImg( img, color )
grayImgName = imageFile.split(".")[0]+"_gray.png"
cv2.imwrite( grayImgName, gray )
getHist( gray )
if tresh:
binaryImg = getThreshold( gray, tresh )
binaryImg2 = openingClosing( binaryImg, ker1, ker2 = None )
newImgName = imageFile.split(".")[0]+"_test.png"
newImgName2 = imageFile.split(".")[0]+"_test2.png"
#newImgName = "newImg.png"
cv2.imwrite( newImgName, binaryImg )
cv2.imwrite( newImgName2, binaryImg2 )
contoursList, hierarchy= cv2.findContours( binaryImg2.copy(), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
contoursList, referencePoints = sortContours2(contoursList)
print "Number of cnt:", len(contoursList)
outFileNameLab = imageFile.split(".")[0]+"_lab.png"
#print outFileNameLab
img = writeLabelsInImg( img, referencePoints, outFileNameLab )
#cntNum = 100
#cv2.drawContours(img, contoursList, cntNum, (0,255,0), 3)
#cv2.imwrite( "imgLabCNT.png", img )
if __name__ == "__main__":
if len(sys.argv) < 2:
print __doc__
sys.exit(1)
color = "g"
tresh = None
if len(sys.argv) > 2:
color = sys.argv[2]
if len(sys.argv) > 3:
tresh = float(sys.argv[3])
cuting = CUTING
imageFile = sys.argv[1]
imageMain( imageFile, tresh, color, cuting )
| gpl-2.0 |
caseyrygt/osf.io | scripts/osfstorage/migrate_from_oldels.py | 51 | 9228 | from __future__ import division
from __future__ import unicode_literals
import logging
import datetime as dt
from pymongo.errors import DuplicateKeyError
from modularodm import Q
from modularodm.storage.base import KeyExistsException
from framework.mongo import database
from framework.analytics import clean_page
from framework.transactions.context import TokuTransaction
from scripts import utils as scripts_utils
from website.app import init_app
from website.project.model import NodeLog
from website.addons.osfstorage import model
from website.addons.osfstorage import oldels
logger = logging.getLogger(__name__)
LOG_ACTIONS = [
'osf_storage_file_added',
'osf_storage_file_updated',
'osf_storage_file_removed',
'osf_storage_file_restored',
'file_added',
'file_updated',
'file_removed',
'file_restored',
]
def migrate_download_counts(node, children, dry=True):
collection = database['pagecounters']
updates = []
for old_path, new in children.items():
if dry:
# Note in dry mode new is None
new_id = ':'.join(['download', node._id, 'new_id'])
old_id = ':'.join(['download', node._id, old_path])
else:
new_id = ':'.join(['download', node._id, new._id])
old_id = ':'.join(['download', node._id, old_path])
result = collection.find_one({'_id': clean_page(old_id)})
if not result:
continue
logger.info('Copying download counts of {!r} to {!r}'.format(old_path, new))
if not dry:
result['_id'] = new_id
updates.append(result)
# try:
# # database.pagecounters.insert(result)
# except DuplicateKeyError:
# logger.warn('Already migrated {!r}'.format(old_path))
# continue
else:
continue
for idx in range(len(new.versions)):
result = collection.find_one({'_id': clean_page('{}:{}'.format(old_id, idx + 1))})
if not result:
continue
logger.info('Copying download count of version {} of {!r} to version {} of {!r}'.format(idx + 1, old_path, idx, new))
if not dry:
result['_id'] = '{}:{}'.format(new_id, idx)
updates.append(result)
# database.pagecounters.insert(result)
if not dry:
try:
database.pagecounters.insert(updates, continue_on_error=True)
except DuplicateKeyError:
pass
def migrate_node_settings(node_settings, dry=True):
logger.info('Running `on add` for node settings of {}'.format(node_settings.owner._id))
if not dry:
node_settings.on_add()
def migrate_file(node, old, parent, dry=True):
assert isinstance(old, oldels.OsfStorageFileRecord)
if not dry:
try:
new = parent.append_file(old.name)
logger.debug('Created new child {}'.format(old.name))
except KeyExistsException:
logger.warning('{!r} has already been migrated'.format(old))
return parent.find_child_by_name(old.name)
new.versions = old.versions
new.is_deleted = old.is_deleted
new.save()
else:
new = None
return new
def migrate_logs(node, children, dry=True):
for log in NodeLog.find(Q('params.node', 'eq', node._id)):
if log.action not in LOG_ACTIONS:
continue
if log.params.get('_path') is not None and log.params.get('_urls'):
logger.warning('Log for file {} has already been migrated'.format(log.params['path']))
continue
if dry:
logger.debug('{!r} {} -> {}'.format(log, log.params['path'], 'New path'))
continue
try:
new = children[log.params['path']]
except KeyError:
if not log.params['path'].startswith('/'):
logger.warning('Failed to migrate log with path {}'.format(log.params['path']))
continue
mpath = new.materialized_path()
url = '/{}/files/osfstorage/{}/'.format(node._id, new._id)
logger.debug('{!r} {} -> {}'.format(log, log.params['path'], mpath))
log.params['_path'] = mpath
log.params['_urls'] = {
'view': url,
'download': url + '?action=download'
}
log.save()
NodeLog._cache.clear()
def migrate_guids(node_settings, children, dry=True):
for guid in model.OsfStorageGuidFile.find(
Q('node', 'eq', node_settings.owner) & Q('_has_no_file_tree', 'ne', True)):
if guid._path is not None:
logger.warn('File guid {} has already been migrated'.format(guid._id))
continue
logger.info('Migrating file guid {}'.format(guid._id))
if not dry:
try:
guid._path = children[guid.path].path
except KeyError:
if not guid.path.startswith('/'):
# A number of invalid GUIDs were generated by
# search bots that spidered invalid URLs
# e.g. /blah/{{ urls.revisions }}
# which created OsfStorageGuidFile records
# that are not included in the file_tree for
# a node's OsfStorageNodeSettings
# Any file Guid whose path contains a '/' should
# be considered invalid, and we skip over those and mark them so that
# the rest of the migration can occur
logger.warning('Skipping invalid OsfStorageGuidFile with _id {} and path {}. Marking as invalid...'.format(guid._id, guid.path))
guid._has_no_file_tree = True
guid.save()
else:
logger.warning('Already migrated {!r}'.format(guid))
continue
guid.save()
model.OsfStorageGuidFile._cache.clear()
def migrate_children(node_settings, dry=True):
if not node_settings.file_tree:
return logger.warning('Skipping node {}; file_tree is None'.format(node_settings.owner._id))
logger.info('Migrating children of node {}'.format(node_settings.owner._id))
children = {}
for x in node_settings.file_tree.children:
n = migrate_file(node_settings.owner, x, node_settings.root_node, dry=dry)
if n: # not migrated yet
children[x.path] = n
migrate_logs(node_settings.owner, children, dry=dry)
migrate_guids(node_settings, children, dry=dry)
migrate_download_counts(node_settings.owner, children, dry=dry)
del children
def main(nworkers, worker_id, dry=True):
if not dry:
scripts_utils.add_file_logger(logger, __file__)
logger.info('Not running in dry mode, changes WILL be made')
else:
logger.info('Running in dry mode, changes NOT will be made')
to_migrate = model.OsfStorageNodeSettings.find(Q('_migrated_from_old_models', 'ne', True))
if to_migrate.count() == 0:
logger.info('No nodes to migrate; exiting...')
return
failed = 0
logger.info('Found {} nodes to migrate'.format(to_migrate.count()))
for node_settings in to_migrate:
if hash(node_settings._id) % nworkers != worker_id:
continue
try:
with TokuTransaction():
migrate_node_settings(node_settings, dry=dry)
migrate_children(node_settings, dry=dry)
if not dry:
node_settings.reload()
node_settings._migrated_from_old_models = True
node_settings.save()
except Exception as error:
logger.error('Could not migrate file tree from {}'.format(node_settings.owner._id))
logger.exception(error)
failed += 1
if failed > 0:
logger.error('Failed to migrate {} nodes'.format(failed))
# Migrate file guids
# db.osfstorageguidfile.update({
# '_path': {'$ne': null}
# }, {
# $rename:{'path': 'premigration_path'}
# }, {multi: true})
# db.osfstorageguidfile.update({
# '_path': {'$ne': null}
# }, {
# $rename:{'_path': 'path'}
# }, {multi: true})
# Migrate logs
# db.nodelog.update({
# 'params._path': {'$ne': null}
# }, {
# $rename:{'params.path': 'params.premigration_path'}
# }, {multi: true})
# db.nodelog.update({
# 'params._path': {'$ne': null}
# }, {
# $rename:{'params._path': 'params.path'}
# }, {multi: true})
# db.nodelog.update({
# 'params._urls': {'$ne': null}
# }, {
# $rename:{'params.urls': 'params.premigration_urls'}
# }, {multi: true})
# db.nodelog.update({
# 'params._urls': {'$ne': null}
# }, {
# $rename:{'params._urls': 'params.urls'}
# }, {multi: true})
if __name__ == '__main__':
import sys
nworkers = int(sys.argv[1])
worker_id = int(sys.argv[2])
dry = 'dry' in sys.argv
if 'debug' in sys.argv:
logger.setLevel(logging.DEBUG)
elif 'info' in sys.argv:
logger.setLevel(logging.INFO)
elif 'error' in sys.argv:
logger.setLevel(logging.ERROR)
init_app(set_backends=True, routes=False)
main(nworkers, worker_id, dry=dry)
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.