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 |
|---|---|---|---|---|---|
Vassy/odoo | addons/hr_payroll_account/__init__.py | 433 | 1116 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import hr_payroll_account
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
zzcclp/spark | python/pyspark/pandas/series.py | 9 | 197528 | #
# 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.
#
"""
A wrapper class for Spark Column to behave similar to pandas Series.
"""
import datetime
import re
import inspect
import sys
from collections.abc import Mapping
from functools import partial, wraps, reduce
from typing import (
Any,
Callable,
Dict,
Generic,
IO,
Iterable,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
no_type_check,
overload,
TYPE_CHECKING,
)
import numpy as np
import pandas as pd
from pandas.core.accessor import CachedAccessor
from pandas.io.formats.printing import pprint_thing
from pandas.api.types import is_list_like, is_hashable
from pandas.api.extensions import ExtensionDtype
from pandas.tseries.frequencies import DateOffset
from pyspark.sql import functions as F, Column, DataFrame as SparkDataFrame
from pyspark.sql.types import (
ArrayType,
BooleanType,
DataType,
DoubleType,
FloatType,
IntegerType,
IntegralType,
LongType,
NumericType,
Row,
StructType,
)
from pyspark.sql.window import Window
from pyspark import pandas as ps # For running doctests and reference resolution in PyCharm.
from pyspark.pandas._typing import Axis, Dtype, Label, Name, Scalar, T
from pyspark.pandas.accessors import PandasOnSparkSeriesMethods
from pyspark.pandas.categorical import CategoricalAccessor
from pyspark.pandas.config import get_option
from pyspark.pandas.base import IndexOpsMixin
from pyspark.pandas.exceptions import SparkPandasIndexingError
from pyspark.pandas.frame import DataFrame
from pyspark.pandas.generic import Frame
from pyspark.pandas.internal import (
InternalField,
InternalFrame,
DEFAULT_SERIES_NAME,
NATURAL_ORDER_COLUMN_NAME,
SPARK_DEFAULT_INDEX_NAME,
SPARK_DEFAULT_SERIES_NAME,
)
from pyspark.pandas.missing.series import MissingPandasLikeSeries
from pyspark.pandas.plot import PandasOnSparkPlotAccessor
from pyspark.pandas.ml import corr
from pyspark.pandas.utils import (
combine_frames,
is_name_like_tuple,
is_name_like_value,
name_like_string,
same_anchor,
scol_for,
sql_conf,
validate_arguments_and_invoke_function,
validate_axis,
validate_bool_kwarg,
verify_temp_column_name,
SPARK_CONF_ARROW_ENABLED,
)
from pyspark.pandas.datetimes import DatetimeMethods
from pyspark.pandas.spark import functions as SF
from pyspark.pandas.spark.accessors import SparkSeriesMethods
from pyspark.pandas.strings import StringMethods
from pyspark.pandas.typedef import (
infer_return_type,
spark_type_to_pandas_dtype,
ScalarType,
SeriesType,
)
if TYPE_CHECKING:
from pyspark.sql._typing import ColumnOrName # noqa: F401 (SPARK-34943)
from pyspark.pandas.groupby import SeriesGroupBy # noqa: F401 (SPARK-34943)
from pyspark.pandas.indexes import Index # noqa: F401 (SPARK-34943)
# This regular expression pattern is complied and defined here to avoid to compile the same
# pattern every time it is used in _repr_ in Series.
# This pattern basically seeks the footer string from pandas'
REPR_PATTERN = re.compile(r"Length: (?P<length>[0-9]+)")
_flex_doc_SERIES = """
Return {desc} of series and other, element-wise (binary operator `{op_name}`).
Equivalent to ``{equiv}``
Parameters
----------
other : Series or scalar value
Returns
-------
Series
The result of the operation.
See Also
--------
Series.{reverse}
{series_examples}
"""
_add_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.add(df.b)
a 4.0
b NaN
c 6.0
d NaN
dtype: float64
>>> df.a.radd(df.b)
a 4.0
b NaN
c 6.0
d NaN
dtype: float64
"""
_sub_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.subtract(df.b)
a 0.0
b NaN
c 2.0
d NaN
dtype: float64
>>> df.a.rsub(df.b)
a 0.0
b NaN
c -2.0
d NaN
dtype: float64
"""
_mul_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.multiply(df.b)
a 4.0
b NaN
c 8.0
d NaN
dtype: float64
>>> df.a.rmul(df.b)
a 4.0
b NaN
c 8.0
d NaN
dtype: float64
"""
_div_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.divide(df.b)
a 1.0
b NaN
c 2.0
d NaN
dtype: float64
>>> df.a.rdiv(df.b)
a 1.0
b NaN
c 0.5
d NaN
dtype: float64
"""
_pow_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.pow(df.b)
a 4.0
b NaN
c 16.0
d NaN
dtype: float64
>>> df.a.rpow(df.b)
a 4.0
b NaN
c 16.0
d NaN
dtype: float64
"""
_mod_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.mod(df.b)
a 0.0
b NaN
c 0.0
d NaN
dtype: float64
>>> df.a.rmod(df.b)
a 0.0
b NaN
c 2.0
d NaN
dtype: float64
"""
_floordiv_example_SERIES = """
Examples
--------
>>> df = ps.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.floordiv(df.b)
a 1.0
b NaN
c 2.0
d NaN
dtype: float64
>>> df.a.rfloordiv(df.b)
a 1.0
b NaN
c 0.0
d NaN
dtype: float64
"""
# Needed to disambiguate Series.str and str type
str_type = str
def _create_type_for_series_type(param: Any) -> Type[SeriesType]:
from pyspark.pandas.typedef import NameTypeHolder
if isinstance(param, ExtensionDtype):
new_class = type("NameType", (NameTypeHolder,), {}) # type: Type[NameTypeHolder]
new_class.tpe = param
else:
new_class = param.type if isinstance(param, np.dtype) else param
return SeriesType[new_class] # type: ignore
if (3, 5) <= sys.version_info < (3, 7) and __name__ != "__main__":
from typing import GenericMeta # type: ignore
old_getitem = GenericMeta.__getitem__ # type: ignore
@no_type_check
def new_getitem(self, params):
if hasattr(self, "is_series"):
return old_getitem(self, _create_type_for_series_type(params))
else:
return old_getitem(self, params)
GenericMeta.__getitem__ = new_getitem # type: ignore
class Series(Frame, IndexOpsMixin, Generic[T]):
"""
pandas-on-Spark Series that corresponds to pandas Series logically. This holds Spark Column
internally.
:ivar _internal: an internal immutable Frame to manage metadata.
:type _internal: InternalFrame
:ivar _psdf: Parent's pandas-on-Spark DataFrame
:type _psdf: ps.DataFrame
Parameters
----------
data : array-like, dict, or scalar value, pandas Series
Contains data stored in Series
If data is a dict, argument order is maintained for Python 3.6
and later.
Note that if `data` is a pandas Series, other arguments should not be used.
index : array-like or Index (1d)
Values must be hashable and have the same length as `data`.
Non-unique index values are allowed. Will default to
RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index
sequence are used, the index will override the keys found in the
dict.
dtype : numpy.dtype or None
If None, dtype will be inferred
copy : boolean, default False
Copy input data
"""
@no_type_check
def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False):
assert data is not None
if isinstance(data, DataFrame):
assert dtype is None
assert name is None
assert not copy
assert not fastpath
self._anchor = data # type: DataFrame
self._col_label = index # type: Label
else:
if isinstance(data, pd.Series):
assert index is None
assert dtype is None
assert name is None
assert not copy
assert not fastpath
s = data
else:
s = pd.Series(
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath
)
internal = InternalFrame.from_pandas(pd.DataFrame(s))
if s.name is None:
internal = internal.copy(column_labels=[None])
anchor = DataFrame(internal)
self._anchor = anchor
self._col_label = anchor._internal.column_labels[0]
object.__setattr__(anchor, "_psseries", {self._column_label: self})
@property
def _psdf(self) -> DataFrame:
return self._anchor
@property
def _internal(self) -> InternalFrame:
return self._psdf._internal.select_column(self._column_label)
@property
def _column_label(self) -> Optional[Label]:
return self._col_label
def _update_anchor(self, psdf: DataFrame) -> None:
assert psdf._internal.column_labels == [self._column_label], (
psdf._internal.column_labels,
[self._column_label],
)
self._anchor = psdf
object.__setattr__(psdf, "_psseries", {self._column_label: self})
def _with_new_scol(self, scol: Column, *, field: Optional[InternalField] = None) -> "Series":
"""
Copy pandas-on-Spark Series with the new Spark Column.
:param scol: the new Spark Column
:return: the copied Series
"""
name = name_like_string(self._column_label)
internal = self._internal.copy(
data_spark_columns=[scol.alias(name)],
data_fields=[
field if field is None or field.struct_field is None else field.copy(name=name)
],
)
return first_series(DataFrame(internal))
spark = CachedAccessor("spark", SparkSeriesMethods)
@property
def dtypes(self) -> Dtype:
"""Return the dtype object of the underlying data.
>>> s = ps.Series(list('abc'))
>>> s.dtype == s.dtypes
True
"""
return self.dtype
@property
def axes(self) -> List["Index"]:
"""
Return a list of the row axis labels.
Examples
--------
>>> psser = ps.Series([1, 2, 3])
>>> psser.axes
[Int64Index([0, 1, 2], dtype='int64')]
"""
return [self.index]
# Arithmetic Operators
def add(self, other: Any) -> "Series":
return self + other
add.__doc__ = _flex_doc_SERIES.format(
desc="Addition",
op_name="+",
equiv="series + other",
reverse="radd",
series_examples=_add_example_SERIES,
)
def radd(self, other: Any) -> "Series":
return other + self
radd.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Addition",
op_name="+",
equiv="other + series",
reverse="add",
series_examples=_add_example_SERIES,
)
def div(self, other: Any) -> "Series":
return self / other
div.__doc__ = _flex_doc_SERIES.format(
desc="Floating division",
op_name="/",
equiv="series / other",
reverse="rdiv",
series_examples=_div_example_SERIES,
)
divide = div
def rdiv(self, other: Any) -> "Series":
return other / self
rdiv.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Floating division",
op_name="/",
equiv="other / series",
reverse="div",
series_examples=_div_example_SERIES,
)
def truediv(self, other: Any) -> "Series":
return self / other
truediv.__doc__ = _flex_doc_SERIES.format(
desc="Floating division",
op_name="/",
equiv="series / other",
reverse="rtruediv",
series_examples=_div_example_SERIES,
)
def rtruediv(self, other: Any) -> "Series":
return other / self
rtruediv.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Floating division",
op_name="/",
equiv="other / series",
reverse="truediv",
series_examples=_div_example_SERIES,
)
def mul(self, other: Any) -> "Series":
return self * other
mul.__doc__ = _flex_doc_SERIES.format(
desc="Multiplication",
op_name="*",
equiv="series * other",
reverse="rmul",
series_examples=_mul_example_SERIES,
)
multiply = mul
def rmul(self, other: Any) -> "Series":
return other * self
rmul.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Multiplication",
op_name="*",
equiv="other * series",
reverse="mul",
series_examples=_mul_example_SERIES,
)
def sub(self, other: Any) -> "Series":
return self - other
sub.__doc__ = _flex_doc_SERIES.format(
desc="Subtraction",
op_name="-",
equiv="series - other",
reverse="rsub",
series_examples=_sub_example_SERIES,
)
subtract = sub
def rsub(self, other: Any) -> "Series":
return other - self
rsub.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Subtraction",
op_name="-",
equiv="other - series",
reverse="sub",
series_examples=_sub_example_SERIES,
)
def mod(self, other: Any) -> "Series":
return self % other
mod.__doc__ = _flex_doc_SERIES.format(
desc="Modulo",
op_name="%",
equiv="series % other",
reverse="rmod",
series_examples=_mod_example_SERIES,
)
def rmod(self, other: Any) -> "Series":
return other % self
rmod.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Modulo",
op_name="%",
equiv="other % series",
reverse="mod",
series_examples=_mod_example_SERIES,
)
def pow(self, other: Any) -> "Series":
return self ** other
pow.__doc__ = _flex_doc_SERIES.format(
desc="Exponential power of series",
op_name="**",
equiv="series ** other",
reverse="rpow",
series_examples=_pow_example_SERIES,
)
def rpow(self, other: Any) -> "Series":
return other ** self
rpow.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Exponential power",
op_name="**",
equiv="other ** series",
reverse="pow",
series_examples=_pow_example_SERIES,
)
def floordiv(self, other: Any) -> "Series":
return self // other
floordiv.__doc__ = _flex_doc_SERIES.format(
desc="Integer division",
op_name="//",
equiv="series // other",
reverse="rfloordiv",
series_examples=_floordiv_example_SERIES,
)
def rfloordiv(self, other: Any) -> "Series":
return other // self
rfloordiv.__doc__ = _flex_doc_SERIES.format(
desc="Reverse Integer division",
op_name="//",
equiv="other // series",
reverse="floordiv",
series_examples=_floordiv_example_SERIES,
)
# create accessor for pandas-on-Spark specific methods.
pandas_on_spark = CachedAccessor("pandas_on_spark", PandasOnSparkSeriesMethods)
# keep the name "koalas" for backward compatibility.
koalas = CachedAccessor("koalas", PandasOnSparkSeriesMethods)
# Comparison Operators
def eq(self, other: Any) -> bool:
"""
Compare if the current value is equal to the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a == 1
a True
b False
c False
d False
Name: a, dtype: bool
>>> df.b.eq(1)
a True
b False
c True
d False
Name: b, dtype: bool
"""
return self == other
equals = eq
def gt(self, other: Any) -> "Series":
"""
Compare if the current value is greater than the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a > 1
a False
b True
c True
d True
Name: a, dtype: bool
>>> df.b.gt(1)
a False
b False
c False
d False
Name: b, dtype: bool
"""
return self > other
def ge(self, other: Any) -> "Series":
"""
Compare if the current value is greater than or equal to the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a >= 2
a False
b True
c True
d True
Name: a, dtype: bool
>>> df.b.ge(2)
a False
b False
c False
d False
Name: b, dtype: bool
"""
return self >= other
def lt(self, other: Any) -> "Series":
"""
Compare if the current value is less than the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a < 1
a False
b False
c False
d False
Name: a, dtype: bool
>>> df.b.lt(2)
a True
b False
c True
d False
Name: b, dtype: bool
"""
return self < other
def le(self, other: Any) -> "Series":
"""
Compare if the current value is less than or equal to the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a <= 2
a True
b True
c False
d False
Name: a, dtype: bool
>>> df.b.le(2)
a True
b False
c True
d False
Name: b, dtype: bool
"""
return self <= other
def ne(self, other: Any) -> "Series":
"""
Compare if the current value is not equal to the other.
>>> df = ps.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a != 1
a False
b True
c True
d True
Name: a, dtype: bool
>>> df.b.ne(1)
a False
b True
c False
d True
Name: b, dtype: bool
"""
return self != other
def divmod(self, other: Any) -> Tuple["Series", "Series"]:
"""
Return Integer division and modulo of series and other, element-wise
(binary operator `divmod`).
Parameters
----------
other : Series or scalar value
Returns
-------
2-Tuple of Series
The result of the operation.
See Also
--------
Series.rdivmod
"""
return self.floordiv(other), self.mod(other)
def rdivmod(self, other: Any) -> Tuple["Series", "Series"]:
"""
Return Integer division and modulo of series and other, element-wise
(binary operator `rdivmod`).
Parameters
----------
other : Series or scalar value
Returns
-------
2-Tuple of Series
The result of the operation.
See Also
--------
Series.divmod
"""
return self.rfloordiv(other), self.rmod(other)
def between(self, left: Any, right: Any, inclusive: bool = True) -> "Series":
"""
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are treated as `False`.
Parameters
----------
left : scalar or list-like
Left boundary.
right : scalar or list-like
Right boundary.
inclusive : bool, default True
Include boundaries.
Returns
-------
Series
Series representing whether each element is between left and
right (inclusive).
See Also
--------
Series.gt : Greater than of series and other.
Series.lt : Less than of series and other.
Notes
-----
This function is equivalent to ``(left <= ser) & (ser <= right)``
Examples
--------
>>> s = ps.Series([2, 0, 4, 8, np.nan])
Boundary values are included by default:
>>> s.between(1, 4)
0 True
1 False
2 True
3 False
4 False
dtype: bool
With `inclusive` set to ``False`` boundary values are excluded:
>>> s.between(1, 4, inclusive=False)
0 True
1 False
2 False
3 False
4 False
dtype: bool
`left` and `right` can be any scalar value:
>>> s = ps.Series(['Alice', 'Bob', 'Carol', 'Eve'])
>>> s.between('Anna', 'Daniel')
0 False
1 True
2 True
3 False
dtype: bool
"""
if inclusive:
lmask = self >= left
rmask = self <= right
else:
lmask = self > left
rmask = self < right
return lmask & rmask
# TODO: arg should support Series
# TODO: NaN and None
def map(self, arg: Union[Dict, Callable]) -> "Series":
"""
Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value,
that may be derived from a function, a ``dict``.
.. note:: make sure the size of the dictionary is not huge because it could
downgrade the performance or throw OutOfMemoryError due to a huge
expression within Spark. Consider the input as a functions as an
alternative instead in this case.
Parameters
----------
arg : function or dict
Mapping correspondence.
Returns
-------
Series
Same index as caller.
See Also
--------
Series.apply : For applying more complex functions on a Series.
DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
Notes
-----
When ``arg`` is a dictionary, values in Series that are not in the
dictionary (as keys) are converted to ``None``. However, if the
dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
provides a method for default values), then this default is used
rather than ``None``.
Examples
--------
>>> s = ps.Series(['cat', 'dog', None, 'rabbit'])
>>> s
0 cat
1 dog
2 None
3 rabbit
dtype: object
``map`` accepts a ``dict``. Values that are not found
in the ``dict`` are converted to ``None``, unless the dict has a default
value (e.g. ``defaultdict``):
>>> s.map({'cat': 'kitten', 'dog': 'puppy'})
0 kitten
1 puppy
2 None
3 None
dtype: object
It also accepts a function:
>>> def format(x) -> str:
... return 'I am a {}'.format(x)
>>> s.map(format)
0 I am a cat
1 I am a dog
2 I am a None
3 I am a rabbit
dtype: object
"""
if isinstance(arg, dict):
is_start = True
# In case dictionary is empty.
current = F.when(SF.lit(False), SF.lit(None).cast(self.spark.data_type))
for to_replace, value in arg.items():
if is_start:
current = F.when(self.spark.column == SF.lit(to_replace), value)
is_start = False
else:
current = current.when(self.spark.column == SF.lit(to_replace), value)
if hasattr(arg, "__missing__"):
tmp_val = arg[np._NoValue]
del arg[np._NoValue] # Remove in case it's set in defaultdict.
current = current.otherwise(SF.lit(tmp_val))
else:
current = current.otherwise(SF.lit(None).cast(self.spark.data_type))
return self._with_new_scol(current)
else:
return self.apply(arg)
@property
def shape(self) -> Tuple[int]:
"""Return a tuple of the shape of the underlying data."""
return (len(self),)
@property
def name(self) -> Name:
"""Return name of the Series."""
name = self._column_label
if name is not None and len(name) == 1:
return name[0]
else:
return name
@name.setter
def name(self, name: Name) -> None:
self.rename(name, inplace=True)
# TODO: Functionality and documentation should be matched. Currently, changing index labels
# taking dictionary and function to change index are not supported.
def rename(self, index: Optional[Name] = None, **kwargs: Any) -> "Series":
"""
Alter Series name.
Parameters
----------
index : scalar
Scalar will alter the ``Series.name`` attribute.
inplace : bool, default False
Whether to return a new Series. If True then value of copy is
ignored.
Returns
-------
Series
Series with name altered.
Examples
--------
>>> s = ps.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
"""
if index is None:
pass
elif not is_hashable(index):
raise TypeError("Series.name must be a hashable type")
elif not isinstance(index, tuple):
index = (index,)
name = name_like_string(index)
scol = self.spark.column.alias(name)
field = self._internal.data_fields[0].copy(name=name)
internal = self._internal.copy(
column_labels=[index],
data_spark_columns=[scol],
data_fields=[field],
column_label_names=None,
)
psdf = DataFrame(internal) # type: DataFrame
if kwargs.get("inplace", False):
self._col_label = index
self._update_anchor(psdf)
return self
else:
return first_series(psdf)
def rename_axis(
self, mapper: Optional[Any] = None, index: Optional[Any] = None, inplace: bool = False
) -> Optional["Series"]:
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper, index : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to the index values.
inplace : bool, default False
Modifies the object directly, instead of creating a new Series.
Returns
-------
Series, or None if `inplace` is True.
See Also
--------
Series.rename : Alter Series index labels or name.
DataFrame.rename : Alter DataFrame index labels or name.
Index.rename : Set new names on index.
Examples
--------
>>> s = ps.Series(["dog", "cat", "monkey"], name="animal")
>>> s # doctest: +NORMALIZE_WHITESPACE
0 dog
1 cat
2 monkey
Name: animal, dtype: object
>>> s.rename_axis("index").sort_index() # doctest: +NORMALIZE_WHITESPACE
index
0 dog
1 cat
2 monkey
Name: animal, dtype: object
**MultiIndex**
>>> index = pd.MultiIndex.from_product([['mammal'],
... ['dog', 'cat', 'monkey']],
... names=['type', 'name'])
>>> s = ps.Series([4, 4, 2], index=index, name='num_legs')
>>> s # doctest: +NORMALIZE_WHITESPACE
type name
mammal dog 4
cat 4
monkey 2
Name: num_legs, dtype: int64
>>> s.rename_axis(index={'type': 'class'}).sort_index() # doctest: +NORMALIZE_WHITESPACE
class name
mammal cat 4
dog 4
monkey 2
Name: num_legs, dtype: int64
>>> s.rename_axis(index=str.upper).sort_index() # doctest: +NORMALIZE_WHITESPACE
TYPE NAME
mammal cat 4
dog 4
monkey 2
Name: num_legs, dtype: int64
"""
psdf = self.to_frame().rename_axis(mapper=mapper, index=index, inplace=False)
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
@property
def index(self) -> "ps.Index":
"""The index (axis labels) Column of the Series.
See Also
--------
Index
"""
return self._psdf.index
@property
def is_unique(self) -> bool:
"""
Return boolean if values in the object are unique
Returns
-------
is_unique : boolean
>>> ps.Series([1, 2, 3]).is_unique
True
>>> ps.Series([1, 2, 2]).is_unique
False
>>> ps.Series([1, 2, 3, None]).is_unique
True
"""
scol = self.spark.column
# Here we check:
# 1. the distinct count without nulls and count without nulls for non-null values
# 2. count null values and see if null is a distinct value.
#
# This workaround is in order to calculate the distinct count including nulls in
# single pass. Note that COUNT(DISTINCT expr) in Spark is designed to ignore nulls.
return self._internal.spark_frame.select(
(F.count(scol) == F.countDistinct(scol))
& (F.count(F.when(scol.isNull(), 1).otherwise(None)) <= 1)
).collect()[0][0]
def reset_index(
self,
level: Optional[Union[int, Name, Sequence[Union[int, Name]]]] = None,
drop: bool = False,
name: Optional[Name] = None,
inplace: bool = False,
) -> Optional[Union["Series", DataFrame]]:
"""
Generate a new DataFrame or Series with the index reset.
This is useful when the index needs to be treated as a column,
or when the index is meaningless and needs to be reset
to the default before another operation.
Parameters
----------
level : int, str, tuple, or list, default optional
For a Series with a MultiIndex, only remove the specified levels from the index.
Removes all levels by default.
drop : bool, default False
Just reset the index, without inserting it as a column in the new DataFrame.
name : object, optional
The name to use for the column containing the original Series values.
Uses self.name by default. This argument is ignored when drop is True.
inplace : bool, default False
Modify the Series in place (do not create a new object).
Returns
-------
Series or DataFrame
When `drop` is False (the default), a DataFrame is returned.
The newly created columns will come first in the DataFrame,
followed by the original Series values.
When `drop` is True, a `Series` is returned.
In either case, if ``inplace=True``, no value is returned.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4], index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))
Generate a DataFrame with default index.
>>> s.reset_index()
idx 0
0 a 1
1 b 2
2 c 3
3 d 4
To specify the name of the new column use `name`.
>>> s.reset_index(name='values')
idx values
0 a 1
1 b 2
2 c 3
3 d 4
To generate a new Series with the default set `drop` to True.
>>> s.reset_index(drop=True)
0 1
1 2
2 3
3 4
dtype: int64
To update the Series in place, without generating a new one
set `inplace` to True. Note that it also requires ``drop=True``.
>>> s.reset_index(inplace=True, drop=True)
>>> s
0 1
1 2
2 3
3 4
dtype: int64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace and not drop:
raise TypeError("Cannot reset_index inplace on a Series to create a DataFrame")
if drop:
psdf = self._psdf[[self.name]]
else:
psser = self
if name is not None:
psser = psser.rename(name)
psdf = psser.to_frame()
psdf = psdf.reset_index(level=level, drop=drop)
if drop:
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
else:
return psdf
def to_frame(self, name: Optional[Name] = None) -> DataFrame:
"""
Convert Series to DataFrame.
Parameters
----------
name : object, default None
The passed name should substitute for the series name (if it has
one).
Returns
-------
DataFrame
DataFrame representation of Series.
Examples
--------
>>> s = ps.Series(["a", "b", "c"])
>>> s.to_frame()
0
0 a
1 b
2 c
>>> s = ps.Series(["a", "b", "c"], name="vals")
>>> s.to_frame()
vals
0 a
1 b
2 c
"""
if name is not None:
renamed = self.rename(name)
elif self._column_label is None:
renamed = self.rename(DEFAULT_SERIES_NAME)
else:
renamed = self
return DataFrame(renamed._internal)
to_dataframe = to_frame
def to_string(
self,
buf: Optional[IO[str]] = None,
na_rep: str = "NaN",
float_format: Optional[Callable[[float], str]] = None,
header: bool = True,
index: bool = True,
length: bool = False,
dtype: bool = False,
name: bool = False,
max_rows: Optional[int] = None,
) -> Optional[str]:
"""
Render a string representation of the Series.
.. note:: This method should only be used if the resulting pandas object is expected
to be small, as all the data is loaded into the driver's memory. If the input
is large, set max_rows parameter.
Parameters
----------
buf : StringIO-like, optional
buffer to write to
na_rep : string, optional
string representation of NAN to use, default 'NaN'
float_format : one-parameter function, optional
formatter function to apply to columns' elements if they are floats
default None
header : boolean, default True
Add the Series header (index name)
index : bool, optional
Add index (row) labels, default True
length : boolean, default False
Add the Series length
dtype : boolean, default False
Add the Series dtype
name : boolean, default False
Add the Series name if not None
max_rows : int, optional
Maximum number of rows to show before truncating. If None, show
all.
Returns
-------
formatted : string (if not buffer passed)
Examples
--------
>>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats'])
>>> print(df['dogs'].to_string())
0 0.2
1 0.0
2 0.6
3 0.2
>>> print(df['dogs'].to_string(max_rows=2))
0 0.2
1 0.0
"""
# Make sure locals() call is at the top of the function so we don't capture local variables.
args = locals()
if max_rows is not None:
psseries = self.head(max_rows)
else:
psseries = self
return validate_arguments_and_invoke_function(
psseries._to_internal_pandas(), self.to_string, pd.Series.to_string, args
)
def to_clipboard(self, excel: bool = True, sep: Optional[str] = None, **kwargs: Any) -> None:
# Docstring defined below by reusing DataFrame.to_clipboard's.
args = locals()
psseries = self
return validate_arguments_and_invoke_function(
psseries._to_internal_pandas(), self.to_clipboard, pd.Series.to_clipboard, args
)
to_clipboard.__doc__ = DataFrame.to_clipboard.__doc__
def to_dict(self, into: Type = dict) -> Mapping:
"""
Convert Series to {label -> value} dict or dict-like object.
.. note:: This method should only be used if the resulting pandas DataFrame is expected
to be small, as all the data is loaded into the driver's memory.
Parameters
----------
into : class, default dict
The collections.abc.Mapping subclass to use as the return
object. Can be the actual class or an empty
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.
Returns
-------
collections.abc.Mapping
Key-value representation of Series.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4])
>>> s_dict = s.to_dict()
>>> sorted(s_dict.items())
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> from collections import OrderedDict, defaultdict
>>> s.to_dict(OrderedDict)
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> dd = defaultdict(list)
>>> s.to_dict(dd) # doctest: +ELLIPSIS
defaultdict(<class 'list'>, {...})
"""
# Make sure locals() call is at the top of the function so we don't capture local variables.
args = locals()
psseries = self
return validate_arguments_and_invoke_function(
psseries._to_internal_pandas(), self.to_dict, pd.Series.to_dict, args
)
def to_latex(
self,
buf: Optional[IO[str]] = None,
columns: Optional[List[Name]] = None,
col_space: Optional[int] = None,
header: bool = True,
index: bool = True,
na_rep: str = "NaN",
formatters: Optional[
Union[List[Callable[[Any], str]], Dict[Name, Callable[[Any], str]]]
] = None,
float_format: Optional[Callable[[float], str]] = None,
sparsify: Optional[bool] = None,
index_names: bool = True,
bold_rows: bool = False,
column_format: Optional[str] = None,
longtable: Optional[bool] = None,
escape: Optional[bool] = None,
encoding: Optional[str] = None,
decimal: str = ".",
multicolumn: Optional[bool] = None,
multicolumn_format: Optional[str] = None,
multirow: Optional[bool] = None,
) -> Optional[str]:
args = locals()
psseries = self
return validate_arguments_and_invoke_function(
psseries._to_internal_pandas(), self.to_latex, pd.Series.to_latex, args
)
to_latex.__doc__ = DataFrame.to_latex.__doc__
def to_pandas(self) -> pd.Series:
"""
Return a pandas Series.
.. note:: This method should only be used if the resulting pandas object is expected
to be small, as all the data is loaded into the driver's memory.
Examples
--------
>>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats'])
>>> df['dogs'].to_pandas()
0 0.2
1 0.0
2 0.6
3 0.2
Name: dogs, dtype: float64
"""
return self._to_internal_pandas().copy()
def to_list(self) -> List:
"""
Return a list of the values.
These are each a scalar type, which is a Python scalar
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
.. note:: This method should only be used if the resulting list is expected
to be small, as all the data is loaded into the driver's memory.
"""
return self._to_internal_pandas().tolist()
tolist = to_list
def drop_duplicates(self, keep: str = "first", inplace: bool = False) -> Optional["Series"]:
"""
Return Series with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
Method to handle dropping duplicates:
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except for the last occurrence.
- ``False`` : Drop all duplicates.
inplace : bool, default ``False``
If ``True``, performs operation inplace and returns None.
Returns
-------
Series
Series with duplicates dropped.
Examples
--------
Generate a Series with duplicated entries.
>>> s = ps.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'],
... name='animal')
>>> s.sort_index()
0 lama
1 cow
2 lama
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
With the 'keep' parameter, the selection behaviour of duplicated values
can be changed. The value 'first' keeps the first occurrence for each
set of duplicated entries. The default value of keep is 'first'.
>>> s.drop_duplicates().sort_index()
0 lama
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
The value 'last' for parameter 'keep' keeps the last occurrence for
each set of duplicated entries.
>>> s.drop_duplicates(keep='last').sort_index()
1 cow
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
The value ``False`` for parameter 'keep' discards all sets of
duplicated entries. Setting the value of 'inplace' to ``True`` performs
the operation inplace and returns ``None``.
>>> s.drop_duplicates(keep=False, inplace=True)
>>> s.sort_index()
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
"""
inplace = validate_bool_kwarg(inplace, "inplace")
psdf = self._psdf[[self.name]].drop_duplicates(keep=keep)
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
def reindex(self, index: Optional[Any] = None, fill_value: Optional[Any] = None) -> "Series":
"""
Conform Series to new index with optional filling logic, placing
NA/NaN in locations having no value in the previous index. A new object
is produced.
Parameters
----------
index: array-like, optional
New labels / index to conform to, should be specified using keywords.
Preferably an Index object to avoid duplicating data
fill_value : scalar, default np.NaN
Value to use for missing values. Defaults to NaN, but can be any
"compatible" value.
Returns
-------
Series with changed index.
See Also
--------
Series.reset_index : Remove row labels or move them to new columns.
Examples
--------
Create a series with some fictional data.
>>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
>>> ser = ps.Series([200, 200, 404, 404, 301],
... index=index, name='http_status')
>>> ser
Firefox 200
Chrome 200
Safari 404
IE10 404
Konqueror 301
Name: http_status, dtype: int64
Create a new index and reindex the Series. By default
values in the new index that do not have corresponding
records in the Series are assigned ``NaN``.
>>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',
... 'Chrome']
>>> ser.reindex(new_index).sort_index()
Chrome 200.0
Comodo Dragon NaN
IE10 404.0
Iceweasel NaN
Safari 404.0
Name: http_status, dtype: float64
We can fill in the missing values by passing a value to
the keyword ``fill_value``.
>>> ser.reindex(new_index, fill_value=0).sort_index()
Chrome 200
Comodo Dragon 0
IE10 404
Iceweasel 0
Safari 404
Name: http_status, dtype: int64
To further illustrate the filling functionality in
``reindex``, we will create a Series with a
monotonically increasing index (for example, a sequence
of dates).
>>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')
>>> ser2 = ps.Series([100, 101, np.nan, 100, 89, 88],
... name='prices', index=date_index)
>>> ser2.sort_index()
2010-01-01 100.0
2010-01-02 101.0
2010-01-03 NaN
2010-01-04 100.0
2010-01-05 89.0
2010-01-06 88.0
Name: prices, dtype: float64
Suppose we decide to expand the series to cover a wider
date range.
>>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')
>>> ser2.reindex(date_index2).sort_index()
2009-12-29 NaN
2009-12-30 NaN
2009-12-31 NaN
2010-01-01 100.0
2010-01-02 101.0
2010-01-03 NaN
2010-01-04 100.0
2010-01-05 89.0
2010-01-06 88.0
2010-01-07 NaN
Name: prices, dtype: float64
"""
return first_series(self.to_frame().reindex(index=index, fill_value=fill_value)).rename(
self.name
)
def reindex_like(self, other: Union["Series", "DataFrame"]) -> "Series":
"""
Return a Series with matching indices as other object.
Conform the object to the same index on all axes. Places NA/NaN in locations
having no value in the previous index.
Parameters
----------
other : Series or DataFrame
Its row and column indices are used to define the new indices
of this object.
Returns
-------
Series
Series with changed indices on each axis.
See Also
--------
DataFrame.set_index : Set row labels.
DataFrame.reset_index : Remove row labels or move them to new columns.
DataFrame.reindex : Change to new indices or expand indices.
Notes
-----
Same as calling
``.reindex(index=other.index, ...)``.
Examples
--------
>>> s1 = ps.Series([24.3, 31.0, 22.0, 35.0],
... index=pd.date_range(start='2014-02-12',
... end='2014-02-15', freq='D'),
... name="temp_celsius")
>>> s1
2014-02-12 24.3
2014-02-13 31.0
2014-02-14 22.0
2014-02-15 35.0
Name: temp_celsius, dtype: float64
>>> s2 = ps.Series(["low", "low", "medium"],
... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',
... '2014-02-15']),
... name="winspeed")
>>> s2
2014-02-12 low
2014-02-13 low
2014-02-15 medium
Name: winspeed, dtype: object
>>> s2.reindex_like(s1).sort_index()
2014-02-12 low
2014-02-13 low
2014-02-14 None
2014-02-15 medium
Name: winspeed, dtype: object
"""
if isinstance(other, (Series, DataFrame)):
return self.reindex(index=other.index)
else:
raise TypeError("other must be a pandas-on-Spark Series or DataFrame")
def fillna(
self,
value: Optional[Any] = None,
method: Optional[str] = None,
axis: Optional[Axis] = None,
inplace: bool = False,
limit: Optional[int] = None,
) -> Optional["Series"]:
"""Fill NA/NaN values.
.. note:: the current implementation of 'method' parameter in fillna uses Spark's Window
without specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
value : scalar, dict, Series
Value to use to fill holes. alternately a dict/Series of values
specifying which value to use for each column.
DataFrame is not supported.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series pad / ffill: propagate last valid
observation forward to next valid backfill / bfill:
use NEXT valid observation to fill gap
axis : {0 or `index`}
1 and `columns` are not supported.
inplace : boolean, default False
Fill in place (do not create a new object)
limit : int, default None
If method is specified, this is the maximum number of consecutive NaN values to
forward/backward fill. In other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. If method is not specified,
this is the maximum number of entries along the entire axis where NaNs will be filled.
Must be greater than 0 if not None
Returns
-------
Series
Series with NA entries filled.
Examples
--------
>>> s = ps.Series([np.nan, 2, 3, 4, np.nan, 6], name='x')
>>> s
0 NaN
1 2.0
2 3.0
3 4.0
4 NaN
5 6.0
Name: x, dtype: float64
Replace all NaN elements with 0s.
>>> s.fillna(0)
0 0.0
1 2.0
2 3.0
3 4.0
4 0.0
5 6.0
Name: x, dtype: float64
We can also propagate non-null values forward or backward.
>>> s.fillna(method='ffill')
0 NaN
1 2.0
2 3.0
3 4.0
4 4.0
5 6.0
Name: x, dtype: float64
>>> s = ps.Series([np.nan, 'a', 'b', 'c', np.nan], name='x')
>>> s.fillna(method='ffill')
0 None
1 a
2 b
3 c
4 c
Name: x, dtype: object
"""
psser = self._fillna(value=value, method=method, axis=axis, limit=limit)
if method is not None:
psser = DataFrame(psser._psdf._internal.resolved_copy)._psser_for(self._column_label)
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
self._psdf._update_internal_frame(psser._psdf._internal, requires_same_anchor=False)
return None
else:
return psser._with_new_scol(psser.spark.column) # TODO: dtype?
def _fillna(
self,
value: Optional[Any] = None,
method: Optional[str] = None,
axis: Optional[Axis] = None,
limit: Optional[int] = None,
part_cols: Sequence["ColumnOrName"] = (),
) -> "Series":
axis = validate_axis(axis)
if axis != 0:
raise NotImplementedError("fillna currently only works for axis=0 or axis='index'")
if (value is None) and (method is None):
raise ValueError("Must specify a fillna 'value' or 'method' parameter.")
if (method is not None) and (method not in ["ffill", "pad", "backfill", "bfill"]):
raise ValueError("Expecting 'pad', 'ffill', 'backfill' or 'bfill'.")
scol = self.spark.column
if isinstance(self.spark.data_type, (FloatType, DoubleType)):
cond = scol.isNull() | F.isnan(scol)
else:
if not self.spark.nullable:
return self.copy()
cond = scol.isNull()
if value is not None:
if not isinstance(value, (float, int, str, bool)):
raise TypeError("Unsupported type %s" % type(value).__name__)
if limit is not None:
raise ValueError("limit parameter for value is not support now")
scol = F.when(cond, value).otherwise(scol)
else:
if method in ["ffill", "pad"]:
func = F.last
end = Window.currentRow - 1
if limit is not None:
begin = Window.currentRow - limit
else:
begin = Window.unboundedPreceding
elif method in ["bfill", "backfill"]:
func = F.first
begin = Window.currentRow + 1
if limit is not None:
end = Window.currentRow + limit
else:
end = Window.unboundedFollowing
window = (
Window.partitionBy(*part_cols)
.orderBy(NATURAL_ORDER_COLUMN_NAME)
.rowsBetween(begin, end)
)
scol = F.when(cond, func(scol, True).over(window)).otherwise(scol)
return DataFrame(
self._psdf._internal.with_new_spark_column(
self._column_label, scol.alias(name_like_string(self.name)) # TODO: dtype?
)
)._psser_for(self._column_label)
def dropna(self, axis: Axis = 0, inplace: bool = False, **kwargs: Any) -> Optional["Series"]:
"""
Return a new Series with missing values removed.
Parameters
----------
axis : {0 or 'index'}, default 0
There is only one axis to drop values from.
inplace : bool, default False
If True, do operation inplace and return None.
**kwargs
Not in use.
Returns
-------
Series
Series with NA entries dropped from it.
Examples
--------
>>> ser = ps.Series([1., 2., np.nan])
>>> ser
0 1.0
1 2.0
2 NaN
dtype: float64
Drop NA values from a Series.
>>> ser.dropna()
0 1.0
1 2.0
dtype: float64
Keep the Series with valid entries in the same variable.
>>> ser.dropna(inplace=True)
>>> ser
0 1.0
1 2.0
dtype: float64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
# TODO: last two examples from pandas produce different results.
psdf = self._psdf[[self.name]].dropna(axis=axis, inplace=False)
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
def clip(self, lower: Union[float, int] = None, upper: Union[float, int] = None) -> "Series":
"""
Trim values at input threshold(s).
Assigns values outside boundary to boundary values.
Parameters
----------
lower : float or int, default None
Minimum threshold value. All values below this threshold will be set to it.
upper : float or int, default None
Maximum threshold value. All values above this threshold will be set to it.
Returns
-------
Series
Series with the values outside the clip boundaries replaced
Examples
--------
>>> ps.Series([0, 2, 4]).clip(1, 3)
0 1
1 2
2 3
dtype: int64
Notes
-----
One difference between this implementation and pandas is that running
`pd.Series(['a', 'b']).clip(0, 1)` will crash with "TypeError: '<=' not supported between
instances of 'str' and 'int'" while `ps.Series(['a', 'b']).clip(0, 1)` will output the
original Series, simply ignoring the incompatible types.
"""
if is_list_like(lower) or is_list_like(upper):
raise TypeError(
"List-like value are not supported for 'lower' and 'upper' at the " + "moment"
)
if lower is None and upper is None:
return self
if isinstance(self.spark.data_type, NumericType):
scol = self.spark.column
if lower is not None:
scol = F.when(scol < lower, lower).otherwise(scol)
if upper is not None:
scol = F.when(scol > upper, upper).otherwise(scol)
return self._with_new_scol(
scol.alias(self._internal.data_spark_column_names[0]),
field=self._internal.data_fields[0],
)
else:
return self
def drop(
self,
labels: Optional[Union[Name, List[Name]]] = None,
index: Optional[Union[Name, List[Name]]] = None,
level: Optional[int] = None,
) -> "Series":
"""
Return Series with specified index labels removed.
Remove elements of a Series based on specifying the index labels.
When using a multi-index, labels on different levels can be removed by specifying the level.
Parameters
----------
labels : single label or list-like
Index labels to drop.
index : None
Redundant for application on Series, but index can be used instead of labels.
level : int or level name, optional
For MultiIndex, level for which the labels will be removed.
Returns
-------
Series
Series with specified index labels removed.
See Also
--------
Series.dropna
Examples
--------
>>> s = ps.Series(data=np.arange(3), index=['A', 'B', 'C'])
>>> s
A 0
B 1
C 2
dtype: int64
Drop single label A
>>> s.drop('A')
B 1
C 2
dtype: int64
Drop labels B and C
>>> s.drop(labels=['B', 'C'])
A 0
dtype: int64
With 'index' rather than 'labels' returns exactly same result.
>>> s.drop(index='A')
B 1
C 2
dtype: int64
>>> s.drop(index=['B', 'C'])
A 0
dtype: int64
Also support for MultiIndex
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
lama speed 45.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.drop(labels='weight', level=1)
lama speed 45.0
length 1.2
cow speed 30.0
length 1.5
falcon speed 320.0
length 0.3
dtype: float64
>>> s.drop(('lama', 'weight'))
lama speed 45.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.drop([('lama', 'speed'), ('falcon', 'weight')])
lama weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
length 0.3
dtype: float64
"""
return first_series(self._drop(labels=labels, index=index, level=level))
def _drop(
self,
labels: Optional[Union[Name, List[Name]]] = None,
index: Optional[Union[Name, List[Name]]] = None,
level: Optional[int] = None,
) -> DataFrame:
if labels is not None:
if index is not None:
raise ValueError("Cannot specify both 'labels' and 'index'")
return self._drop(index=labels, level=level)
if index is not None:
internal = self._internal
if level is None:
level = 0
if level >= internal.index_level:
raise ValueError("'level' should be less than the number of indexes")
if is_name_like_tuple(index): # type: ignore
index_list = [cast(Label, index)]
elif is_name_like_value(index):
index_list = [(index,)]
elif all(is_name_like_value(idxes, allow_tuple=False) for idxes in index):
index_list = [(idex,) for idex in index]
elif not all(is_name_like_tuple(idxes) for idxes in index):
raise ValueError(
"If the given index is a list, it "
"should only contains names as all tuples or all non tuples "
"that contain index names"
)
else:
index_list = cast(List[Label], index)
drop_index_scols = []
for idxes in index_list:
try:
index_scols = [
internal.index_spark_columns[lvl] == idx
for lvl, idx in enumerate(idxes, level)
]
except IndexError:
raise KeyError(
"Key length ({}) exceeds index depth ({})".format(
internal.index_level, len(idxes)
)
)
drop_index_scols.append(reduce(lambda x, y: x & y, index_scols))
cond = ~reduce(lambda x, y: x | y, drop_index_scols)
return DataFrame(internal.with_filter(cond))
else:
raise ValueError("Need to specify at least one of 'labels' or 'index'")
def head(self, n: int = 5) -> "Series":
"""
Return the first n rows.
This function returns the first n rows for the object based on position.
It is useful for quickly testing if your object has the right type of data in it.
Parameters
----------
n : Integer, default = 5
Returns
-------
The first n rows of the caller object.
Examples
--------
>>> df = ps.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion']})
>>> df.animal.head(2) # doctest: +NORMALIZE_WHITESPACE
0 alligator
1 bee
Name: animal, dtype: object
"""
return first_series(self.to_frame().head(n)).rename(self.name)
def last(self, offset: Union[str, DateOffset]) -> "Series":
"""
Select final periods of time series data based on a date offset.
When having a Series with dates as index, this function can
select the last few elements based on a date offset.
Parameters
----------
offset : str or DateOffset
The offset length of the data that will be selected. For instance,
'3D' will display all the rows having their index within the last 3 days.
Returns
-------
Series
A subset of the caller.
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
Examples
--------
>>> index = pd.date_range('2018-04-09', periods=4, freq='2D')
>>> psser = ps.Series([1, 2, 3, 4], index=index)
>>> psser
2018-04-09 1
2018-04-11 2
2018-04-13 3
2018-04-15 4
dtype: int64
Get the rows for the last 3 days:
>>> psser.last('3D')
2018-04-13 3
2018-04-15 4
dtype: int64
Notice the data for 3 last calendar days were returned, not the last
3 observed days in the dataset, and therefore data for 2018-04-11 was
not returned.
"""
return first_series(self.to_frame().last(offset)).rename(self.name)
def first(self, offset: Union[str, DateOffset]) -> "Series":
"""
Select first periods of time series data based on a date offset.
When having a Series with dates as index, this function can
select the first few elements based on a date offset.
Parameters
----------
offset : str or DateOffset
The offset length of the data that will be selected. For instance,
'3D' will display all the rows having their index within the first 3 days.
Returns
-------
Series
A subset of the caller.
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
Examples
--------
>>> index = pd.date_range('2018-04-09', periods=4, freq='2D')
>>> psser = ps.Series([1, 2, 3, 4], index=index)
>>> psser
2018-04-09 1
2018-04-11 2
2018-04-13 3
2018-04-15 4
dtype: int64
Get the rows for the first 3 days:
>>> psser.first('3D')
2018-04-09 1
2018-04-11 2
dtype: int64
Notice the data for 3 first calendar days were returned, not the first
3 observed days in the dataset, and therefore data for 2018-04-13 was
not returned.
"""
return first_series(self.to_frame().first(offset)).rename(self.name)
# TODO: Categorical type isn't supported (due to PySpark's limitation) and
# some doctests related with timestamps were not added.
def unique(self) -> "Series":
"""
Return unique values of Series object.
Uniques are returned in order of appearance. Hash table-based unique,
therefore does NOT sort.
.. note:: This method returns newly created Series whereas pandas returns
the unique values as a NumPy array.
Returns
-------
Returns the unique values as a Series.
See Also
--------
Index.unique
groupby.SeriesGroupBy.unique
Examples
--------
>>> psser = ps.Series([2, 1, 3, 3], name='A')
>>> psser.unique().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
<BLANKLINE>
... 1
... 2
... 3
Name: A, dtype: int64
>>> ps.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique()
0 2016-01-01
dtype: datetime64[ns]
>>> psser.name = ('x', 'a')
>>> psser.unique().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
<BLANKLINE>
... 1
... 2
... 3
Name: (x, a), dtype: int64
"""
sdf = self._internal.spark_frame.select(self.spark.column).distinct()
internal = InternalFrame(
spark_frame=sdf,
index_spark_columns=None,
column_labels=[self._column_label],
data_spark_columns=[scol_for(sdf, self._internal.data_spark_column_names[0])],
data_fields=[self._internal.data_fields[0]],
column_label_names=self._internal.column_label_names,
)
return first_series(DataFrame(internal))
def sort_values(
self, ascending: bool = True, inplace: bool = False, na_position: str = "last"
) -> Optional["Series"]:
"""
Sort by the values.
Sort a Series in ascending or descending order by some criterion.
Parameters
----------
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders. If this is a list of bools, must match the length of
the by.
inplace : bool, default False
if True, perform operation in-place
na_position : {'first', 'last'}, default 'last'
`first` puts NaNs at the beginning, `last` puts NaNs at the end
Returns
-------
sorted_obj : Series ordered by values.
Examples
--------
>>> s = ps.Series([np.nan, 1, 3, 10, 5])
>>> s
0 NaN
1 1.0
2 3.0
3 10.0
4 5.0
dtype: float64
Sort values ascending order (default behaviour)
>>> s.sort_values(ascending=True)
1 1.0
2 3.0
4 5.0
3 10.0
0 NaN
dtype: float64
Sort values descending order
>>> s.sort_values(ascending=False)
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values inplace
>>> s.sort_values(ascending=False, inplace=True)
>>> s
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values putting NAs first
>>> s.sort_values(na_position='first')
0 NaN
1 1.0
2 3.0
4 5.0
3 10.0
dtype: float64
Sort a series of strings
>>> s = ps.Series(['z', 'b', 'd', 'a', 'c'])
>>> s
0 z
1 b
2 d
3 a
4 c
dtype: object
>>> s.sort_values()
3 a
1 b
4 c
2 d
0 z
dtype: object
"""
inplace = validate_bool_kwarg(inplace, "inplace")
psdf = self._psdf[[self.name]]._sort(
by=[self.spark.column], ascending=ascending, na_position=na_position
)
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
def sort_index(
self,
axis: Axis = 0,
level: Optional[Union[int, List[int]]] = None,
ascending: bool = True,
inplace: bool = False,
kind: str = None,
na_position: str = "last",
) -> Optional["Series"]:
"""
Sort object by labels (along an axis)
Parameters
----------
axis : index, columns to direct sorting. Currently, only axis = 0 is supported.
level : int or level name or list of ints or list of level names
if not None, sort on values in specified index level(s)
ascending : boolean, default True
Sort ascending vs. descending
inplace : bool, default False
if True, perform operation in-place
kind : str, default None
pandas-on-Spark does not allow specifying the sorting algorithm at the moment,
default None
na_position : {‘first’, ‘last’}, default ‘last’
first puts NaNs at the beginning, last puts NaNs at the end. Not implemented for
MultiIndex.
Returns
-------
sorted_obj : Series
Examples
--------
>>> df = ps.Series([2, 1, np.nan], index=['b', 'a', np.nan])
>>> df.sort_index()
a 1.0
b 2.0
NaN NaN
dtype: float64
>>> df.sort_index(ascending=False)
b 2.0
a 1.0
NaN NaN
dtype: float64
>>> df.sort_index(na_position='first')
NaN NaN
a 1.0
b 2.0
dtype: float64
>>> df.sort_index(inplace=True)
>>> df
a 1.0
b 2.0
NaN NaN
dtype: float64
>>> df = ps.Series(range(4), index=[['b', 'b', 'a', 'a'], [1, 0, 1, 0]], name='0')
>>> df.sort_index()
a 0 3
1 2
b 0 1
1 0
Name: 0, dtype: int64
>>> df.sort_index(level=1) # doctest: +SKIP
a 0 3
b 0 1
a 1 2
b 1 0
Name: 0, dtype: int64
>>> df.sort_index(level=[1, 0])
a 0 3
b 0 1
a 1 2
b 1 0
Name: 0, dtype: int64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
psdf = self._psdf[[self.name]].sort_index(
axis=axis, level=level, ascending=ascending, kind=kind, na_position=na_position
)
if inplace:
self._update_anchor(psdf)
return None
else:
return first_series(psdf)
def swaplevel(
self, i: Union[int, Name] = -2, j: Union[int, Name] = -1, copy: bool = True
) -> "Series":
"""
Swap levels i and j in a MultiIndex.
Default is to swap the two innermost levels of the index.
Parameters
----------
i, j : int, str
Level of the indices to be swapped. Can pass level name as string.
copy : bool, default True
Whether to copy underlying data. Must be True.
Returns
-------
Series
Series with levels swapped in MultiIndex.
Examples
--------
>>> midx = pd.MultiIndex.from_arrays([['a', 'b'], [1, 2]], names = ['word', 'number'])
>>> midx # doctest: +SKIP
MultiIndex([('a', 1),
('b', 2)],
names=['word', 'number'])
>>> psser = ps.Series(['x', 'y'], index=midx)
>>> psser
word number
a 1 x
b 2 y
dtype: object
>>> psser.swaplevel()
number word
1 a x
2 b y
dtype: object
>>> psser.swaplevel(0, 1)
number word
1 a x
2 b y
dtype: object
>>> psser.swaplevel('number', 'word')
number word
1 a x
2 b y
dtype: object
"""
assert copy is True
return first_series(self.to_frame().swaplevel(i, j, axis=0)).rename(self.name)
def swapaxes(self, i: Axis, j: Axis, copy: bool = True) -> "Series":
"""
Interchange axes and swap values axes appropriately.
Parameters
----------
i: {0 or 'index', 1 or 'columns'}. The axis to swap.
j: {0 or 'index', 1 or 'columns'}. The axis to swap.
copy : bool, default True.
Returns
-------
Series
Examples
--------
>>> psser = ps.Series([1, 2, 3], index=["x", "y", "z"])
>>> psser
x 1
y 2
z 3
dtype: int64
>>>
>>> psser.swapaxes(0, 0)
x 1
y 2
z 3
dtype: int64
"""
assert copy is True
i = validate_axis(i)
j = validate_axis(j)
if not i == j == 0:
raise ValueError("Axis must be 0 for Series")
return self.copy()
def add_prefix(self, prefix: str) -> "Series":
"""
Prefix labels with string `prefix`.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Parameters
----------
prefix : str
The string to add before each label.
Returns
-------
Series
New Series with updated labels.
See Also
--------
Series.add_suffix: Suffix column labels with string `suffix`.
DataFrame.add_suffix: Suffix column labels with string `suffix`.
DataFrame.add_prefix: Prefix column labels with string `prefix`.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_prefix('item_')
item_0 1
item_1 2
item_2 3
item_3 4
dtype: int64
"""
assert isinstance(prefix, str)
internal = self._internal.resolved_copy
sdf = internal.spark_frame.select(
[
F.concat(SF.lit(prefix), index_spark_column).alias(index_spark_column_name)
for index_spark_column, index_spark_column_name in zip(
internal.index_spark_columns, internal.index_spark_column_names
)
]
+ internal.data_spark_columns
)
return first_series(
DataFrame(internal.with_new_sdf(sdf, index_fields=([None] * internal.index_level)))
)
def add_suffix(self, suffix: str) -> "Series":
"""
Suffix labels with string suffix.
For Series, the row labels are suffixed.
For DataFrame, the column labels are suffixed.
Parameters
----------
suffix : str
The string to add after each label.
Returns
-------
Series
New Series with updated labels.
See Also
--------
Series.add_prefix: Prefix row labels with string `prefix`.
DataFrame.add_prefix: Prefix column labels with string `prefix`.
DataFrame.add_suffix: Suffix column labels with string `suffix`.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_suffix('_item')
0_item 1
1_item 2
2_item 3
3_item 4
dtype: int64
"""
assert isinstance(suffix, str)
internal = self._internal.resolved_copy
sdf = internal.spark_frame.select(
[
F.concat(index_spark_column, SF.lit(suffix)).alias(index_spark_column_name)
for index_spark_column, index_spark_column_name in zip(
internal.index_spark_columns, internal.index_spark_column_names
)
]
+ internal.data_spark_columns
)
return first_series(
DataFrame(internal.with_new_sdf(sdf, index_fields=([None] * internal.index_level)))
)
def corr(self, other: "Series", method: str = "pearson") -> float:
"""
Compute correlation with `other` Series, excluding missing values.
Parameters
----------
other : Series
method : {'pearson', 'spearman'}
* pearson : standard correlation coefficient
* spearman : Spearman rank correlation
Returns
-------
correlation : float
Examples
--------
>>> df = ps.DataFrame({'s1': [.2, .0, .6, .2],
... 's2': [.3, .6, .0, .1]})
>>> s1 = df.s1
>>> s2 = df.s2
>>> s1.corr(s2, method='pearson') # doctest: +ELLIPSIS
-0.851064...
>>> s1.corr(s2, method='spearman') # doctest: +ELLIPSIS
-0.948683...
Notes
-----
There are behavior differences between pandas-on-Spark and pandas.
* the `method` argument only accepts 'pearson', 'spearman'
* the data should not contain NaNs. pandas-on-Spark will return an error.
* pandas-on-Spark doesn't support the following argument(s).
* `min_periods` argument is not supported
"""
# This implementation is suboptimal because it computes more than necessary,
# but it should be a start
columns = ["__corr_arg1__", "__corr_arg2__"]
psdf = self._psdf.assign(__corr_arg1__=self, __corr_arg2__=other)[columns]
psdf.columns = columns
c = corr(psdf, method=method)
return c.loc[tuple(columns)]
def nsmallest(self, n: int = 5) -> "Series":
"""
Return the smallest `n` elements.
Parameters
----------
n : int, default 5
Return this many ascending sorted values.
Returns
-------
Series
The `n` smallest values in the Series, sorted in increasing order.
See Also
--------
Series.nlargest: Get the `n` largest elements.
Series.sort_values: Sort Series by values.
Series.head: Return the first `n` rows.
Notes
-----
Faster than ``.sort_values().head(n)`` for small `n` relative to
the size of the ``Series`` object.
In pandas-on-Spark, thanks to Spark's lazy execution and query optimizer,
the two would have same performance.
Examples
--------
>>> data = [1, 2, 3, 4, np.nan ,6, 7, 8]
>>> s = ps.Series(data)
>>> s
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
5 6.0
6 7.0
7 8.0
dtype: float64
The `n` largest elements where ``n=5`` by default.
>>> s.nsmallest()
0 1.0
1 2.0
2 3.0
3 4.0
5 6.0
dtype: float64
>>> s.nsmallest(3)
0 1.0
1 2.0
2 3.0
dtype: float64
"""
return self.sort_values(ascending=True).head(n)
def nlargest(self, n: int = 5) -> "Series":
"""
Return the largest `n` elements.
Parameters
----------
n : int, default 5
Returns
-------
Series
The `n` largest values in the Series, sorted in decreasing order.
See Also
--------
Series.nsmallest: Get the `n` smallest elements.
Series.sort_values: Sort Series by values.
Series.head: Return the first `n` rows.
Notes
-----
Faster than ``.sort_values(ascending=False).head(n)`` for small `n`
relative to the size of the ``Series`` object.
In pandas-on-Spark, thanks to Spark's lazy execution and query optimizer,
the two would have same performance.
Examples
--------
>>> data = [1, 2, 3, 4, np.nan ,6, 7, 8]
>>> s = ps.Series(data)
>>> s
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
5 6.0
6 7.0
7 8.0
dtype: float64
The `n` largest elements where ``n=5`` by default.
>>> s.nlargest()
7 8.0
6 7.0
5 6.0
3 4.0
2 3.0
dtype: float64
>>> s.nlargest(n=3)
7 8.0
6 7.0
5 6.0
dtype: float64
"""
return self.sort_values(ascending=False).head(n)
def append(
self, to_append: "Series", ignore_index: bool = False, verify_integrity: bool = False
) -> "Series":
"""
Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
ignore_index : boolean, default False
If True, do not use the index labels.
verify_integrity : boolean, default False
If True, raise Exception on creating index with duplicates
Returns
-------
appended : Series
Examples
--------
>>> s1 = ps.Series([1, 2, 3])
>>> s2 = ps.Series([4, 5, 6])
>>> s3 = ps.Series([4, 5, 6], index=[3,4,5])
>>> s1.append(s2)
0 1
1 2
2 3
0 4
1 5
2 6
dtype: int64
>>> s1.append(s3)
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
With ignore_index set to True:
>>> s1.append(s2, ignore_index=True)
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
"""
return first_series(
self.to_frame().append(to_append.to_frame(), ignore_index, verify_integrity)
).rename(self.name)
def sample(
self,
n: Optional[int] = None,
frac: Optional[float] = None,
replace: bool = False,
random_state: Optional[int] = None,
) -> "Series":
return first_series(
self.to_frame().sample(n=n, frac=frac, replace=replace, random_state=random_state)
).rename(self.name)
sample.__doc__ = DataFrame.sample.__doc__
@no_type_check
def hist(self, bins=10, **kwds):
return self.plot.hist(bins, **kwds)
hist.__doc__ = PandasOnSparkPlotAccessor.hist.__doc__
def apply(self, func: Callable, args: Sequence[Any] = (), **kwds: Any) -> "Series":
"""
Invoke function on values of Series.
Can be a Python function that only works on the Series.
.. note:: this API executes the function once to infer the type which is
potentially expensive, for instance, when the dataset is created after
aggregations or sorting.
To avoid this, specify return type in ``func``, for instance, as below:
>>> def square(x) -> np.int32:
... return x ** 2
pandas-on-Spark uses return type hint and does not try to infer the type.
Parameters
----------
func : function
Python function to apply. Note that type hint for return type is required.
args : tuple
Positional arguments passed to func after the series value.
**kwds
Additional keyword arguments passed to func.
Returns
-------
Series
See Also
--------
Series.aggregate : Only perform aggregating type operations.
Series.transform : Only perform transforming type operations.
DataFrame.apply : The equivalent function for DataFrame.
Examples
--------
Create a Series with typical summer temperatures for each city.
>>> s = ps.Series([20, 21, 12],
... index=['London', 'New York', 'Helsinki'])
>>> s
London 20
New York 21
Helsinki 12
dtype: int64
Square the values by defining a function and passing it as an
argument to ``apply()``.
>>> def square(x) -> np.int64:
... return x ** 2
>>> s.apply(square)
London 400
New York 441
Helsinki 144
dtype: int64
Define a custom function that needs additional positional
arguments and pass these additional arguments using the
``args`` keyword
>>> def subtract_custom_value(x, custom_value) -> np.int64:
... return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,))
London 15
New York 16
Helsinki 7
dtype: int64
Define a custom function that takes keyword arguments
and pass these arguments to ``apply``
>>> def add_custom_values(x, **kwargs) -> np.int64:
... for month in kwargs:
... x += kwargs[month]
... return x
>>> s.apply(add_custom_values, june=30, july=20, august=25)
London 95
New York 96
Helsinki 87
dtype: int64
Use a function from the Numpy library
>>> def numpy_log(col) -> np.float64:
... return np.log(col)
>>> s.apply(numpy_log)
London 2.995732
New York 3.044522
Helsinki 2.484907
dtype: float64
You can omit the type hint and let pandas-on-Spark infer its type.
>>> s.apply(np.log)
London 2.995732
New York 3.044522
Helsinki 2.484907
dtype: float64
"""
assert callable(func), "the first argument should be a callable function."
try:
spec = inspect.getfullargspec(func)
return_sig = spec.annotations.get("return", None)
should_infer_schema = return_sig is None
except TypeError:
# Falls back to schema inference if it fails to get signature.
should_infer_schema = True
apply_each = wraps(func)(lambda s: s.apply(func, args=args, **kwds))
if should_infer_schema:
return self.pandas_on_spark._transform_batch(apply_each, None)
else:
sig_return = infer_return_type(func)
if not isinstance(sig_return, ScalarType):
raise ValueError(
"Expected the return type of this function to be of scalar type, "
"but found type {}".format(sig_return)
)
return_type = cast(ScalarType, sig_return)
return self.pandas_on_spark._transform_batch(apply_each, return_type)
# TODO: not all arguments are implemented comparing to pandas' for now.
def aggregate(self, func: Union[str, List[str]]) -> Union[Scalar, "Series"]:
"""Aggregate using one or more operations over the specified axis.
Parameters
----------
func : str or a list of str
function name(s) as string apply to series.
Returns
-------
scalar, Series
The return can be:
- scalar : when Series.agg is called with single function
- Series : when Series.agg is called with several functions
Notes
-----
`agg` is an alias for `aggregate`. Use the alias.
See Also
--------
Series.apply : Invoke function on a Series.
Series.transform : Only perform transforming type operations.
Series.groupby : Perform operations over groups.
DataFrame.aggregate : The equivalent function for DataFrame.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4])
>>> s.agg('min')
1
>>> s.agg(['min', 'max']).sort_index()
max 4
min 1
dtype: int64
"""
if isinstance(func, list):
return first_series(self.to_frame().aggregate(func)).rename(self.name)
elif isinstance(func, str):
return getattr(self, func)()
else:
raise TypeError("func must be a string or list of strings")
agg = aggregate
def transpose(self, *args: Any, **kwargs: Any) -> "Series":
"""
Return the transpose, which is by definition self.
Examples
--------
It returns the same object as the transpose of the given series object, which is by
definition self.
>>> s = ps.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.transpose()
0 1
1 2
2 3
dtype: int64
"""
return self.copy()
T = property(transpose)
def transform(
self, func: Union[Callable, List[Callable]], axis: Axis = 0, *args: Any, **kwargs: Any
) -> Union["Series", DataFrame]:
"""
Call ``func`` producing the same type as `self` with transformed values
and that has the same axis length as input.
.. note:: this API executes the function once to infer the type which is
potentially expensive, for instance, when the dataset is created after
aggregations or sorting.
To avoid this, specify return type in ``func``, for instance, as below:
>>> def square(x) -> np.int32:
... return x ** 2
pandas-on-Spark uses return type hint and does not try to infer the type.
Parameters
----------
func : function or list
A function or a list of functions to use for transforming the data.
axis : int, default 0 or 'index'
Can only be set to 0 at the moment.
*args
Positional arguments to pass to `func`.
**kwargs
Keyword arguments to pass to `func`.
Returns
-------
An instance of the same type with `self` that must have the same length as input.
See Also
--------
Series.aggregate : Only perform aggregating type operations.
Series.apply : Invoke function on Series.
DataFrame.transform : The equivalent function for DataFrame.
Examples
--------
>>> s = ps.Series(range(3))
>>> s
0 0
1 1
2 2
dtype: int64
>>> def sqrt(x) -> float:
... return np.sqrt(x)
>>> s.transform(sqrt)
0 0.000000
1 1.000000
2 1.414214
dtype: float64
Even though the resulting instance must have the same length as the
input, it is possible to provide several input functions:
>>> def exp(x) -> float:
... return np.exp(x)
>>> s.transform([sqrt, exp])
sqrt exp
0 0.000000 1.000000
1 1.000000 2.718282
2 1.414214 7.389056
You can omit the type hint and let pandas-on-Spark infer its type.
>>> s.transform([np.sqrt, np.exp])
sqrt exp
0 0.000000 1.000000
1 1.000000 2.718282
2 1.414214 7.389056
"""
axis = validate_axis(axis)
if axis != 0:
raise NotImplementedError('axis should be either 0 or "index" currently.')
if isinstance(func, list):
applied = []
for f in func:
applied.append(self.apply(f, args=args, **kwargs).rename(f.__name__))
internal = self._internal.with_new_columns(applied)
return DataFrame(internal)
else:
return self.apply(func, args=args, **kwargs)
def round(self, decimals: int = 0) -> "Series":
"""
Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int
Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of
positions to the left of the decimal point.
Returns
-------
Series object
See Also
--------
DataFrame.round
Examples
--------
>>> df = ps.Series([0.028208, 0.038683, 0.877076], name='x')
>>> df
0 0.028208
1 0.038683
2 0.877076
Name: x, dtype: float64
>>> df.round(2)
0 0.03
1 0.04
2 0.88
Name: x, dtype: float64
"""
if not isinstance(decimals, int):
raise TypeError("decimals must be an integer")
scol = F.round(self.spark.column, decimals)
return self._with_new_scol(scol) # TODO: dtype?
# TODO: add 'interpolation' parameter.
def quantile(
self, q: Union[float, Iterable[float]] = 0.5, accuracy: int = 10000
) -> Union[Scalar, "Series"]:
"""
Return value at the given quantile.
.. note:: Unlike pandas', the quantile in pandas-on-Spark is an approximated quantile
based upon approximate percentile computation because computing quantile across
a large dataset is extremely expensive.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
0 <= q <= 1, the quantile(s) to compute.
accuracy : int, optional
Default accuracy of approximation. Larger value means better accuracy.
The relative error can be deduced by 1.0 / accuracy.
Returns
-------
float or Series
If the current object is a Series and ``q`` is an array, a Series will be
returned where the index is ``q`` and the values are the quantiles, otherwise
a float will be returned.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4, 5])
>>> s.quantile(.5)
3.0
>>> (s + 1).quantile(.5)
4.0
>>> s.quantile([.25, .5, .75])
0.25 2.0
0.50 3.0
0.75 4.0
dtype: float64
>>> (s + 1).quantile([.25, .5, .75])
0.25 3.0
0.50 4.0
0.75 5.0
dtype: float64
"""
if isinstance(q, Iterable):
return first_series(
self.to_frame().quantile(q=q, axis=0, numeric_only=False, accuracy=accuracy)
).rename(self.name)
else:
if not isinstance(accuracy, int):
raise TypeError(
"accuracy must be an integer; however, got [%s]" % type(accuracy).__name__
)
if not isinstance(q, float):
raise TypeError(
"q must be a float or an array of floats; however, [%s] found." % type(q)
)
q_float = cast(float, q)
if q_float < 0.0 or q_float > 1.0:
raise ValueError("percentiles should all be in the interval [0, 1].")
def quantile(spark_column: Column, spark_type: DataType) -> Column:
if isinstance(spark_type, (BooleanType, NumericType)):
return F.percentile_approx(spark_column.cast(DoubleType()), q_float, accuracy)
else:
raise TypeError(
"Could not convert {} ({}) to numeric".format(
spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()
)
)
return self._reduce_for_stat_function(quantile, name="quantile")
# TODO: add axis, numeric_only, pct, na_option parameter
def rank(self, method: str = "average", ascending: bool = True) -> "Series":
"""
Compute numerical data ranks (1 through n) along axis. Equal values are
assigned a rank that is the average of the ranks of those values.
.. note:: the current implementation of rank uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
method : {'average', 'min', 'max', 'first', 'dense'}
* average: average rank of group
* min: lowest rank in group
* max: highest rank in group
* first: ranks assigned in order they appear in the array
* dense: like 'min', but rank always increases by 1 between groups
ascending : boolean, default True
False for ranks by high (1) to low (N)
Returns
-------
ranks : same type as caller
Examples
--------
>>> s = ps.Series([1, 2, 2, 3], name='A')
>>> s
0 1
1 2
2 2
3 3
Name: A, dtype: int64
>>> s.rank()
0 1.0
1 2.5
2 2.5
3 4.0
Name: A, dtype: float64
If method is set to 'min', it use lowest rank in group.
>>> s.rank(method='min')
0 1.0
1 2.0
2 2.0
3 4.0
Name: A, dtype: float64
If method is set to 'max', it use highest rank in group.
>>> s.rank(method='max')
0 1.0
1 3.0
2 3.0
3 4.0
Name: A, dtype: float64
If method is set to 'first', it is assigned rank in order without groups.
>>> s.rank(method='first')
0 1.0
1 2.0
2 3.0
3 4.0
Name: A, dtype: float64
If method is set to 'dense', it leaves no gaps in group.
>>> s.rank(method='dense')
0 1.0
1 2.0
2 2.0
3 3.0
Name: A, dtype: float64
"""
return self._rank(method, ascending).spark.analyzed
def _rank(
self,
method: str = "average",
ascending: bool = True,
*,
part_cols: Sequence["ColumnOrName"] = ()
) -> "Series":
if method not in ["average", "min", "max", "first", "dense"]:
msg = "method must be one of 'average', 'min', 'max', 'first', 'dense'"
raise ValueError(msg)
if self._internal.index_level > 1:
raise ValueError("rank do not support index now")
if ascending:
asc_func = lambda scol: scol.asc()
else:
asc_func = lambda scol: scol.desc()
if method == "first":
window = (
Window.orderBy(
asc_func(self.spark.column),
asc_func(F.col(NATURAL_ORDER_COLUMN_NAME)),
)
.partitionBy(*part_cols)
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
scol = F.row_number().over(window)
elif method == "dense":
window = (
Window.orderBy(asc_func(self.spark.column))
.partitionBy(*part_cols)
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
scol = F.dense_rank().over(window)
else:
if method == "average":
stat_func = F.mean
elif method == "min":
stat_func = F.min
elif method == "max":
stat_func = F.max
window1 = (
Window.orderBy(asc_func(self.spark.column))
.partitionBy(*part_cols)
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
window2 = Window.partitionBy([self.spark.column] + list(part_cols)).rowsBetween(
Window.unboundedPreceding, Window.unboundedFollowing
)
scol = stat_func(F.row_number().over(window1)).over(window2)
psser = self._with_new_scol(scol)
return psser.astype(np.float64)
def filter(
self,
items: Optional[Sequence[Any]] = None,
like: Optional[str] = None,
regex: Optional[str] = None,
axis: Optional[Axis] = None,
) -> "Series":
axis = validate_axis(axis)
if axis == 1:
raise ValueError("Series does not support columns axis.")
return first_series(
self.to_frame().filter(items=items, like=like, regex=regex, axis=axis)
).rename(self.name)
filter.__doc__ = DataFrame.filter.__doc__
def describe(self, percentiles: Optional[List[float]] = None) -> "Series":
return first_series(self.to_frame().describe(percentiles)).rename(self.name)
describe.__doc__ = DataFrame.describe.__doc__
def diff(self, periods: int = 1) -> "Series":
"""
First discrete difference of element.
Calculates the difference of a Series element compared with another element in the
DataFrame (default is the element in the same column of the previous row).
.. note:: the current implementation of diff uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
periods : int, default 1
Periods to shift for calculating difference, accepts negative values.
Returns
-------
diffed : Series
Examples
--------
>>> df = ps.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [1, 1, 2, 3, 5, 8],
... 'c': [1, 4, 9, 16, 25, 36]}, columns=['a', 'b', 'c'])
>>> df
a b c
0 1 1 1
1 2 1 4
2 3 2 9
3 4 3 16
4 5 5 25
5 6 8 36
>>> df.b.diff()
0 NaN
1 0.0
2 1.0
3 1.0
4 2.0
5 3.0
Name: b, dtype: float64
Difference with previous value
>>> df.c.diff(periods=3)
0 NaN
1 NaN
2 NaN
3 15.0
4 21.0
5 27.0
Name: c, dtype: float64
Difference with following value
>>> df.c.diff(periods=-1)
0 -3.0
1 -5.0
2 -7.0
3 -9.0
4 -11.0
5 NaN
Name: c, dtype: float64
"""
return self._diff(periods).spark.analyzed
def _diff(self, periods: int, *, part_cols: Sequence["ColumnOrName"] = ()) -> "Series":
if not isinstance(periods, int):
raise TypeError("periods should be an int; however, got [%s]" % type(periods).__name__)
window = (
Window.partitionBy(*part_cols)
.orderBy(NATURAL_ORDER_COLUMN_NAME)
.rowsBetween(-periods, -periods)
)
scol = self.spark.column - F.lag(self.spark.column, periods).over(window)
return self._with_new_scol(scol, field=self._internal.data_fields[0].copy(nullable=True))
def idxmax(self, skipna: bool = True) -> Union[Tuple, Any]:
"""
Return the row label of the maximum value.
If multiple values equal the maximum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.
Returns
-------
Index
Label of the maximum value.
Raises
------
ValueError
If the Series is empty.
See Also
--------
Series.idxmin : Return index *label* of the first occurrence
of minimum of values.
Examples
--------
>>> s = ps.Series(data=[1, None, 4, 3, 5],
... index=['A', 'B', 'C', 'D', 'E'])
>>> s
A 1.0
B NaN
C 4.0
D 3.0
E 5.0
dtype: float64
>>> s.idxmax()
'E'
If `skipna` is False and there is an NA value in the data,
the function returns ``nan``.
>>> s.idxmax(skipna=False)
nan
In case of multi-index, you get a tuple:
>>> index = pd.MultiIndex.from_arrays([
... ['a', 'a', 'b', 'b'], ['c', 'd', 'e', 'f']], names=('first', 'second'))
>>> s = ps.Series(data=[1, None, 4, 5], index=index)
>>> s
first second
a c 1.0
d NaN
b e 4.0
f 5.0
dtype: float64
>>> s.idxmax()
('b', 'f')
If multiple values equal the maximum, the first row label with that
value is returned.
>>> s = ps.Series([1, 100, 1, 100, 1, 100], index=[10, 3, 5, 2, 1, 8])
>>> s
10 1
3 100
5 1
2 100
1 1
8 100
dtype: int64
>>> s.idxmax()
3
"""
sdf = self._internal.spark_frame
scol = self.spark.column
index_scols = self._internal.index_spark_columns
# desc_nulls_(last|first) is used via Py4J directly because
# it's not supported in Spark 2.3.
if skipna:
sdf = sdf.orderBy(Column(scol._jc.desc_nulls_last()), NATURAL_ORDER_COLUMN_NAME)
else:
sdf = sdf.orderBy(Column(scol._jc.desc_nulls_first()), NATURAL_ORDER_COLUMN_NAME)
results = sdf.select([scol] + index_scols).take(1)
if len(results) == 0:
raise ValueError("attempt to get idxmin of an empty sequence")
if results[0][0] is None:
# This will only happens when skipna is False because we will
# place nulls first.
return np.nan
values = list(results[0][1:])
if len(values) == 1:
return values[0]
else:
return tuple(values)
def idxmin(self, skipna: bool = True) -> Union[Tuple, Any]:
"""
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.
Returns
-------
Index
Label of the minimum value.
Raises
------
ValueError
If the Series is empty.
See Also
--------
Series.idxmax : Return index *label* of the first occurrence
of maximum of values.
Notes
-----
This method is the Series version of ``ndarray.argmin``. This method
returns the label of the minimum, while ``ndarray.argmin`` returns
the position. To get the position, use ``series.values.argmin()``.
Examples
--------
>>> s = ps.Series(data=[1, None, 4, 0],
... index=['A', 'B', 'C', 'D'])
>>> s
A 1.0
B NaN
C 4.0
D 0.0
dtype: float64
>>> s.idxmin()
'D'
If `skipna` is False and there is an NA value in the data,
the function returns ``nan``.
>>> s.idxmin(skipna=False)
nan
In case of multi-index, you get a tuple:
>>> index = pd.MultiIndex.from_arrays([
... ['a', 'a', 'b', 'b'], ['c', 'd', 'e', 'f']], names=('first', 'second'))
>>> s = ps.Series(data=[1, None, 4, 0], index=index)
>>> s
first second
a c 1.0
d NaN
b e 4.0
f 0.0
dtype: float64
>>> s.idxmin()
('b', 'f')
If multiple values equal the minimum, the first row label with that
value is returned.
>>> s = ps.Series([1, 100, 1, 100, 1, 100], index=[10, 3, 5, 2, 1, 8])
>>> s
10 1
3 100
5 1
2 100
1 1
8 100
dtype: int64
>>> s.idxmin()
10
"""
sdf = self._internal.spark_frame
scol = self.spark.column
index_scols = self._internal.index_spark_columns
# asc_nulls_(last|first)is used via Py4J directly because
# it's not supported in Spark 2.3.
if skipna:
sdf = sdf.orderBy(Column(scol._jc.asc_nulls_last()), NATURAL_ORDER_COLUMN_NAME)
else:
sdf = sdf.orderBy(Column(scol._jc.asc_nulls_first()), NATURAL_ORDER_COLUMN_NAME)
results = sdf.select([scol] + index_scols).take(1)
if len(results) == 0:
raise ValueError("attempt to get idxmin of an empty sequence")
if results[0][0] is None:
# This will only happens when skipna is False because we will
# place nulls first.
return np.nan
values = list(results[0][1:])
if len(values) == 1:
return values[0]
else:
return tuple(values)
def pop(self, item: Name) -> Union["Series", Scalar]:
"""
Return item and drop from series.
Parameters
----------
item : label
Label of index to be popped.
Returns
-------
Value that is popped from series.
Examples
--------
>>> s = ps.Series(data=np.arange(3), index=['A', 'B', 'C'])
>>> s
A 0
B 1
C 2
dtype: int64
>>> s.pop('A')
0
>>> s
B 1
C 2
dtype: int64
>>> s = ps.Series(data=np.arange(3), index=['A', 'A', 'C'])
>>> s
A 0
A 1
C 2
dtype: int64
>>> s.pop('A')
A 0
A 1
dtype: int64
>>> s
C 2
dtype: int64
Also support for MultiIndex
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
lama speed 45.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.pop('lama')
speed 45.0
weight 200.0
length 1.2
dtype: float64
>>> s
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
Also support for MultiIndex with several indexs.
>>> midx = pd.MultiIndex([['a', 'b', 'c'],
... ['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 0, 0, 0, 1, 1, 1],
... [0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 0, 2]]
... )
>>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
a lama speed 45.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
b falcon speed 320.0
speed 1.0
length 0.3
dtype: float64
>>> s.pop(('a', 'lama'))
speed 45.0
weight 200.0
length 1.2
dtype: float64
>>> s
a cow speed 30.0
weight 250.0
length 1.5
b falcon speed 320.0
speed 1.0
length 0.3
dtype: float64
>>> s.pop(('b', 'falcon', 'speed'))
(b, falcon, speed) 320.0
(b, falcon, speed) 1.0
dtype: float64
"""
if not is_name_like_value(item):
raise TypeError("'key' should be string or tuple that contains strings")
if not is_name_like_tuple(item):
item = (item,)
if self._internal.index_level < len(item):
raise KeyError(
"Key length ({}) exceeds index depth ({})".format(
len(item), self._internal.index_level
)
)
internal = self._internal
scols = internal.index_spark_columns[len(item) :] + [self.spark.column]
rows = [internal.spark_columns[level] == index for level, index in enumerate(item)]
sdf = internal.spark_frame.filter(reduce(lambda x, y: x & y, rows)).select(scols)
psdf = self._drop(item)
self._update_anchor(psdf)
if self._internal.index_level == len(item):
# if spark_frame has one column and one data, return data only without frame
pdf = sdf.limit(2).toPandas()
length = len(pdf)
if length == 1:
return pdf[internal.data_spark_column_names[0]].iloc[0]
item_string = name_like_string(item)
sdf = sdf.withColumn(SPARK_DEFAULT_INDEX_NAME, SF.lit(str(item_string)))
internal = InternalFrame(
spark_frame=sdf,
index_spark_columns=[scol_for(sdf, SPARK_DEFAULT_INDEX_NAME)],
column_labels=[self._column_label],
data_fields=[self._internal.data_fields[0]],
)
return first_series(DataFrame(internal))
else:
internal = internal.copy(
spark_frame=sdf,
index_spark_columns=[
scol_for(sdf, col) for col in internal.index_spark_column_names[len(item) :]
],
index_fields=internal.index_fields[len(item) :],
index_names=self._internal.index_names[len(item) :],
data_spark_columns=[scol_for(sdf, internal.data_spark_column_names[0])],
)
return first_series(DataFrame(internal))
def copy(self, deep: bool = True) -> "Series":
"""
Make a copy of this object's indices and data.
Parameters
----------
deep : bool, default True
this parameter is not supported but just dummy parameter to match pandas.
Returns
-------
copy : Series
Examples
--------
>>> s = ps.Series([1, 2], index=["a", "b"])
>>> s
a 1
b 2
dtype: int64
>>> s_copy = s.copy()
>>> s_copy
a 1
b 2
dtype: int64
"""
return self._psdf.copy(deep=deep)._psser_for(self._column_label)
def mode(self, dropna: bool = True) -> "Series":
"""
Return the mode(s) of the dataset.
Always returns Series even if only one value is returned.
Parameters
----------
dropna : bool, default True
Don't consider counts of NaN/NaT.
Returns
-------
Series
Modes of the Series.
Examples
--------
>>> s = ps.Series([0, 0, 1, 1, 1, np.nan, np.nan, np.nan])
>>> s
0 0.0
1 0.0
2 1.0
3 1.0
4 1.0
5 NaN
6 NaN
7 NaN
dtype: float64
>>> s.mode()
0 1.0
dtype: float64
If there are several same modes, all items are shown
>>> s = ps.Series([0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3,
... np.nan, np.nan, np.nan])
>>> s
0 0.0
1 0.0
2 1.0
3 1.0
4 1.0
5 2.0
6 2.0
7 2.0
8 3.0
9 3.0
10 3.0
11 NaN
12 NaN
13 NaN
dtype: float64
>>> s.mode().sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
<BLANKLINE>
... 1.0
... 2.0
... 3.0
dtype: float64
With 'dropna' set to 'False', we can also see NaN in the result
>>> s.mode(False).sort_values() # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
<BLANKLINE>
... 1.0
... 2.0
... 3.0
... NaN
dtype: float64
"""
ser_count = self.value_counts(dropna=dropna, sort=False)
sdf_count = ser_count._internal.spark_frame
most_value = ser_count.max()
sdf_most_value = sdf_count.filter("count == {}".format(most_value))
sdf = sdf_most_value.select(
F.col(SPARK_DEFAULT_INDEX_NAME).alias(SPARK_DEFAULT_SERIES_NAME)
)
internal = InternalFrame(spark_frame=sdf, index_spark_columns=None, column_labels=[None])
return first_series(DataFrame(internal))
def keys(self) -> "ps.Index":
"""
Return alias for index.
Returns
-------
Index
Index of the Series.
Examples
--------
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> psser = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx)
>>> psser.keys() # doctest: +SKIP
MultiIndex([( 'lama', 'speed'),
( 'lama', 'weight'),
( 'lama', 'length'),
( 'cow', 'speed'),
( 'cow', 'weight'),
( 'cow', 'length'),
('falcon', 'speed'),
('falcon', 'weight'),
('falcon', 'length')],
)
"""
return self.index
# TODO: 'regex', 'method' parameter
def replace(
self,
to_replace: Optional[Union[Any, List, Tuple, Dict]] = None,
value: Optional[Union[List, Tuple]] = None,
regex: bool = False,
) -> "Series":
"""
Replace values given in to_replace with value.
Values of the Series are replaced with other values dynamically.
Parameters
----------
to_replace : str, list, tuple, dict, Series, int, float, or None
How to find the values that will be replaced.
* numeric, str:
- numeric: numeric values equal to to_replace will be replaced with value
- str: string exactly matching to_replace will be replaced with value
* list of str or numeric:
- if to_replace and value are both lists or tuples, they must be the same length.
- str and numeric rules apply as above.
* dict:
- Dicts can be used to specify different replacement values for different
existing values.
For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’
with ‘z’. To use a dict in this way the value parameter should be None.
- For a DataFrame a dict can specify that different values should be replaced
in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1
in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with
whatever is specified in value.
The value parameter should not be None in this case.
You can treat this as a special case of passing two lists except that you are
specifying the column to search in.
See the examples section for examples of each of these.
value : scalar, dict, list, tuple, str default None
Value to replace any values matching to_replace with.
For a DataFrame a dict of values can be used to specify which value to use
for each column (columns not in the dict will not be filled).
Regular expressions, strings and lists or dicts of such objects are also allowed.
Returns
-------
Series
Object after replacement.
Examples
--------
Scalar `to_replace` and `value`
>>> s = ps.Series([0, 1, 2, 3, 4])
>>> s
0 0
1 1
2 2
3 3
4 4
dtype: int64
>>> s.replace(0, 5)
0 5
1 1
2 2
3 3
4 4
dtype: int64
List-like `to_replace`
>>> s.replace([0, 4], 5000)
0 5000
1 1
2 2
3 3
4 5000
dtype: int64
>>> s.replace([1, 2, 3], [10, 20, 30])
0 0
1 10
2 20
3 30
4 4
dtype: int64
Dict-like `to_replace`
>>> s.replace({1: 1000, 2: 2000, 3: 3000, 4: 4000})
0 0
1 1000
2 2000
3 3000
4 4000
dtype: int64
Also support for MultiIndex
>>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
lama speed 45.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.replace(45, 450)
lama speed 450.0
weight 200.0
length 1.2
cow speed 30.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
>>> s.replace([45, 30, 320], 500)
lama speed 500.0
weight 200.0
length 1.2
cow speed 500.0
weight 250.0
length 1.5
falcon speed 500.0
weight 1.0
length 0.3
dtype: float64
>>> s.replace({45: 450, 30: 300})
lama speed 450.0
weight 200.0
length 1.2
cow speed 300.0
weight 250.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
"""
if to_replace is None:
return self.fillna(method="ffill")
if not isinstance(to_replace, (str, list, tuple, dict, int, float)):
raise TypeError("'to_replace' should be one of str, list, tuple, dict, int, float")
if regex:
raise NotImplementedError("replace currently not support for regex")
to_replace = list(to_replace) if isinstance(to_replace, tuple) else to_replace
value = list(value) if isinstance(value, tuple) else value
if isinstance(to_replace, list) and isinstance(value, list):
if not len(to_replace) == len(value):
raise ValueError(
"Replacement lists must match in length. Expecting {} got {}".format(
len(to_replace), len(value)
)
)
to_replace = {k: v for k, v in zip(to_replace, value)}
if isinstance(to_replace, dict):
is_start = True
if len(to_replace) == 0:
current = self.spark.column
else:
for to_replace_, value in to_replace.items():
cond = (
(F.isnan(self.spark.column) | self.spark.column.isNull())
if pd.isna(to_replace_)
else (self.spark.column == SF.lit(to_replace_))
)
if is_start:
current = F.when(cond, value)
is_start = False
else:
current = current.when(cond, value)
current = current.otherwise(self.spark.column)
else:
cond = self.spark.column.isin(to_replace)
# to_replace may be a scalar
if np.array(pd.isna(to_replace)).any():
cond = cond | F.isnan(self.spark.column) | self.spark.column.isNull()
current = F.when(cond, value).otherwise(self.spark.column)
return self._with_new_scol(current) # TODO: dtype?
def update(self, other: "Series") -> None:
"""
Modify Series in place using non-NA values from passed Series. Aligns on index.
Parameters
----------
other : Series
Examples
--------
>>> from pyspark.pandas.config import set_option, reset_option
>>> set_option("compute.ops_on_diff_frames", True)
>>> s = ps.Series([1, 2, 3])
>>> s.update(ps.Series([4, 5, 6]))
>>> s.sort_index()
0 4
1 5
2 6
dtype: int64
>>> s = ps.Series(['a', 'b', 'c'])
>>> s.update(ps.Series(['d', 'e'], index=[0, 2]))
>>> s.sort_index()
0 d
1 b
2 e
dtype: object
>>> s = ps.Series([1, 2, 3])
>>> s.update(ps.Series([4, 5, 6, 7, 8]))
>>> s.sort_index()
0 4
1 5
2 6
dtype: int64
>>> s = ps.Series([1, 2, 3], index=[10, 11, 12])
>>> s
10 1
11 2
12 3
dtype: int64
>>> s.update(ps.Series([4, 5, 6]))
>>> s.sort_index()
10 1
11 2
12 3
dtype: int64
>>> s.update(ps.Series([4, 5, 6], index=[11, 12, 13]))
>>> s.sort_index()
10 1
11 4
12 5
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = ps.Series([1, 2, 3])
>>> s.update(ps.Series([4, np.nan, 6]))
>>> s.sort_index()
0 4.0
1 2.0
2 6.0
dtype: float64
>>> reset_option("compute.ops_on_diff_frames")
"""
if not isinstance(other, Series):
raise TypeError("'other' must be a Series")
combined = combine_frames(self._psdf, other._psdf, how="leftouter")
this_scol = combined["this"]._internal.spark_column_for(self._column_label)
that_scol = combined["that"]._internal.spark_column_for(other._column_label)
scol = (
F.when(that_scol.isNotNull(), that_scol)
.otherwise(this_scol)
.alias(self._psdf._internal.spark_column_name_for(self._column_label))
)
internal = combined["this"]._internal.with_new_spark_column(
self._column_label, scol # TODO: dtype?
)
self._psdf._update_internal_frame(internal.resolved_copy, requires_same_anchor=False)
def where(self, cond: "Series", other: Any = np.nan) -> "Series":
"""
Replace values where the condition is False.
Parameters
----------
cond : boolean Series
Where cond is True, keep the original value. Where False,
replace with corresponding value from other.
other : scalar, Series
Entries where cond is False are replaced with corresponding value from other.
Returns
-------
Series
Examples
--------
>>> from pyspark.pandas.config import set_option, reset_option
>>> set_option("compute.ops_on_diff_frames", True)
>>> s1 = ps.Series([0, 1, 2, 3, 4])
>>> s2 = ps.Series([100, 200, 300, 400, 500])
>>> s1.where(s1 > 0).sort_index()
0 NaN
1 1.0
2 2.0
3 3.0
4 4.0
dtype: float64
>>> s1.where(s1 > 1, 10).sort_index()
0 10
1 10
2 2
3 3
4 4
dtype: int64
>>> s1.where(s1 > 1, s1 + 100).sort_index()
0 100
1 101
2 2
3 3
4 4
dtype: int64
>>> s1.where(s1 > 1, s2).sort_index()
0 100
1 200
2 2
3 3
4 4
dtype: int64
>>> reset_option("compute.ops_on_diff_frames")
"""
assert isinstance(cond, Series)
# We should check the DataFrame from both `cond` and `other`.
should_try_ops_on_diff_frame = not same_anchor(cond, self) or (
isinstance(other, Series) and not same_anchor(other, self)
)
if should_try_ops_on_diff_frame:
# Try to perform it with 'compute.ops_on_diff_frame' option.
psdf = self.to_frame()
tmp_cond_col = verify_temp_column_name(psdf, "__tmp_cond_col__")
tmp_other_col = verify_temp_column_name(psdf, "__tmp_other_col__")
psdf[tmp_cond_col] = cond
psdf[tmp_other_col] = other
# above logic makes a Spark DataFrame looks like below:
# +-----------------+---+----------------+-----------------+
# |__index_level_0__| 0|__tmp_cond_col__|__tmp_other_col__|
# +-----------------+---+----------------+-----------------+
# | 0| 0| false| 100|
# | 1| 1| false| 200|
# | 3| 3| true| 400|
# | 2| 2| true| 300|
# | 4| 4| true| 500|
# +-----------------+---+----------------+-----------------+
condition = (
F.when(
psdf[tmp_cond_col].spark.column,
psdf._psser_for(psdf._internal.column_labels[0]).spark.column,
)
.otherwise(psdf[tmp_other_col].spark.column)
.alias(psdf._internal.data_spark_column_names[0])
)
internal = psdf._internal.with_new_columns(
[condition], column_labels=self._internal.column_labels
)
return first_series(DataFrame(internal))
else:
if isinstance(other, Series):
other = other.spark.column
condition = (
F.when(cond.spark.column, self.spark.column)
.otherwise(other)
.alias(self._internal.data_spark_column_names[0])
)
return self._with_new_scol(condition)
def mask(self, cond: "Series", other: Any = np.nan) -> "Series":
"""
Replace values where the condition is True.
Parameters
----------
cond : boolean Series
Where cond is False, keep the original value. Where True,
replace with corresponding value from other.
other : scalar, Series
Entries where cond is True are replaced with corresponding value from other.
Returns
-------
Series
Examples
--------
>>> from pyspark.pandas.config import set_option, reset_option
>>> set_option("compute.ops_on_diff_frames", True)
>>> s1 = ps.Series([0, 1, 2, 3, 4])
>>> s2 = ps.Series([100, 200, 300, 400, 500])
>>> s1.mask(s1 > 0).sort_index()
0 0.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
>>> s1.mask(s1 > 1, 10).sort_index()
0 0
1 1
2 10
3 10
4 10
dtype: int64
>>> s1.mask(s1 > 1, s1 + 100).sort_index()
0 0
1 1
2 102
3 103
4 104
dtype: int64
>>> s1.mask(s1 > 1, s2).sort_index()
0 0
1 1
2 300
3 400
4 500
dtype: int64
>>> reset_option("compute.ops_on_diff_frames")
"""
return self.where(cast(Series, ~cond), other)
def xs(self, key: Name, level: Optional[int] = None) -> "Series":
"""
Return cross-section from the Series.
This method takes a `key` argument to select data at a particular
level of a MultiIndex.
Parameters
----------
key : label or tuple of label
Label contained in the index, or partially in a MultiIndex.
level : object, defaults to first n levels (n=1 or len(key))
In case of a key partially contained in a MultiIndex, indicate
which levels are used. Levels can be referred by label or position.
Returns
-------
Series
Cross-section from the original Series
corresponding to the selected index levels.
Examples
--------
>>> midx = pd.MultiIndex([['a', 'b', 'c'],
... ['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... [[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> s = ps.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3],
... index=midx)
>>> s
a lama speed 45.0
weight 200.0
length 1.2
b cow speed 30.0
weight 250.0
length 1.5
c falcon speed 320.0
weight 1.0
length 0.3
dtype: float64
Get values at specified index
>>> s.xs('a')
lama speed 45.0
weight 200.0
length 1.2
dtype: float64
Get values at several indexes
>>> s.xs(('a', 'lama'))
speed 45.0
weight 200.0
length 1.2
dtype: float64
Get values at specified index and level
>>> s.xs('lama', level=1)
a speed 45.0
weight 200.0
length 1.2
dtype: float64
"""
if not isinstance(key, tuple):
key = (key,)
if level is None:
level = 0
internal = self._internal
scols = (
internal.index_spark_columns[:level]
+ internal.index_spark_columns[level + len(key) :]
+ [self.spark.column]
)
rows = [internal.spark_columns[lvl] == index for lvl, index in enumerate(key, level)]
sdf = internal.spark_frame.filter(reduce(lambda x, y: x & y, rows)).select(scols)
if internal.index_level == len(key):
# if spark_frame has one column and one data, return data only without frame
pdf = sdf.limit(2).toPandas()
length = len(pdf)
if length == 1:
return pdf[self._internal.data_spark_column_names[0]].iloc[0]
index_spark_column_names = (
internal.index_spark_column_names[:level]
+ internal.index_spark_column_names[level + len(key) :]
)
index_names = internal.index_names[:level] + internal.index_names[level + len(key) :]
index_fields = internal.index_fields[:level] + internal.index_fields[level + len(key) :]
internal = internal.copy(
spark_frame=sdf,
index_spark_columns=[scol_for(sdf, col) for col in index_spark_column_names],
index_names=index_names,
index_fields=index_fields,
data_spark_columns=[scol_for(sdf, internal.data_spark_column_names[0])],
)
return first_series(DataFrame(internal))
def pct_change(self, periods: int = 1) -> "Series":
"""
Percentage change between the current and a prior element.
.. note:: the current implementation of this API uses Spark's Window without
specifying partition specification. This leads to move all data into
single partition in single machine and could cause serious
performance degradation. Avoid this method against very large dataset.
Parameters
----------
periods : int, default 1
Periods to shift for forming percent change.
Returns
-------
Series
Examples
--------
>>> psser = ps.Series([90, 91, 85], index=[2, 4, 1])
>>> psser
2 90
4 91
1 85
dtype: int64
>>> psser.pct_change()
2 NaN
4 0.011111
1 -0.065934
dtype: float64
>>> psser.sort_index().pct_change()
1 NaN
2 0.058824
4 0.011111
dtype: float64
>>> psser.pct_change(periods=2)
2 NaN
4 NaN
1 -0.055556
dtype: float64
"""
scol = self.spark.column
window = Window.orderBy(NATURAL_ORDER_COLUMN_NAME).rowsBetween(-periods, -periods)
prev_row = F.lag(scol, periods).over(window)
return self._with_new_scol((scol - prev_row) / prev_row).spark.analyzed
def combine_first(self, other: "Series") -> "Series":
"""
Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
The value(s) to be combined with the `Series`.
Returns
-------
Series
The result of combining the Series with the other object.
See Also
--------
Series.combine : Perform elementwise operation on two Series
using a given function.
Notes
-----
Result index will be the union of the two indexes.
Examples
--------
>>> s1 = ps.Series([1, np.nan])
>>> s2 = ps.Series([3, 4])
>>> with ps.option_context("compute.ops_on_diff_frames", True):
... s1.combine_first(s2)
0 1.0
1 4.0
dtype: float64
"""
if not isinstance(other, ps.Series):
raise TypeError("`combine_first` only allows `Series` for parameter `other`")
if same_anchor(self, other):
this = self.spark.column
that = other.spark.column
combined = self._psdf
else:
combined = combine_frames(self._psdf, other._psdf)
this = combined["this"]._internal.spark_column_for(self._column_label)
that = combined["that"]._internal.spark_column_for(other._column_label)
# If `self` has missing value, use value of `other`
cond = F.when(this.isNull(), that).otherwise(this)
# If `self` and `other` come from same frame, the anchor should be kept
if same_anchor(self, other):
return self._with_new_scol(cond) # TODO: dtype?
index_scols = combined._internal.index_spark_columns
sdf = combined._internal.spark_frame.select(
*index_scols, cond.alias(self._internal.data_spark_column_names[0])
).distinct()
internal = self._internal.with_new_sdf(
sdf, index_fields=combined._internal.index_fields, data_fields=[None] # TODO: dtype?
)
return first_series(DataFrame(internal))
def dot(self, other: Union["Series", DataFrame]) -> Union[Scalar, "Series"]:
"""
Compute the dot product between the Series and the columns of other.
This method computes the dot product between the Series and another
one, or the Series and each columns of a DataFrame.
It can also be called using `self @ other` in Python >= 3.5.
.. note:: This API is slightly different from pandas when indexes from both Series
are not aligned. To match with pandas', it requires to read the whole data for,
for example, counting. pandas raises an exception; however, pandas-on-Spark
just proceeds and performs by ignoring mismatches with NaN permissively.
>>> pdf1 = pd.Series([1, 2, 3], index=[0, 1, 2])
>>> pdf2 = pd.Series([1, 2, 3], index=[0, 1, 3])
>>> pdf1.dot(pdf2) # doctest: +SKIP
...
ValueError: matrices are not aligned
>>> psdf1 = ps.Series([1, 2, 3], index=[0, 1, 2])
>>> psdf2 = ps.Series([1, 2, 3], index=[0, 1, 3])
>>> psdf1.dot(psdf2) # doctest: +SKIP
5
Parameters
----------
other : Series, DataFrame.
The other object to compute the dot product with its columns.
Returns
-------
scalar, Series
Return the dot product of the Series and other if other is a
Series, the Series of the dot product of Series and each rows of
other if other is a DataFrame.
Notes
-----
The Series and other has to share the same index if other is a Series
or a DataFrame.
Examples
--------
>>> s = ps.Series([0, 1, 2, 3])
>>> s.dot(s)
14
>>> s @ s
14
>>> psdf = ps.DataFrame({'x': [0, 1, 2, 3], 'y': [0, -1, -2, -3]})
>>> psdf
x y
0 0 0
1 1 -1
2 2 -2
3 3 -3
>>> with ps.option_context("compute.ops_on_diff_frames", True):
... s.dot(psdf)
...
x 14
y -14
dtype: int64
"""
if isinstance(other, DataFrame):
if not same_anchor(self, other):
if not self.index.sort_values().equals(other.index.sort_values()):
raise ValueError("matrices are not aligned")
other_copy = other.copy() # type: DataFrame
column_labels = other_copy._internal.column_labels
self_column_label = verify_temp_column_name(other_copy, "__self_column__")
other_copy[self_column_label] = self
self_psser = other_copy._psser_for(self_column_label)
product_pssers = [
cast(Series, other_copy._psser_for(label) * self_psser) for label in column_labels
]
dot_product_psser = DataFrame(
other_copy._internal.with_new_columns(product_pssers, column_labels=column_labels)
).sum()
return cast(Series, dot_product_psser).rename(self.name)
else:
assert isinstance(other, Series)
if not same_anchor(self, other):
if len(self.index) != len(other.index):
raise ValueError("matrices are not aligned")
return (self * other).sum()
def __matmul__(self, other: Union["Series", DataFrame]) -> Union[Scalar, "Series"]:
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.dot(other)
def repeat(self, repeats: Union[int, "Series"]) -> "Series":
"""
Repeat elements of a Series.
Returns a new Series where each element of the current Series
is repeated consecutively a given number of times.
Parameters
----------
repeats : int or Series
The number of repetitions for each element. This should be a
non-negative integer. Repeating 0 times will return an empty
Series.
Returns
-------
Series
Newly created Series with repeated elements.
See Also
--------
Index.repeat : Equivalent function for Index.
Examples
--------
>>> s = ps.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
>>> s.repeat(2)
0 a
1 b
2 c
0 a
1 b
2 c
dtype: object
>>> ps.Series([1, 2, 3]).repeat(0)
Series([], dtype: int64)
"""
if not isinstance(repeats, (int, Series)):
raise TypeError(
"`repeats` argument must be integer or Series, but got {}".format(type(repeats))
)
if isinstance(repeats, Series):
if not same_anchor(self, repeats):
psdf = self.to_frame()
temp_repeats = verify_temp_column_name(psdf, "__temp_repeats__")
psdf[temp_repeats] = repeats
return (
psdf._psser_for(psdf._internal.column_labels[0])
.repeat(psdf[temp_repeats])
.rename(self.name)
)
else:
scol = F.explode(
F.array_repeat(self.spark.column, repeats.astype("int32").spark.column)
).alias(name_like_string(self.name))
sdf = self._internal.spark_frame.select(self._internal.index_spark_columns + [scol])
internal = self._internal.copy(
spark_frame=sdf,
index_spark_columns=[
scol_for(sdf, col) for col in self._internal.index_spark_column_names
],
data_spark_columns=[scol_for(sdf, name_like_string(self.name))],
)
return first_series(DataFrame(internal))
else:
if repeats < 0:
raise ValueError("negative dimensions are not allowed")
psdf = self._psdf[[self.name]]
if repeats == 0:
return first_series(DataFrame(psdf._internal.with_filter(SF.lit(False))))
else:
return first_series(ps.concat([psdf] * repeats))
def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
"""
Return the last row(s) without any NaNs before `where`.
The last row (for each element in `where`, if list) without any
NaN is taken.
If there is no good value, NaN is returned.
.. note:: This API is dependent on :meth:`Index.is_monotonic_increasing`
which can be expensive.
Parameters
----------
where : index or array-like of indices
Returns
-------
scalar or Series
The return can be:
* scalar : when `self` is a Series and `where` is a scalar
* Series: when `self` is a Series and `where` is an array-like
Return scalar or Series
Notes
-----
Indices are assumed to be sorted. Raises if this is not the case.
Examples
--------
>>> s = ps.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
>>> s
10 1.0
20 2.0
30 NaN
40 4.0
dtype: float64
A scalar `where`.
>>> s.asof(20)
2.0
For a sequence `where`, a Series is returned. The first value is
NaN, because the first element of `where` is before the first
index value.
>>> s.asof([5, 20]).sort_index()
5 NaN
20 2.0
dtype: float64
Missing values are not considered. The following is ``2.0``, not
NaN, even though NaN is at the index location for ``30``.
>>> s.asof(30)
2.0
"""
should_return_series = True
if isinstance(self.index, ps.MultiIndex):
raise ValueError("asof is not supported for a MultiIndex")
if isinstance(where, (ps.Index, ps.Series, DataFrame)):
raise ValueError("where cannot be an Index, Series or a DataFrame")
if not self.index.is_monotonic_increasing:
raise ValueError("asof requires a sorted index")
if not is_list_like(where):
should_return_series = False
where = [where]
index_scol = self._internal.index_spark_columns[0]
index_type = self._internal.spark_type_for(index_scol)
cond = [
F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
for index in where
]
sdf = self._internal.spark_frame.select(cond)
if not should_return_series:
with sql_conf({SPARK_CONF_ARROW_ENABLED: False}):
# Disable Arrow to keep row ordering.
result = cast(pd.DataFrame, sdf.limit(1).toPandas()).iloc[0, 0]
return result if result is not None else np.nan
# The data is expected to be small so it's fine to transpose/use default index.
with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
psdf = ps.DataFrame(sdf) # type: DataFrame
psdf.columns = pd.Index(where)
return first_series(psdf.transpose()).rename(self.name)
def mad(self) -> float:
"""
Return the mean absolute deviation of values.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.mad()
1.0
"""
sdf = self._internal.spark_frame
spark_column = self.spark.column
avg = unpack_scalar(sdf.select(F.avg(spark_column)))
mad = unpack_scalar(sdf.select(F.avg(F.abs(spark_column - avg))))
return mad
def unstack(self, level: int = -1) -> DataFrame:
"""
Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame.
The level involved will automatically get sorted.
Notes
-----
Unlike pandas, pandas-on-Spark doesn't check whether an index is duplicated or not
because the checking of duplicated index requires scanning whole data which
can be quite expensive.
Parameters
----------
level : int, str, or list of these, default last level
Level(s) to unstack, can pass level name.
Returns
-------
DataFrame
Unstacked Series.
Examples
--------
>>> s = ps.Series([1, 2, 3, 4],
... index=pd.MultiIndex.from_product([['one', 'two'],
... ['a', 'b']]))
>>> s
one a 1
b 2
two a 3
b 4
dtype: int64
>>> s.unstack(level=-1).sort_index()
a b
one 1 2
two 3 4
>>> s.unstack(level=0).sort_index()
one two
a 1 3
b 2 4
"""
if not isinstance(self.index, ps.MultiIndex):
raise ValueError("Series.unstack only support for a MultiIndex")
index_nlevels = self.index.nlevels
if level > 0 and (level > index_nlevels - 1):
raise IndexError(
"Too many levels: Index has only {} levels, not {}".format(index_nlevels, level + 1)
)
elif level < 0 and (level < -index_nlevels):
raise IndexError(
"Too many levels: Index has only {} levels, {} is not a valid level number".format(
index_nlevels, level
)
)
internal = self._internal.resolved_copy
index_map = list(zip(internal.index_spark_column_names, internal.index_names))
pivot_col, column_label_names = index_map.pop(level)
index_scol_names, index_names = zip(*index_map)
col = internal.data_spark_column_names[0]
sdf = internal.spark_frame
sdf = sdf.groupby(list(index_scol_names)).pivot(pivot_col).agg(F.first(scol_for(sdf, col)))
internal = InternalFrame( # TODO: dtypes?
spark_frame=sdf,
index_spark_columns=[scol_for(sdf, col) for col in index_scol_names],
index_names=list(index_names),
column_label_names=[column_label_names],
)
return DataFrame(internal)
def item(self) -> Scalar:
"""
Return the first element of the underlying data as a Python scalar.
Returns
-------
scalar
The first element of Series.
Raises
------
ValueError
If the data is not length-1.
Examples
--------
>>> psser = ps.Series([10])
>>> psser.item()
10
"""
return self.head(2)._to_internal_pandas().item()
def iteritems(self) -> Iterable[Tuple[Name, Any]]:
"""
Lazily iterate over (index, value) tuples.
This method returns an iterable tuple (index, value). This is
convenient if you want to create a lazy iterator.
.. note:: Unlike pandas', the iteritems in pandas-on-Spark returns generator rather
zip object
Returns
-------
iterable
Iterable of tuples containing the (index, value) pairs from a
Series.
See Also
--------
DataFrame.items : Iterate over (column name, Series) pairs.
DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs.
Examples
--------
>>> s = ps.Series(['A', 'B', 'C'])
>>> for index, value in s.items():
... print("Index : {}, Value : {}".format(index, value))
Index : 0, Value : A
Index : 1, Value : B
Index : 2, Value : C
"""
internal_index_columns = self._internal.index_spark_column_names
internal_data_column = self._internal.data_spark_column_names[0]
def extract_kv_from_spark_row(row: Row) -> Tuple[Name, Any]:
k = (
row[internal_index_columns[0]]
if len(internal_index_columns) == 1
else tuple(row[c] for c in internal_index_columns)
)
v = row[internal_data_column]
return k, v
for k, v in map(
extract_kv_from_spark_row, self._internal.resolved_copy.spark_frame.toLocalIterator()
):
yield k, v
def items(self) -> Iterable[Tuple[Name, Any]]:
"""This is an alias of ``iteritems``."""
return self.iteritems()
def droplevel(self, level: Union[int, Name, List[Union[int, Name]]]) -> "Series":
"""
Return Series with requested index level(s) removed.
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, elements must be names or positional indexes
of levels.
Returns
-------
Series
Series with requested index level(s) removed.
Examples
--------
>>> psser = ps.Series(
... [1, 2, 3],
... index=pd.MultiIndex.from_tuples(
... [("x", "a"), ("x", "b"), ("y", "c")], names=["level_1", "level_2"]
... ),
... )
>>> psser
level_1 level_2
x a 1
b 2
y c 3
dtype: int64
Removing specific index level by level
>>> psser.droplevel(0)
level_2
a 1
b 2
c 3
dtype: int64
Removing specific index level by name
>>> psser.droplevel("level_2")
level_1
x 1
x 2
y 3
dtype: int64
"""
return first_series(self.to_frame().droplevel(level=level, axis=0)).rename(self.name)
def tail(self, n: int = 5) -> "Series":
"""
Return the last `n` rows.
This function returns last `n` rows from the object based on
position. It is useful for quickly verifying data, for example,
after sorting or appending rows.
For negative values of `n`, this function returns all rows except
the first `n` rows, equivalent to ``df[n:]``.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
type of caller
The last `n` rows of the caller object.
See Also
--------
DataFrame.head : The first `n` rows of the caller object.
Examples
--------
>>> psser = ps.Series([1, 2, 3, 4, 5])
>>> psser
0 1
1 2
2 3
3 4
4 5
dtype: int64
>>> psser.tail(3) # doctest: +SKIP
2 3
3 4
4 5
dtype: int64
"""
return first_series(self.to_frame().tail(n=n)).rename(self.name)
def explode(self) -> "Series":
"""
Transform each element of a list-like to a row.
Returns
-------
Series
Exploded lists to rows; index will be duplicated for these rows.
See Also
--------
Series.str.split : Split string values on specified separator.
Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex
to produce DataFrame.
DataFrame.melt : Unpivot a DataFrame from wide format to long format.
DataFrame.explode : Explode a DataFrame from list-like
columns to long format.
Examples
--------
>>> psser = ps.Series([[1, 2, 3], [], [3, 4]])
>>> psser
0 [1, 2, 3]
1 []
2 [3, 4]
dtype: object
>>> psser.explode() # doctest: +SKIP
0 1.0
0 2.0
0 3.0
1 NaN
2 3.0
2 4.0
dtype: float64
"""
if not isinstance(self.spark.data_type, ArrayType):
return self.copy()
scol = F.explode_outer(self.spark.column).alias(name_like_string(self._column_label))
internal = self._internal.with_new_columns([scol], keep_order=False)
return first_series(DataFrame(internal))
def argsort(self) -> "Series":
"""
Return the integer indices that would sort the Series values.
Unlike pandas, the index order is not preserved in the result.
Returns
-------
Series
Positions of values within the sort order with -1 indicating
nan values.
Examples
--------
>>> psser = ps.Series([3, 3, 4, 1, 6, 2, 3, 7, 8, 7, 10])
>>> psser
0 3
1 3
2 4
3 1
4 6
5 2
6 3
7 7
8 8
9 7
10 10
dtype: int64
>>> psser.argsort().sort_index()
0 3
1 5
2 0
3 1
4 6
5 2
6 4
7 7
8 9
9 8
10 10
dtype: int64
"""
notnull = self.loc[self.notnull()]
sdf_for_index = notnull._internal.spark_frame.select(notnull._internal.index_spark_columns)
tmp_join_key = verify_temp_column_name(sdf_for_index, "__tmp_join_key__")
sdf_for_index, _ = InternalFrame.attach_distributed_sequence_column(
sdf_for_index, tmp_join_key
)
# sdf_for_index:
# +----------------+-----------------+
# |__tmp_join_key__|__index_level_0__|
# +----------------+-----------------+
# | 0| 0|
# | 1| 1|
# | 2| 2|
# | 3| 3|
# | 4| 4|
# +----------------+-----------------+
sdf_for_data = notnull._internal.spark_frame.select(
notnull.spark.column.alias("values"), NATURAL_ORDER_COLUMN_NAME
)
sdf_for_data, _ = InternalFrame.attach_distributed_sequence_column(
sdf_for_data, SPARK_DEFAULT_SERIES_NAME
)
# sdf_for_data:
# +---+------+-----------------+
# | 0|values|__natural_order__|
# +---+------+-----------------+
# | 0| 3| 25769803776|
# | 1| 3| 51539607552|
# | 2| 4| 77309411328|
# | 3| 1| 103079215104|
# | 4| 2| 128849018880|
# +---+------+-----------------+
sdf_for_data = sdf_for_data.sort(
scol_for(sdf_for_data, "values"), NATURAL_ORDER_COLUMN_NAME
).drop("values", NATURAL_ORDER_COLUMN_NAME)
tmp_join_key = verify_temp_column_name(sdf_for_data, "__tmp_join_key__")
sdf_for_data, _ = InternalFrame.attach_distributed_sequence_column(
sdf_for_data, tmp_join_key
)
# sdf_for_index: sdf_for_data:
# +----------------+-----------------+ +----------------+---+
# |__tmp_join_key__|__index_level_0__| |__tmp_join_key__| 0|
# +----------------+-----------------+ +----------------+---+
# | 0| 0| | 0| 3|
# | 1| 1| | 1| 4|
# | 2| 2| | 2| 0|
# | 3| 3| | 3| 1|
# | 4| 4| | 4| 2|
# +----------------+-----------------+ +----------------+---+
sdf = sdf_for_index.join(sdf_for_data, on=tmp_join_key).drop(tmp_join_key)
internal = self._internal.with_new_sdf(
spark_frame=sdf,
data_columns=[SPARK_DEFAULT_SERIES_NAME],
index_fields=[
InternalField(dtype=field.dtype) for field in self._internal.index_fields
],
data_fields=[None],
)
psser = first_series(DataFrame(internal))
return cast(
Series,
ps.concat([psser, self.loc[self.isnull()].spark.transform(lambda _: SF.lit(-1))]),
)
def argmax(self) -> int:
"""
Return int position of the largest value in the Series.
If the maximum is achieved in multiple locations,
the first row position is returned.
Returns
-------
int
Row position of the maximum value.
Examples
--------
Consider dataset containing cereal calories
>>> s = ps.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
>>> s # doctest: +SKIP
Corn Flakes 100.0
Almond Delight 110.0
Cinnamon Toast Crunch 120.0
Cocoa Puff 110.0
dtype: float64
>>> s.argmax() # doctest: +SKIP
2
"""
sdf = self._internal.spark_frame.select(self.spark.column, NATURAL_ORDER_COLUMN_NAME)
max_value = sdf.select(
F.max(scol_for(sdf, self._internal.data_spark_column_names[0])),
F.first(NATURAL_ORDER_COLUMN_NAME),
).head()
if max_value[1] is None:
raise ValueError("attempt to get argmax of an empty sequence")
elif max_value[0] is None:
return -1
# We should remember the natural sequence started from 0
seq_col_name = verify_temp_column_name(sdf, "__distributed_sequence_column__")
sdf, _ = InternalFrame.attach_distributed_sequence_column(
sdf.drop(NATURAL_ORDER_COLUMN_NAME), seq_col_name
)
# If the maximum is achieved in multiple locations, the first row position is returned.
return sdf.filter(
scol_for(sdf, self._internal.data_spark_column_names[0]) == max_value[0]
).head()[0]
def argmin(self) -> int:
"""
Return int position of the smallest value in the Series.
If the minimum is achieved in multiple locations,
the first row position is returned.
Returns
-------
int
Row position of the minimum value.
Examples
--------
Consider dataset containing cereal calories
>>> s = ps.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
>>> s # doctest: +SKIP
Corn Flakes 100.0
Almond Delight 110.0
Cinnamon Toast Crunch 120.0
Cocoa Puff 110.0
dtype: float64
>>> s.argmin() # doctest: +SKIP
0
"""
sdf = self._internal.spark_frame.select(self.spark.column, NATURAL_ORDER_COLUMN_NAME)
min_value = sdf.select(
F.min(scol_for(sdf, self._internal.data_spark_column_names[0])),
F.first(NATURAL_ORDER_COLUMN_NAME),
).head()
if min_value[1] is None:
raise ValueError("attempt to get argmin of an empty sequence")
elif min_value[0] is None:
return -1
# We should remember the natural sequence started from 0
seq_col_name = verify_temp_column_name(sdf, "__distributed_sequence_column__")
sdf, _ = InternalFrame.attach_distributed_sequence_column(
sdf.drop(NATURAL_ORDER_COLUMN_NAME), seq_col_name
)
# If the minimum is achieved in multiple locations, the first row position is returned.
return sdf.filter(
scol_for(sdf, self._internal.data_spark_column_names[0]) == min_value[0]
).head()[0]
def compare(
self, other: "Series", keep_shape: bool = False, keep_equal: bool = False
) -> DataFrame:
"""
Compare to another Series and show the differences.
Parameters
----------
other : Series
Object to compare with.
keep_shape : bool, default False
If true, all rows and columns are kept.
Otherwise, only the ones with different values are kept.
keep_equal : bool, default False
If true, the result keeps values that are equal.
Otherwise, equal values are shown as NaNs.
Returns
-------
DataFrame
Notes
-----
Matching NaNs will not appear as a difference.
Examples
--------
>>> from pyspark.pandas.config import set_option, reset_option
>>> set_option("compute.ops_on_diff_frames", True)
>>> s1 = ps.Series(["a", "b", "c", "d", "e"])
>>> s2 = ps.Series(["a", "a", "c", "b", "e"])
Align the differences on columns
>>> s1.compare(s2).sort_index()
self other
1 b a
3 d b
Keep all original rows
>>> s1.compare(s2, keep_shape=True).sort_index()
self other
0 None None
1 b a
2 None None
3 d b
4 None None
Keep all original rows and also all original values
>>> s1.compare(s2, keep_shape=True, keep_equal=True).sort_index()
self other
0 a a
1 b a
2 c c
3 d b
4 e e
>>> reset_option("compute.ops_on_diff_frames")
"""
if same_anchor(self, other):
self_column_label = verify_temp_column_name(other.to_frame(), "__self_column__")
other_column_label = verify_temp_column_name(self.to_frame(), "__other_column__")
combined = DataFrame(
self._internal.with_new_columns(
[self.rename(self_column_label), other.rename(other_column_label)]
)
) # type: DataFrame
else:
if not self.index.equals(other.index):
raise ValueError("Can only compare identically-labeled Series objects")
combined = combine_frames(self.to_frame(), other.to_frame())
this_column_label = "self"
that_column_label = "other"
if keep_equal and keep_shape:
combined.columns = pd.Index([this_column_label, that_column_label])
return combined
this_data_scol = combined._internal.data_spark_columns[0]
that_data_scol = combined._internal.data_spark_columns[1]
index_scols = combined._internal.index_spark_columns
sdf = combined._internal.spark_frame
if keep_shape:
this_scol = (
F.when(this_data_scol == that_data_scol, None)
.otherwise(this_data_scol)
.alias(this_column_label)
)
this_field = combined._internal.data_fields[0].copy(
name=this_column_label, nullable=True
)
that_scol = (
F.when(this_data_scol == that_data_scol, None)
.otherwise(that_data_scol)
.alias(that_column_label)
)
that_field = combined._internal.data_fields[1].copy(
name=that_column_label, nullable=True
)
else:
sdf = sdf.filter(~this_data_scol.eqNullSafe(that_data_scol))
this_scol = this_data_scol.alias(this_column_label)
this_field = combined._internal.data_fields[0].copy(name=this_column_label)
that_scol = that_data_scol.alias(that_column_label)
that_field = combined._internal.data_fields[1].copy(name=that_column_label)
sdf = sdf.select(*index_scols, this_scol, that_scol, NATURAL_ORDER_COLUMN_NAME)
internal = InternalFrame(
spark_frame=sdf,
index_spark_columns=[
scol_for(sdf, col) for col in self._internal.index_spark_column_names
],
index_names=self._internal.index_names,
index_fields=combined._internal.index_fields,
column_labels=[(this_column_label,), (that_column_label,)],
data_spark_columns=[scol_for(sdf, this_column_label), scol_for(sdf, that_column_label)],
data_fields=[this_field, that_field],
column_label_names=[None],
)
return DataFrame(internal)
def align(
self,
other: Union[DataFrame, "Series"],
join: str = "outer",
axis: Optional[Axis] = None,
copy: bool = True,
) -> Tuple["Series", Union[DataFrame, "Series"]]:
"""
Align two objects on their axes with the specified join method.
Join method is specified for each axis Index.
Parameters
----------
other : DataFrame or Series
join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
axis : allowed axis of the other object, default None
Align on index (0), columns (1), or both (None).
copy : bool, default True
Always returns new objects. If copy=False and no reindexing is
required then original objects are returned.
Returns
-------
(left, right) : (Series, type of other)
Aligned objects.
Examples
--------
>>> ps.set_option("compute.ops_on_diff_frames", True)
>>> s1 = ps.Series([7, 8, 9], index=[10, 11, 12])
>>> s2 = ps.Series(["g", "h", "i"], index=[10, 20, 30])
>>> aligned_l, aligned_r = s1.align(s2)
>>> aligned_l.sort_index()
10 7.0
11 8.0
12 9.0
20 NaN
30 NaN
dtype: float64
>>> aligned_r.sort_index()
10 g
11 None
12 None
20 h
30 i
dtype: object
Align with the join type "inner":
>>> aligned_l, aligned_r = s1.align(s2, join="inner")
>>> aligned_l.sort_index()
10 7
dtype: int64
>>> aligned_r.sort_index()
10 g
dtype: object
Align with a DataFrame:
>>> df = ps.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}, index=[10, 20, 30])
>>> aligned_l, aligned_r = s1.align(df)
>>> aligned_l.sort_index()
10 7.0
11 8.0
12 9.0
20 NaN
30 NaN
dtype: float64
>>> aligned_r.sort_index()
a b
10 1.0 a
11 NaN None
12 NaN None
20 2.0 b
30 3.0 c
>>> ps.reset_option("compute.ops_on_diff_frames")
"""
axis = validate_axis(axis)
if axis == 1:
raise ValueError("Series does not support columns axis.")
self_df = self.to_frame()
left, right = self_df.align(other, join=join, axis=axis, copy=False)
if left is self_df:
left_ser = self
else:
left_ser = first_series(left).rename(self.name)
return (left_ser.copy(), right.copy()) if copy else (left_ser, right)
def between_time(
self,
start_time: Union[datetime.time, str],
end_time: Union[datetime.time, str],
include_start: bool = True,
include_end: bool = True,
axis: Axis = 0,
) -> "Series":
"""
Select values between particular times of the day (example: 9:00-9:30 AM).
By setting ``start_time`` to be later than ``end_time``,
you can get the times that are *not* between the two times.
Parameters
----------
start_time : datetime.time or str
Initial time as a time filter limit.
end_time : datetime.time or str
End time as a time filter limit.
include_start : bool, default True
Whether the start time needs to be included in the result.
include_end : bool, default True
Whether the end time needs to be included in the result.
axis : {0 or 'index', 1 or 'columns'}, default 0
Determine range time on index or columns value.
Returns
-------
Series
Data from the original object filtered to the specified dates range.
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
See Also
--------
at_time : Select values at a particular time of the day.
last : Select final periods of time series based on a date offset.
DatetimeIndex.indexer_between_time : Get just the index locations for
values between particular times of the day.
Examples
--------
>>> idx = pd.date_range('2018-04-09', periods=4, freq='1D20min')
>>> psser = ps.Series([1, 2, 3, 4], index=idx)
>>> psser
2018-04-09 00:00:00 1
2018-04-10 00:20:00 2
2018-04-11 00:40:00 3
2018-04-12 01:00:00 4
dtype: int64
>>> psser.between_time('0:15', '0:45')
2018-04-10 00:20:00 2
2018-04-11 00:40:00 3
dtype: int64
"""
return first_series(
self.to_frame().between_time(start_time, end_time, include_start, include_end, axis)
).rename(self.name)
def at_time(
self, time: Union[datetime.time, str], asof: bool = False, axis: Axis = 0
) -> "Series":
"""
Select values at particular time of day (example: 9:30AM).
Parameters
----------
time : datetime.time or str
axis : {0 or 'index', 1 or 'columns'}, default 0
Returns
-------
Series
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
See Also
--------
between_time : Select values between particular times of the day.
DatetimeIndex.indexer_at_time : Get just the index locations for
values at particular time of the day.
Examples
--------
>>> idx = pd.date_range('2018-04-09', periods=4, freq='12H')
>>> psser = ps.Series([1, 2, 3, 4], index=idx)
>>> psser
2018-04-09 00:00:00 1
2018-04-09 12:00:00 2
2018-04-10 00:00:00 3
2018-04-10 12:00:00 4
dtype: int64
>>> psser.at_time('12:00')
2018-04-09 12:00:00 2
2018-04-10 12:00:00 4
dtype: int64
"""
return first_series(self.to_frame().at_time(time, asof, axis)).rename(self.name)
def _cum(
self,
func: Callable[[Column], Column],
skipna: bool,
part_cols: Sequence["ColumnOrName"] = (),
ascending: bool = True,
) -> "Series":
# This is used to cummin, cummax, cumsum, etc.
if ascending:
window = (
Window.orderBy(F.asc(NATURAL_ORDER_COLUMN_NAME))
.partitionBy(*part_cols)
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
else:
window = (
Window.orderBy(F.desc(NATURAL_ORDER_COLUMN_NAME))
.partitionBy(*part_cols)
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
if skipna:
# There is a behavior difference between pandas and PySpark. In case of cummax,
#
# Input:
# A B
# 0 2.0 1.0
# 1 5.0 NaN
# 2 1.0 0.0
# 3 2.0 4.0
# 4 4.0 9.0
#
# pandas:
# A B
# 0 2.0 1.0
# 1 5.0 NaN
# 2 5.0 1.0
# 3 5.0 4.0
# 4 5.0 9.0
#
# PySpark:
# A B
# 0 2.0 1.0
# 1 5.0 1.0
# 2 5.0 1.0
# 3 5.0 4.0
# 4 5.0 9.0
scol = F.when(
# Manually sets nulls given the column defined above.
self.spark.column.isNull(),
SF.lit(None),
).otherwise(func(self.spark.column).over(window))
else:
# Here, we use two Windows.
# One for real data.
# The other one for setting nulls after the first null it meets.
#
# There is a behavior difference between pandas and PySpark. In case of cummax,
#
# Input:
# A B
# 0 2.0 1.0
# 1 5.0 NaN
# 2 1.0 0.0
# 3 2.0 4.0
# 4 4.0 9.0
#
# pandas:
# A B
# 0 2.0 1.0
# 1 5.0 NaN
# 2 5.0 NaN
# 3 5.0 NaN
# 4 5.0 NaN
#
# PySpark:
# A B
# 0 2.0 1.0
# 1 5.0 1.0
# 2 5.0 1.0
# 3 5.0 4.0
# 4 5.0 9.0
scol = F.when(
# By going through with max, it sets True after the first time it meets null.
F.max(self.spark.column.isNull()).over(window),
# Manually sets nulls given the column defined above.
SF.lit(None),
).otherwise(func(self.spark.column).over(window))
return self._with_new_scol(scol)
def _cumsum(self, skipna: bool, part_cols: Sequence["ColumnOrName"] = ()) -> "Series":
psser = self
if isinstance(psser.spark.data_type, BooleanType):
psser = psser.spark.transform(lambda scol: scol.cast(LongType()))
elif not isinstance(psser.spark.data_type, NumericType):
raise TypeError(
"Could not convert {} ({}) to numeric".format(
spark_type_to_pandas_dtype(psser.spark.data_type),
psser.spark.data_type.simpleString(),
)
)
return psser._cum(F.sum, skipna, part_cols)
def _cumprod(self, skipna: bool, part_cols: Sequence["ColumnOrName"] = ()) -> "Series":
if isinstance(self.spark.data_type, BooleanType):
scol = self._cum(
lambda scol: F.min(F.coalesce(scol, SF.lit(True))), skipna, part_cols
).spark.column.cast(LongType())
elif isinstance(self.spark.data_type, NumericType):
num_zeros = self._cum(
lambda scol: F.sum(F.when(scol == 0, 1).otherwise(0)), skipna, part_cols
).spark.column
num_negatives = self._cum(
lambda scol: F.sum(F.when(scol < 0, 1).otherwise(0)), skipna, part_cols
).spark.column
sign = F.when(num_negatives % 2 == 0, 1).otherwise(-1)
abs_prod = F.exp(
self._cum(lambda scol: F.sum(F.log(F.abs(scol))), skipna, part_cols).spark.column
)
scol = F.when(num_zeros > 0, 0).otherwise(sign * abs_prod)
if isinstance(self.spark.data_type, IntegralType):
scol = F.round(scol).cast(LongType())
else:
raise TypeError(
"Could not convert {} ({}) to numeric".format(
spark_type_to_pandas_dtype(self.spark.data_type),
self.spark.data_type.simpleString(),
)
)
return self._with_new_scol(scol)
# ----------------------------------------------------------------------
# Accessor Methods
# ----------------------------------------------------------------------
dt = CachedAccessor("dt", DatetimeMethods)
str = CachedAccessor("str", StringMethods)
cat = CachedAccessor("cat", CategoricalAccessor)
plot = CachedAccessor("plot", PandasOnSparkPlotAccessor)
# ----------------------------------------------------------------------
def _apply_series_op(
self, op: Callable[["Series"], Union["Series", Column]], should_resolve: bool = False
) -> "Series":
psser_or_scol = op(self)
if isinstance(psser_or_scol, Series):
psser = psser_or_scol
else:
psser = self._with_new_scol(cast(Column, psser_or_scol))
if should_resolve:
internal = psser._internal.resolved_copy
return first_series(DataFrame(internal))
else:
return psser
def _reduce_for_stat_function(
self,
sfun: Union[Callable[[Column], Column], Callable[[Column, DataType], Column]],
name: str_type,
axis: Optional[Axis] = None,
numeric_only: bool = True,
**kwargs: Any
) -> Scalar:
"""
Applies sfun to the column and returns a scalar
Parameters
----------
sfun : the stats function to be used for aggregation
name : original pandas API name.
axis : used only for sanity check because series only support index axis.
numeric_only : not used by this implementation, but passed down by stats functions
"""
from inspect import signature
axis = validate_axis(axis)
if axis == 1:
raise ValueError("Series does not support columns axis.")
num_args = len(signature(sfun).parameters)
spark_column = self.spark.column
spark_type = self.spark.data_type
if num_args == 1:
# Only pass in the column if sfun accepts only one arg
scol = cast(Callable[[Column], Column], sfun)(spark_column)
else: # must be 2
assert num_args == 2
# Pass in both the column and its data type if sfun accepts two args
scol = cast(Callable[[Column, DataType], Column], sfun)(spark_column, spark_type)
min_count = kwargs.get("min_count", 0)
if min_count > 0:
scol = F.when(Frame._count_expr(spark_column, spark_type) >= min_count, scol)
result = unpack_scalar(self._internal.spark_frame.select(scol))
return result if result is not None else np.nan
# Override the `groupby` to specify the actual return type annotation.
def groupby(
self,
by: Union[Name, "Series", List[Union[Name, "Series"]]],
axis: Axis = 0,
as_index: bool = True,
dropna: bool = True,
) -> "SeriesGroupBy":
return cast(
"SeriesGroupBy", super().groupby(by=by, axis=axis, as_index=as_index, dropna=dropna)
)
groupby.__doc__ = Frame.groupby.__doc__
def _build_groupby(
self, by: List[Union["Series", Label]], as_index: bool, dropna: bool
) -> "SeriesGroupBy":
from pyspark.pandas.groupby import SeriesGroupBy
return SeriesGroupBy._build(self, by, as_index=as_index, dropna=dropna)
def __getitem__(self, key: Any) -> Any:
try:
if (isinstance(key, slice) and any(type(n) == int for n in [key.start, key.stop])) or (
type(key) == int
and not isinstance(self.index.spark.data_type, (IntegerType, LongType))
):
# Seems like pandas Series always uses int as positional search when slicing
# with ints, searches based on index values when the value is int.
return self.iloc[key]
return self.loc[key]
except SparkPandasIndexingError:
raise KeyError(
"Key length ({}) exceeds index depth ({})".format(
len(key), self._internal.index_level
)
)
def __getattr__(self, item: str_type) -> Any:
if item.startswith("__"):
raise AttributeError(item)
if hasattr(MissingPandasLikeSeries, item):
property_or_func = getattr(MissingPandasLikeSeries, item)
if isinstance(property_or_func, property):
return property_or_func.fget(self) # type: ignore
else:
return partial(property_or_func, self)
raise AttributeError("'Series' object has no attribute '{}'".format(item))
def _to_internal_pandas(self) -> pd.Series:
"""
Return a pandas Series directly from _internal to avoid overhead of copy.
This method is for internal use only.
"""
return self._psdf._internal.to_pandas_frame[self.name]
def __repr__(self) -> str_type:
max_display_count = get_option("display.max_rows")
if max_display_count is None:
return self._to_internal_pandas().to_string(name=self.name, dtype=self.dtype)
pser = self._psdf._get_or_create_repr_pandas_cache(max_display_count)[self.name]
pser_length = len(pser)
pser = pser.iloc[:max_display_count]
if pser_length > max_display_count:
repr_string = pser.to_string(length=True)
rest, prev_footer = repr_string.rsplit("\n", 1)
match = REPR_PATTERN.search(prev_footer)
if match is not None:
length = match.group("length")
dtype_name = str(self.dtype.name)
if self.name is None:
footer = "\ndtype: {dtype}\nShowing only the first {length}".format(
length=length, dtype=pprint_thing(dtype_name)
)
else:
footer = (
"\nName: {name}, dtype: {dtype}"
"\nShowing only the first {length}".format(
length=length, name=self.name, dtype=pprint_thing(dtype_name)
)
)
return rest + footer
return pser.to_string(name=self.name, dtype=self.dtype)
def __dir__(self) -> Iterable[str_type]:
if not isinstance(self.spark.data_type, StructType):
fields = []
else:
fields = [f for f in self.spark.data_type.fieldNames() if " " not in f]
return list(super().__dir__()) + fields
def __iter__(self) -> None:
return MissingPandasLikeSeries.__iter__(self)
if sys.version_info >= (3, 7):
# In order to support the type hints such as Series[...]. See DataFrame.__class_getitem__.
def __class_getitem__(cls, params: Any) -> Type[SeriesType]:
return _create_type_for_series_type(params)
elif (3, 5) <= sys.version_info < (3, 7):
# The implementation is in its metaclass so this flag is needed to distinguish
# pandas-on-Spark Series.
is_series = None
def unpack_scalar(sdf: SparkDataFrame) -> Any:
"""
Takes a dataframe that is supposed to contain a single row with a single scalar value,
and returns this value.
"""
l = cast(pd.DataFrame, sdf.limit(2).toPandas())
assert len(l) == 1, (sdf, l)
row = l.iloc[0]
l2 = list(row)
assert len(l2) == 1, (row, l2)
return l2[0]
@overload
def first_series(df: DataFrame) -> Series:
...
@overload
def first_series(df: pd.DataFrame) -> pd.Series:
...
def first_series(df: Union[DataFrame, pd.DataFrame]) -> Union[Series, pd.Series]:
"""
Takes a DataFrame and returns the first column of the DataFrame as a Series
"""
assert isinstance(df, (DataFrame, pd.DataFrame)), type(df)
if isinstance(df, DataFrame):
return df._psser_for(df._internal.column_labels[0])
else:
return df[df.columns[0]]
def _test() -> None:
import os
import doctest
import sys
from pyspark.sql import SparkSession
import pyspark.pandas.series
os.chdir(os.environ["SPARK_HOME"])
globs = pyspark.pandas.series.__dict__.copy()
globs["ps"] = pyspark.pandas
spark = (
SparkSession.builder.master("local[4]").appName("pyspark.pandas.series tests").getOrCreate()
)
(failure_count, test_count) = doctest.testmod(
pyspark.pandas.series,
globs=globs,
optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE,
)
spark.stop()
if failure_count:
sys.exit(-1)
if __name__ == "__main__":
_test()
| apache-2.0 |
ran0101/namebench | nb_third_party/dns/reversename.py | 248 | 2931 | # Copyright (C) 2006, 2007, 2009, 2010 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.
"""DNS Reverse Map Names.
@var ipv4_reverse_domain: The DNS IPv4 reverse-map domain, in-addr.arpa.
@type ipv4_reverse_domain: dns.name.Name object
@var ipv6_reverse_domain: The DNS IPv6 reverse-map domain, ip6.arpa.
@type ipv6_reverse_domain: dns.name.Name object
"""
import dns.name
import dns.ipv6
import dns.ipv4
ipv4_reverse_domain = dns.name.from_text('in-addr.arpa.')
ipv6_reverse_domain = dns.name.from_text('ip6.arpa.')
def from_address(text):
"""Convert an IPv4 or IPv6 address in textual form into a Name object whose
value is the reverse-map domain name of the address.
@param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1',
'::1')
@type text: str
@rtype: dns.name.Name object
"""
try:
parts = list(dns.ipv6.inet_aton(text).encode('hex_codec'))
origin = ipv6_reverse_domain
except:
parts = ['%d' % ord(byte) for byte in dns.ipv4.inet_aton(text)]
origin = ipv4_reverse_domain
parts.reverse()
return dns.name.from_text('.'.join(parts), origin=origin)
def to_address(name):
"""Convert a reverse map domain name into textual address form.
@param name: an IPv4 or IPv6 address in reverse-map form.
@type name: dns.name.Name object
@rtype: str
"""
if name.is_subdomain(ipv4_reverse_domain):
name = name.relativize(ipv4_reverse_domain)
labels = list(name.labels)
labels.reverse()
text = '.'.join(labels)
# run through inet_aton() to check syntax and make pretty.
return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))
elif name.is_subdomain(ipv6_reverse_domain):
name = name.relativize(ipv6_reverse_domain)
labels = list(name.labels)
labels.reverse()
parts = []
i = 0
l = len(labels)
while i < l:
parts.append(''.join(labels[i:i+4]))
i += 4
text = ':'.join(parts)
# run through inet_aton() to check syntax and make pretty.
return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text))
else:
raise dns.exception.SyntaxError('unknown reverse-map address family')
| apache-2.0 |
yxblee/AI-Global | py/python-twitter/setup.py | 3 | 2781 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
#
# Copyright 2007-2016 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import codecs
from setuptools import setup, find_packages
cwd = os.path.abspath(os.path.dirname(__file__))
def read(filename):
with codecs.open(os.path.join(cwd, filename), 'rb', 'utf-8') as h:
return h.read()
metadata = read(os.path.join(cwd, 'twitter', '__init__.py'))
def extract_metaitem(meta):
# swiped from https://hynek.me 's attr package
meta_match = re.search(r"""^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]""".format(meta=meta),
metadata, re.MULTILINE)
if meta_match:
return meta_match.group(1)
raise RuntimeError('Unable to find __{meta}__ string.'.format(meta=meta))
setup(
name='python-twitter',
version=extract_metaitem('version'),
license=extract_metaitem('license'),
description=extract_metaitem('description'),
long_description=(read('README.rst') + '\n\n' +
read('AUTHORS.rst') + '\n\n' +
read('CHANGES')),
author=extract_metaitem('author'),
author_email=extract_metaitem('email'),
maintainer=extract_metaitem('author'),
maintainer_email=extract_metaitem('email'),
url=extract_metaitem('url'),
download_url=extract_metaitem('download_url'),
packages=find_packages(exclude=('tests', 'docs')),
platforms=['Any'],
install_requires=['future', 'requests', 'requests-oauthlib'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
keywords='twitter api',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
],
)
| mit |
mpasternak/michaldtz-fix-552 | tests/window/MULTIPLE_SCREEN.py | 33 | 1478 | #!/usr/bin/env python
'''Test that screens can be selected for fullscreen.
Expected behaviour:
One window will be created fullscreen on the primary screen. When you
close this window, another will open on the next screen, and so
on until all screens have been tested.
Each screen will be filled with a different color:
- Screen 0: Red
- Screen 1: Green
- Screen 2: Blue
- Screen 3: Purple
The test will end when all screens have been tested.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet import window
from pyglet.gl import *
colours = [
(1, 0, 0, 1),
(0, 1, 0, 1),
(0, 0, 1, 1),
(1, 0, 1, 1)]
class MULTIPLE_SCREEN(unittest.TestCase):
def open_next_window(self):
screen = self.screens[self.index]
self.w = window.Window(screen=screen, fullscreen=True)
def on_expose(self):
self.w.switch_to()
glClearColor(*colours[self.index])
glClear(GL_COLOR_BUFFER_BIT)
self.w.flip()
def test_multiple_screen(self):
display = window.get_platform().get_default_display()
self.screens = display.get_screens()
for i in range(len(self.screens)):
self.index = i
self.open_next_window()
self.on_expose()
while not self.w.has_exit:
self.w.dispatch_events()
self.w.close()
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
Sodki/ansible | test/units/executor/test_task_result.py | 104 | 5583 | # (c) 2016, James Cammarata <jimi@sngx.net>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.executor.task_result import TaskResult
class TestTaskResult(unittest.TestCase):
def test_task_result_basic(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test loading a result with a dict
tr = TaskResult(mock_host, mock_task, dict())
# test loading a result with a JSON string
with patch('ansible.parsing.dataloader.DataLoader.load') as p:
tr = TaskResult(mock_host, mock_task, '{}')
def test_task_result_is_changed(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test with no changed in result
tr = TaskResult(mock_host, mock_task, dict())
self.assertFalse(tr.is_changed())
# test with changed in the result
tr = TaskResult(mock_host, mock_task, dict(changed=True))
self.assertTrue(tr.is_changed())
# test with multiple results but none changed
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
self.assertFalse(tr.is_changed())
# test with multiple results and one changed
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(changed=False), dict(changed=True), dict(some_key=False)]))
self.assertTrue(tr.is_changed())
def test_task_result_is_skipped(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test with no skipped in result
tr = TaskResult(mock_host, mock_task, dict())
self.assertFalse(tr.is_skipped())
# test with skipped in the result
tr = TaskResult(mock_host, mock_task, dict(skipped=True))
self.assertTrue(tr.is_skipped())
# test with multiple results but none skipped
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
self.assertFalse(tr.is_skipped())
# test with multiple results and one skipped
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(skipped=False), dict(skipped=True), dict(some_key=False)]))
self.assertFalse(tr.is_skipped())
# test with multiple results and all skipped
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(skipped=True), dict(skipped=True), dict(skipped=True)]))
self.assertTrue(tr.is_skipped())
# test with multiple squashed results (list of strings)
# first with the main result having skipped=False
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=["a", "b", "c"], skipped=False))
self.assertFalse(tr.is_skipped())
# then with the main result having skipped=True
tr = TaskResult(mock_host, mock_task, dict(results=["a", "b", "c"], skipped=True))
self.assertTrue(tr.is_skipped())
def test_task_result_is_unreachable(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test with no unreachable in result
tr = TaskResult(mock_host, mock_task, dict())
self.assertFalse(tr.is_unreachable())
# test with unreachable in the result
tr = TaskResult(mock_host, mock_task, dict(unreachable=True))
self.assertTrue(tr.is_unreachable())
# test with multiple results but none unreachable
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
self.assertFalse(tr.is_unreachable())
# test with multiple results and one unreachable
mock_task.loop = 'foo'
tr = TaskResult(mock_host, mock_task, dict(results=[dict(unreachable=False), dict(unreachable=True), dict(some_key=False)]))
self.assertTrue(tr.is_unreachable())
def test_task_result_is_failed(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test with no failed in result
tr = TaskResult(mock_host, mock_task, dict())
self.assertFalse(tr.is_failed())
# test failed result with rc values
tr = TaskResult(mock_host, mock_task, dict(rc=0))
self.assertFalse(tr.is_failed())
tr = TaskResult(mock_host, mock_task, dict(rc=1))
self.assertTrue(tr.is_failed())
# test with failed in result
tr = TaskResult(mock_host, mock_task, dict(failed=True))
self.assertTrue(tr.is_failed())
# test with failed_when in result
tr = TaskResult(mock_host, mock_task, dict(failed_when_result=True))
self.assertTrue(tr.is_failed())
| gpl-3.0 |
wathen/PhD | MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/SplitMatrix/ScottTest/MHDgenerator/MHDfluid.py | 1 | 10096 | #!/usr/bin/python
# interpolate scalar gradient onto nedelec space
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
from dolfin import *
import mshr
Print = PETSc.Sys.Print
# from MatrixOperations import *
import numpy as np
import PETScIO as IO
import common
import scipy
import scipy.io
import time
import BiLinear as forms
import IterOperations as Iter
import MatrixOperations as MO
import CheckPetsc4py as CP
import ExactSol
import Solver as S
import MHDmatrixPrecondSetup as PrecondSetup
import NSprecondSetup
import MHDprec as MHDpreconditioner
import memory_profiler
import gc
import MHDmulti
import MHDmatrixSetup as MHDsetup
import Generator
#@profile
m = 2
set_log_active(False)
errL2u =np.zeros((m-1,1))
errH1u =np.zeros((m-1,1))
errL2p =np.zeros((m-1,1))
errL2b =np.zeros((m-1,1))
errCurlb =np.zeros((m-1,1))
errL2r =np.zeros((m-1,1))
errH1r =np.zeros((m-1,1))
l2uorder = np.zeros((m-1,1))
H1uorder =np.zeros((m-1,1))
l2porder = np.zeros((m-1,1))
l2border = np.zeros((m-1,1))
Curlborder =np.zeros((m-1,1))
l2rorder = np.zeros((m-1,1))
H1rorder = np.zeros((m-1,1))
NN = np.zeros((m-1,1))
DoF = np.zeros((m-1,1))
Velocitydim = np.zeros((m-1,1))
Magneticdim = np.zeros((m-1,1))
Pressuredim = np.zeros((m-1,1))
Lagrangedim = np.zeros((m-1,1))
Wdim = np.zeros((m-1,1))
iterations = np.zeros((m-1,1))
SolTime = np.zeros((m-1,1))
udiv = np.zeros((m-1,1))
MU = np.zeros((m-1,1))
level = np.zeros((m-1,1))
NSave = np.zeros((m-1,1))
Mave = np.zeros((m-1,1))
TotalTime = np.zeros((m-1,1))
nn = 2
dim = 2
ShowResultPlots = 'yes'
split = 'Linear'
MU[0]= 1e0
for xx in xrange(1,m):
print xx
level[xx-1] = xx + 1
nn = 2**(level[xx-1])
# Create mesh and define function space
nn = int(nn)
NN[xx-1] = nn/2
parameters["form_compiler"]["quadrature_degree"] = -1
mesh, boundaries, domains = Generator.Domain(nn)
order = 2
parameters['reorder_dofs_serial'] = False
Velocity = VectorFunctionSpace(mesh, "CG", order)
Pressure = FunctionSpace(mesh, "CG", order-1)
Magnetic = FunctionSpace(mesh, "N1curl", order-1)
Lagrange = FunctionSpace(mesh, "CG", order-1)
W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange])
# W = Velocity*Pressure*Magnetic*Lagrange
Velocitydim[xx-1] = Velocity.dim()
Pressuredim[xx-1] = Pressure.dim()
Magneticdim[xx-1] = Magnetic.dim()
Lagrangedim[xx-1] = Lagrange.dim()
Wdim[xx-1] = W.dim()
print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n"
dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()]
def boundary(x, on_boundary):
return on_boundary
FSpaces = [Velocity,Pressure,Magnetic,Lagrange]
kappa = 1.0
Mu_m = 10.0
MU = 1.0
N = FacetNormal(mesh)
IterType = 'Full'
Split = "No"
Saddle = "No"
Stokes = "No"
SetupType = 'python-class'
params = [kappa,Mu_m,MU]
F_M = Expression(("0.0","0.0","0.0"))
F_S = Expression(("0.0","0.0","0.0"))
n = FacetNormal(mesh)
r0 = Expression(("0.0"))
b0 = Expression(("1.0", "0.0", "0.0"))
u0 = Expression(("1.0", "0", "0.0"))
Hiptmairtol = 1e-6
HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params)
B0 = 1.
delta = 0.1
x_on = 4.
x_off = 6.
u0, p0, b0, r0, Laplacian, Advection, gradPres, NScouple, CurlCurl, gradLagr, Mcouple = Generator.ExactSolution(params, B0, delta, x_on, x_off)
F_NS = -MU*Laplacian + Advection + gradPres - kappa*NScouple
if kappa == 0.0:
F_M = Mu_m*CurlCurl + gradLagr - kappa*Mcouple
else:
F_M = Mu_m*kappa*CurlCurl + gradLagr - kappa*Mcouple
MO.PrintStr("Seting up initial guess matricies",2,"=","\n\n","\n")
u_k, p_k = Generator.Stokes(Velocity, Pressure, F_S, u0, params, boundaries, domains)
b_k, r_k = Generator.Maxwell(Magnetic, Lagrange, F_M, b0, params, HiptmairMatrices, Hiptmairtol)
x = Iter.u_prev(u_k,p_k,b_k,r_k)
(u, p, b, r) = TrialFunctions(W)
(v, q, c, s) = TestFunctions(W)
m11 = params[1]*params[0]*inner(curl(b),curl(c))*dx
m21 = inner(c,grad(r))*dx
m12 = inner(b,grad(s))*dx
a11 = params[2]*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1./2)*div(u_k)*inner(u,v)*dx - (1./2)*inner(u_k,n)*inner(u,v)*ds
a12 = -div(v)*p*dx
a21 = -div(u)*q*dx
CoupleT = params[0]*inner(cross(v,b_k),curl(b))*dx
Couple = -params[0]*inner(cross(u,b_k),curl(c))*dx
a = m11 + m12 + m21 + a11 + a21 + a12 + Couple + CoupleT
Lns = inner(F_S, v)*dx #+ inner(Neumann,v)*ds(2)
Lmaxwell = inner(F_M, c)*dx
m11 = params[1]*params[0]*inner(curl(b_k),curl(c))*dx
m21 = inner(c,grad(r_k))*dx
m12 = inner(b_k,grad(s))*dx
a11 = params[2]*inner(grad(v), grad(u_k))*dx + inner((grad(u_k)*u_k),v)*dx + (1./2)*div(u_k)*inner(u_k,v)*dx - (1./2)*inner(u_k,n)*inner(u_k,v)*ds
a12 = -div(v)*p_k*dx
a21 = -div(u_k)*q*dx
CoupleT = params[0]*inner(cross(v,b_k),curl(b_k))*dx
Couple = -params[0]*inner(cross(u_k,b_k),curl(c))*dx
L = Lns + Lmaxwell - (m11 + m12 + m21 + a11 + a21 + a12 + Couple + CoupleT)
# u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-10,Neumann=None,options ="New")
ones = Function(Pressure)
ones.vector()[:]=(0*ones.vector().array()+1)
# pConst = - assemble(p_k*dx)/assemble(ones*dx)
# p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx)
KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU)
kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)
#plot(b_k)
IS = MO.IndexSet(W, 'Blocks')
eps = 1.0 # error measure ||u-u_k||
tol = 1.0E-4 # tolerance
iter = 0 # iteration counter
maxiter = 10 # max no of iterations allowed
SolutionTime = 0
outer = 0
u_is = PETSc.IS().createGeneral(range(Velocity.dim()))
NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim()))
M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim()))
OuterTol = 1e-5
InnerTol = 1e-5
NSits =0
Mits =0
TotalStart =time.time()
SolutionTime = 0
while eps > tol and iter < maxiter:
iter += 1
MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n")
bcu1 = DirichletBC(W.sub(0), Expression(("0.0","0.0","0.0")), boundaries, 1)
bcu2 = DirichletBC(W.sub(0), Expression(("0.0","0.0","0.0")), boundaries, 2)
bcb = DirichletBC(W.sub(2), Expression(("0.0","0.0","0.0")), boundary)
bcr = DirichletBC(W.sub(3), Expression("0.0"), boundary)
bcs = [bcu1, bcu2, bcb, bcr]
A, b = assemble_system(a, L, bcs)
# if iter == 2:
# ss
A, b = CP.Assemble(A,b)
u = b.duplicate()
n = FacetNormal(mesh)
b_t = TrialFunction(Velocity)
c_t = TestFunction(Velocity)
mat = as_matrix([[b_k[2]*b_k[2]+b_k[1]*b_k[1],-b_k[1]*b_k[0],-b_k[0]*b_k[2]],
[-b_k[1]*b_k[0],b_k[0]*b_k[0]+b_k[2]*b_k[2],-b_k[2]*b_k[1]],
[-b_k[0]*b_k[2],-b_k[1]*b_k[2],b_k[0]*b_k[0]+b_k[1]*b_k[1]]])
aa = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh())
ShiftedMass = assemble(aa)
for bc in [bcu1, bcu2]:
bc.apply(ShiftedMass)
ShiftedMass = CP.Assemble(ShiftedMass)
kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass)
stime = time.time()
u, mits,nsits = S.solve(A,b,u,params,W,'Direct',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF)
Soltime = time.time()- stime
MO.StrTimePrint("MHD solve, time: ", Soltime)
Mits += mits
NSits += nsits
SolutionTime += Soltime
# print x.array + u.array
u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter)
p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx)
u_k.assign(u1)
p_k.assign(p1)
b_k.assign(b1)
r_k.assign(r1)
uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
x = IO.arrayToVec(uOld)
SolTime[xx-1] = SolutionTime/iter
NSave[xx-1] = (float(NSits)/iter)
Mave[xx-1] = (float(Mits)/iter)
iterations[xx-1] = iter
TotalTime[xx-1] = time.time() - TotalStart
XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0)
dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()]
import pandas as pd
print "\n\n Iteration table"
if IterType == "Full":
IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",]
else:
IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"]
IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1)
IterTable= pd.DataFrame(IterValues, columns = IterTitles)
if IterType == "Full":
IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f")
IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f")
else:
IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f")
IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f")
print IterTable.to_latex()
b = b_k.vector().array()
b = b/np.linalg.norm(b)
B = Function(Magnetic)
B.vector()[:] = b
p = plot(u_k)
p.write_png()
p = plot(p_k)
p.write_png()
p = plot(b_k)
p.write_png()
p = plot(r_k)
p.write_png()
file1 = File("solutions/u.pvd")
file2 = File("solutions/p.pvd")
file3 = File("solutions/b.pvd")
file4 = File("solutions/r.pvd")
file1 << u_k
file2 << p_k
file3 << b_k
file4 << r_k
ssss
interactive()
| mit |
AuyaJackie/odoo | addons/website_sale/models/product.py | 262 | 10108 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import tools
from openerp.osv import osv, fields
class product_style(osv.Model):
_name = "product.style"
_columns = {
'name' : fields.char('Style Name', required=True),
'html_class': fields.char('HTML Classes'),
}
class product_pricelist(osv.Model):
_inherit = "product.pricelist"
_columns = {
'code': fields.char('Promotional Code'),
}
class product_public_category(osv.osv):
_name = "product.public.category"
_description = "Public Category"
_order = "sequence, name"
_constraints = [
(osv.osv._check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id'])
]
def name_get(self, cr, uid, ids, context=None):
res = []
for cat in self.browse(cr, uid, ids, context=context):
names = [cat.name]
pcat = cat.parent_id
while pcat:
names.append(pcat.name)
pcat = pcat.parent_id
res.append((cat.id, ' / '.join(reversed(names))))
return res
def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
res = self.name_get(cr, uid, ids, context=context)
return dict(res)
def _get_image(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = tools.image_get_resized_images(obj.image)
return result
def _set_image(self, cr, uid, id, name, value, args, context=None):
return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
_columns = {
'name': fields.char('Name', required=True, translate=True),
'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
'parent_id': fields.many2one('product.public.category','Parent Category', select=True),
'child_id': fields.one2many('product.public.category', 'parent_id', string='Children Categories'),
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of product categories."),
# NOTE: there is no 'default image', because by default we don't show thumbnails for categories. However if we have a thumbnail
# for at least one category, then we display a default image on the other, so that the buttons have consistent styling.
# In this case, the default image is set by the js code.
# NOTE2: image: all image fields are base64 encoded and PIL-supported
'image': fields.binary("Image",
help="This field holds the image used as image for the category, limited to 1024x1024px."),
'image_medium': fields.function(_get_image, fnct_inv=_set_image,
string="Medium-sized image", type="binary", multi="_get_image",
store={
'product.public.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Medium-sized image of the category. It is automatically "\
"resized as a 128x128px image, with aspect ratio preserved. "\
"Use this field in form views or some kanban views."),
'image_small': fields.function(_get_image, fnct_inv=_set_image,
string="Smal-sized image", type="binary", multi="_get_image",
store={
'product.public.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Small-sized image of the category. It is automatically "\
"resized as a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required."),
}
class product_template(osv.Model):
_inherit = ["product.template", "website.seo.metadata"]
_order = 'website_published desc, website_sequence desc, name'
_name = 'product.template'
_mail_post_access = 'read'
def _website_url(self, cr, uid, ids, field_name, arg, context=None):
res = dict.fromkeys(ids, '')
for product in self.browse(cr, uid, ids, context=context):
res[product.id] = "/shop/product/%s" % (product.id,)
return res
_columns = {
# TODO FIXME tde: when website_mail/mail_thread.py inheritance work -> this field won't be necessary
'website_message_ids': fields.one2many(
'mail.message', 'res_id',
domain=lambda self: [
'&', ('model', '=', self._name), ('type', '=', 'comment')
],
string='Website Comments',
),
'website_published': fields.boolean('Available in the website', copy=False),
'website_description': fields.html('Description for the website', translate=True),
'alternative_product_ids': fields.many2many('product.template','product_alternative_rel','src_id','dest_id', string='Alternative Products', help='Appear on the product page'),
'accessory_product_ids': fields.many2many('product.product','product_accessory_rel','src_id','dest_id', string='Accessory Products', help='Appear on the shopping cart'),
'website_size_x': fields.integer('Size X'),
'website_size_y': fields.integer('Size Y'),
'website_style_ids': fields.many2many('product.style', string='Styles'),
'website_sequence': fields.integer('Sequence', help="Determine the display order in the Website E-commerce"),
'website_url': fields.function(_website_url, string="Website url", type="char"),
'public_categ_ids': fields.many2many('product.public.category', string='Public Category', help="Those categories are used to group similar products for e-commerce."),
}
def _defaults_website_sequence(self, cr, uid, *l, **kwargs):
cr.execute('SELECT MAX(website_sequence)+1 FROM product_template')
next_sequence = cr.fetchone()[0] or 0
return next_sequence
_defaults = {
'website_size_x': 1,
'website_size_y': 1,
'website_sequence': _defaults_website_sequence,
'website_published': False,
}
def set_sequence_top(self, cr, uid, ids, context=None):
cr.execute('SELECT MAX(website_sequence) FROM product_template')
max_sequence = cr.fetchone()[0] or 0
return self.write(cr, uid, ids, {'website_sequence': max_sequence + 1}, context=context)
def set_sequence_bottom(self, cr, uid, ids, context=None):
cr.execute('SELECT MIN(website_sequence) FROM product_template')
min_sequence = cr.fetchone()[0] or 0
return self.write(cr, uid, ids, {'website_sequence': min_sequence -1}, context=context)
def set_sequence_up(self, cr, uid, ids, context=None):
product = self.browse(cr, uid, ids[0], context=context)
cr.execute(""" SELECT id, website_sequence FROM product_template
WHERE website_sequence > %s AND website_published = %s ORDER BY website_sequence ASC LIMIT 1""" % (product.website_sequence, product.website_published))
prev = cr.fetchone()
if prev:
self.write(cr, uid, [prev[0]], {'website_sequence': product.website_sequence}, context=context)
return self.write(cr, uid, [ids[0]], {'website_sequence': prev[1]}, context=context)
else:
return self.set_sequence_top(cr, uid, ids, context=context)
def set_sequence_down(self, cr, uid, ids, context=None):
product = self.browse(cr, uid, ids[0], context=context)
cr.execute(""" SELECT id, website_sequence FROM product_template
WHERE website_sequence < %s AND website_published = %s ORDER BY website_sequence DESC LIMIT 1""" % (product.website_sequence, product.website_published))
next = cr.fetchone()
if next:
self.write(cr, uid, [next[0]], {'website_sequence': product.website_sequence}, context=context)
return self.write(cr, uid, [ids[0]], {'website_sequence': next[1]}, context=context)
else:
return self.set_sequence_bottom(cr, uid, ids, context=context)
class product_product(osv.Model):
_inherit = "product.product"
def _website_url(self, cr, uid, ids, field_name, arg, context=None):
res = {}
for product in self.browse(cr, uid, ids, context=context):
res[product.id] = "/shop/product/%s" % (product.product_tmpl_id.id,)
return res
_columns = {
'website_url': fields.function(_website_url, string="Website url", type="char"),
}
class product_attribute(osv.Model):
_inherit = "product.attribute"
_columns = {
'type': fields.selection([('radio', 'Radio'), ('select', 'Select'), ('color', 'Color'), ('hidden', 'Hidden')], string="Type"),
}
_defaults = {
'type': lambda *a: 'radio',
}
class product_attribute_value(osv.Model):
_inherit = "product.attribute.value"
_columns = {
'color': fields.char("HTML Color Index", help="Here you can set a specific HTML color index (e.g. #ff0000) to display the color on the website if the attibute type is 'Color'."),
}
| agpl-3.0 |
subodhchhabra/airflow | airflow/contrib/utils/sendgrid.py | 8 | 4274 | # -*- 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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import base64
import mimetypes
import os
import sendgrid
from sendgrid.helpers.mail import Attachment, Content, Email, Mail, \
Personalization, CustomArg, Category
from airflow.utils.email import get_email_address_list
from airflow.utils.log.logging_mixin import LoggingMixin
def send_email(to, subject, html_content, files=None,
dryrun=False, cc=None, bcc=None,
mime_subtype='mixed', **kwargs):
"""
Send an email with html content using sendgrid.
To use this plugin:
0. include sendgrid subpackage as part of your Airflow installation, e.g.,
pip install airflow[sendgrid]
1. update [email] backend in airflow.cfg, i.e.,
[email]
email_backend = airflow.contrib.utils.sendgrid.send_email
2. configure Sendgrid specific environment variables at all Airflow instances:
SENDGRID_MAIL_FROM={your-mail-from}
SENDGRID_API_KEY={your-sendgrid-api-key}.
"""
mail = Mail()
from_email = kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM')
from_name = kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER')
mail.from_email = Email(from_email, from_name)
mail.subject = subject
# Add the recipient list of to emails.
personalization = Personalization()
to = get_email_address_list(to)
for to_address in to:
personalization.add_to(Email(to_address))
if cc:
cc = get_email_address_list(cc)
for cc_address in cc:
personalization.add_cc(Email(cc_address))
if bcc:
bcc = get_email_address_list(bcc)
for bcc_address in bcc:
personalization.add_bcc(Email(bcc_address))
# Add custom_args to personalization if present
pers_custom_args = kwargs.get('personalization_custom_args', None)
if isinstance(pers_custom_args, dict):
for key in pers_custom_args.keys():
personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))
mail.add_personalization(personalization)
mail.add_content(Content('text/html', html_content))
categories = kwargs.get('categories', [])
for cat in categories:
mail.add_category(Category(cat))
# Add email attachment.
for fname in files or []:
basename = os.path.basename(fname)
attachment = Attachment()
with open(fname, "rb") as f:
attachment.content = base64.b64encode(f.read())
attachment.type = mimetypes.guess_type(basename)[0]
attachment.filename = basename
attachment.disposition = "attachment"
attachment.content_id = '<%s>' % basename
mail.add_attachment(attachment)
_post_sendgrid_mail(mail.get())
def _post_sendgrid_mail(mail_data):
log = LoggingMixin().log
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
response = sg.client.mail.send.post(request_body=mail_data)
# 2xx status code.
if response.status_code >= 200 and response.status_code < 300:
log.info('Email with subject %s is successfully sent to recipients: %s' %
(mail_data['subject'], mail_data['personalizations']))
else:
log.warning('Failed to send out email with subject %s, status code: %s' %
(mail_data['subject'], response.status_code))
| apache-2.0 |
ferabra/edx-platform | cms/djangoapps/contentstore/management/commands/tests/test_export_convert_format.py | 69 | 2381 | """
Test for export_convert_format.
"""
from unittest import TestCase
from django.core.management import call_command, CommandError
from django.conf import settings
from tempfile import mkdtemp
import shutil
from path import Path as path
from contentstore.management.commands.export_convert_format import Command, extract_source
from xmodule.tests.helpers import directories_equal
class ConvertExportFormat(TestCase):
"""
Tests converting between export formats.
"""
def setUp(self):
""" Common setup. """
super(ConvertExportFormat, self).setUp()
self.temp_dir = mkdtemp(dir=settings.DATA_DIR)
self.addCleanup(shutil.rmtree, self.temp_dir)
self.data_dir = path(__file__).realpath().parent / 'data'
self.version0 = self.data_dir / "Version0_drafts.tar.gz"
self.version1 = self.data_dir / "Version1_drafts.tar.gz"
self.command = Command()
def test_no_args(self):
""" Test error condition of no arguments. """
errstring = "export requires two arguments"
with self.assertRaisesRegexp(CommandError, errstring):
self.command.handle()
def test_version1_archive(self):
"""
Smoke test for creating a version 1 archive from a version 0.
"""
call_command('export_convert_format', self.version0, self.temp_dir)
output = path(self.temp_dir) / 'Version0_drafts_version_1.tar.gz'
self.assertTrue(self._verify_archive_equality(output, self.version1))
def test_version0_archive(self):
"""
Smoke test for creating a version 0 archive from a version 1.
"""
call_command('export_convert_format', self.version1, self.temp_dir)
output = path(self.temp_dir) / 'Version1_drafts_version_0.tar.gz'
self.assertTrue(self._verify_archive_equality(output, self.version0))
def _verify_archive_equality(self, file1, file2):
"""
Helper function for determining if 2 archives are equal.
"""
temp_dir_1 = mkdtemp(dir=settings.DATA_DIR)
temp_dir_2 = mkdtemp(dir=settings.DATA_DIR)
try:
extract_source(file1, temp_dir_1)
extract_source(file2, temp_dir_2)
return directories_equal(temp_dir_1, temp_dir_2)
finally:
shutil.rmtree(temp_dir_1)
shutil.rmtree(temp_dir_2)
| agpl-3.0 |
ksmit799/Toontown-Source | toontown/coghq/BossbotCountryClubGreenRoom_Action02.py | 5 | 2122 | from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_12/models/bossbotHQ/BossbotGreenRoom_A',
'wantDoors': 1},
1001: {'type': 'editMgr',
'name': 'EditMgr',
'parentEntId': 0,
'insertEntity': None,
'removeEntity': None,
'requestNewEntity': None,
'requestSave': None},
0: {'type': 'zone',
'name': 'UberZone',
'comment': '',
'parentEntId': 0,
'scale': 1,
'description': '',
'visibility': []},
110301: {'type': 'door',
'name': '<unnamed>',
'comment': '',
'parentEntId': 110303,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1,
'color': Vec4(1, 1, 1, 1),
'isLock0Unlocked': 1,
'isLock1Unlocked': 0,
'isLock2Unlocked': 1,
'isLock3Unlocked': 1,
'isOpen': 0,
'isOpenEvent': 0,
'isVisBlocker': 0,
'secondsOpen': 1,
'unlock0Event': 0,
'unlock1Event': 110302,
'unlock2Event': 0,
'unlock3Event': 0},
110302: {'type': 'golfGreenGame',
'name': '<unnamed>',
'comment': '',
'parentEntId': 0,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1,
'puzzleBase': 3,
'puzzlePerPlayer': 3,
'timeToPlay': 180,
'cellId': 0,
'switchId': 0},
10002: {'type': 'nodepath',
'name': 'props',
'comment': '',
'parentEntId': 0,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1},
110303: {'type': 'nodepath',
'name': '<unnamed>',
'comment': '',
'parentEntId': 0,
'pos': Point3(40.9635, 2, 0),
'hpr': Vec3(270, 0, 0),
'scale': Vec3(1, 1, 1)}}
Scenario0 = {}
levelSpec = {'globalEntities': GlobalEntities,
'scenarios': [Scenario0]}
| mit |
amith01994/intellij-community | python/lib/Lib/site-packages/django/conf/global_settings.py | 73 | 20942 | # Default Django settings. Override these with settings in the module
# pointed-to by the DJANGO_SETTINGS_MODULE environment variable.
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
gettext_noop = lambda s: s
####################
# CORE #
####################
DEBUG = False
TEMPLATE_DEBUG = False
# Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing siutations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS = False
# Whether to use the "Etag" header. This saves bandwidth but slows down performance.
USE_ETAGS = False
# People who get code error notifications.
# In the format (('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com'))
ADMINS = ()
# Tuple of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = ()
# Local time zone for this installation. All choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities).
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'
# Languages we provide translations for, out of the box. The language name
# should be the utf-8 encoded local name for the language.
LANGUAGES = (
('ar', gettext_noop('Arabic')),
('bg', gettext_noop('Bulgarian')),
('bn', gettext_noop('Bengali')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('en-gb', gettext_noop('British English')),
('es', gettext_noop('Spanish')),
('es-ar', gettext_noop('Argentinian Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('fy-nl', gettext_noop('Frisian')),
('ga', gettext_noop('Irish')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hu', gettext_noop('Hungarian')),
('id', gettext_noop('Indonesian')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('nl', gettext_noop('Dutch')),
('no', gettext_noop('Norwegian')),
('nb', gettext_noop('Norwegian Bokmal')),
('nn', gettext_noop('Norwegian Nynorsk')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sr-latn', gettext_noop('Serbian Latin')),
('sv', gettext_noop('Swedish')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('uk', gettext_noop('Ukrainian')),
('vi', gettext_noop('Vietnamese')),
('zh-cn', gettext_noop('Simplified Chinese')),
('zh-tw', gettext_noop('Traditional Chinese')),
)
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ("he", "ar", "fa")
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = ()
LANGUAGE_COOKIE_NAME = 'django_language'
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale
USE_L10N = False
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various e-mails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_CHARSET = 'utf-8'
# Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET = 'utf-8'
# E-mail address that error messages come from.
SERVER_EMAIL = 'root@localhost'
# Whether to send broken-link e-mails.
SEND_BROKEN_LINK_EMAILS = False
# Database connection info.
# Legacy format
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
DATABASE_OPTIONS = {} # Set to empty dictionary for default.
# New format
DATABASES = {
}
# Classes used to implement db routing behaviour
DATABASE_ROUTERS = []
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending e-mail.
EMAIL_HOST = 'localhost'
# Port for sending e-mail.
EMAIL_PORT = 25
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
# List of strings representing installed apps.
INSTALLED_APPS = ()
# List of locations of the template source files, in search order.
TEMPLATE_DIRS = ()
# List of callables that know how to import templates from various sources.
# See the comments in django/core/template/loader.py for interface
# documentation.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
# 'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
# Output to use in template system for invalid (e.g. misspelled) variables.
TEMPLATE_STRING_IF_INVALID = ''
# Default e-mail address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
# Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers. Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX = '[Django] '
# Whether to append trailing slashes to URLs.
APPEND_SLASH = True
# Whether to prepend the "www." subdomain to URLs that don't have it.
PREPEND_WWW = False
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = (
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search')
# )
DISALLOWED_USER_AGENTS = ()
ABSOLUTE_URL_OVERRIDES = {}
# Tuple of strings representing allowed prefixes for the {% ssi %} tag.
# Example: ('/home/html', '/var/www')
ALLOWED_INCLUDE_ROOTS = ()
# If this is a admin settings module, this should be a list of
# settings modules (in the format 'foo.bar.baz') for which this admin
# is an admin.
ADMIN_FOR = ()
# 404s that may be ignored.
IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php')
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY = ''
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
# 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.
# Example: "http://media.lawrence.com/media/"
MEDIA_URL = ''
# Absolute path to the directory that holds static files.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = None
# List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS = (
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
)
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
# (i.e. "/tmp" on *nix systems).
FILE_UPLOAD_TEMP_DIR = None
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html.
FILE_UPLOAD_PERMISSIONS = None
# Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
# named as the locales, containing a formats.py file
# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
FORMAT_MODULE_PATH = None
# Default formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'N j, Y'
# Default formatting for datetime objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATETIME_FORMAT = 'N j, Y, P'
# Default formatting for time objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
TIME_FORMAT = 'P'
# Default formatting for date objects when only the year and month are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
YEAR_MONTH_FORMAT = 'F Y'
# Default formatting for date objects when only the month and day are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MONTH_DAY_FORMAT = 'F j'
# Default short formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATE_FORMAT = 'm/d/Y'
# Default short formatting for datetime objects.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATETIME_FORMAT = 'm/d/Y P'
# Default formats to be used when parsing dates from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
)
# Default formats to be used when parsing times from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
# Default formats to be used when parsing dates and times from input boxes,
# in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%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'
)
# First day of week, to be used on calendars
# 0 means Sunday, 1 means Monday...
FIRST_DAY_OF_WEEK = 0
# Decimal separator symbol
DECIMAL_SEPARATOR = '.'
# Boolean that sets whether to add thousand separator when formatting numbers
USE_THOUSAND_SEPARATOR = False
# Number of digits that will be together, when spliting them by
# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...
NUMBER_GROUPING = 0
# Thousand separator symbol
THOUSAND_SEPARATOR = ','
# Do you want to manage transactions manually?
# Hint: you really don't!
TRANSACTIONS_MANAGED = False
# The User-Agent string to use when checking for URL validity through the
# isExistingURL validator.
from django import get_version
URL_VALIDATOR_USER_AGENT = "Django/%s (http://www.djangoproject.com)" % get_version()
# The tablespaces to use for each model when not specified otherwise.
DEFAULT_TABLESPACE = ''
DEFAULT_INDEX_TABLESPACE = ''
##############
# MIDDLEWARE #
##############
# List of middleware classes to use. Order is important; in the request phase,
# this middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
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',
# 'django.middleware.http.ConditionalGetMiddleware',
# 'django.middleware.gzip.GZipMiddleware',
)
############
# SESSIONS #
############
SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want.
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie.
SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_PATH = '/' # The path of the session cookie.
SESSION_COOKIE_HTTPONLY = False # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed.
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data
SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default.
#########
# CACHE #
#########
# New format
CACHES = {
}
# The cache backend to use. See the docstring in django.core.cache for the
# possible values.
CACHE_BACKEND = 'locmem://'
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default'
####################
# COMMENTS #
####################
COMMENTS_ALLOW_PROFANITIES = False
# The profanities that will trigger a validation error in the
# 'hasNoProfanities' validator. All of these should be in lowercase.
PROFANITIES_LIST = ()
# The group ID that designates which users are banned.
# Set to None if you're not using it.
COMMENTS_BANNED_USERS_GROUP = None
# The group ID that designates which users can moderate comments.
# Set to None if you're not using it.
COMMENTS_MODERATORS_GROUP = None
# The group ID that designates the users whose comments should be e-mailed to MANAGERS.
# Set to None if you're not using it.
COMMENTS_SKETCHY_USERS_GROUP = None
# The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each
# user. Set this to 0 if you want to disable it.
COMMENTS_FIRST_FEW = 0
# A tuple of IP addresses that have been banned from participating in various
# Django-powered features.
BANNED_IPS = ()
##################
# AUTHENTICATION #
##################
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
LOGIN_URL = '/accounts/login/'
LOGOUT_URL = '/accounts/logout/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
# The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3
########
# CSRF #
########
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
# Name and domain for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_DOMAIN = None
############
# MESSAGES #
############
# Class to use as messges backend
MESSAGE_STORAGE = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
###########
# LOGGING #
###########
# The callable to use to configure logging
LOGGING_CONFIG = 'django.utils.log.dictConfig'
# The default logging configuration. This sends an email to
# the site admins on every HTTP 500 error. All other log
# records are sent to the bit bucket.
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,
},
}
}
###########
# TESTING #
###########
# The name of the class to use to run the test suite
TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
# The name of the database to use for testing purposes.
# If None, a name of 'test_' + DATABASE_NAME will be assumed
TEST_DATABASE_NAME = None
# Strings used to set the character set and collation order for the test
# database. These values are passed literally to the server, so they are
# backend-dependent. If None, no special settings are sent (system defaults are
# used).
TEST_DATABASE_CHARSET = None
TEST_DATABASE_COLLATION = None
############
# FIXTURES #
############
# The list of directories to search for fixtures
FIXTURE_DIRS = ()
###############
# STATICFILES #
###############
# A list of locations of additional static files
STATICFILES_DIRS = ()
# The default file storage backend used during the build process
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# 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',
)
# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
| apache-2.0 |
backtou/longlab | gr-digital/python/crc.py | 15 | 1284 | #
# Copyright 2005,2007,2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gru
import digital_swig
import struct
def gen_and_append_crc32(s):
crc = digital_swig.crc32(s)
return s + struct.pack(">I", gru.hexint(crc) & 0xFFFFFFFF)
def check_crc32(s):
if len(s) < 4:
return (False, '')
msg = s[:-4]
#print "msg = '%s'" % (msg,)
actual = digital_swig.crc32(msg)
(expected,) = struct.unpack(">I", s[-4:])
# print "actual =", hex(actual), "expected =", hex(expected)
return (actual == expected, msg)
| gpl-3.0 |
TangXT/GreatCatMOOC | cms/djangoapps/contentstore/management/commands/export.py | 33 | 1181 | """
Script for exporting courseware from Mongo to a tar.gz file
"""
import os
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
from xmodule.course_module import CourseDescriptor
class Command(BaseCommand):
"""
Export the specified data directory into the default ModuleStore
"""
help = 'Export the specified data directory into the default ModuleStore'
def handle(self, *args, **options):
"Execute the command"
if len(args) != 2:
raise CommandError("export requires two arguments: <course location> <output path>")
course_id = args[0]
output_path = args[1]
print("Exporting course id = {0} to {1}".format(course_id, output_path))
location = CourseDescriptor.id_to_location(course_id)
root_dir = os.path.dirname(output_path)
course_dir = os.path.splitext(os.path.basename(output_path))[0]
export_to_xml(modulestore('direct'), contentstore(), location, root_dir, course_dir, modulestore())
| agpl-3.0 |
ogenstad/ansible | lib/ansible/modules/utilities/logic/import_tasks.py | 71 | 1471 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'
}
DOCUMENTATION = '''
---
author: Ansible Core Team (@ansible)
module: import_tasks
short_description: Import a task list
description:
- Imports a list of tasks to be added to the current playbook for subsequent execution.
version_added: "2.4"
options:
free-form:
description:
- The name of the imported file is specified directly without any other option.
- Most keywords, including loops and conditionals, only applied to the imported tasks, not to this statement
itself. If you need any of those to apply, use M(include_tasks) instead.
notes:
- This is a core feature of Ansible, rather than a module, and cannot be overridden like a module.
'''
EXAMPLES = """
- hosts: all
tasks:
- debug:
msg: task1
- name: Include task list in play
import_tasks: stuff.yaml
- debug:
msg: task10
- hosts: all
tasks:
- debug:
msg: task1
- name: Apply conditional to all imported tasks
import_tasks: stuff.yaml
when: hostvar is defined
"""
RETURN = """
# This module does not return anything except tasks to execute.
"""
| gpl-3.0 |
janslifka/imagediffer | imagediffer/core/differ.py | 1 | 3600 | """Differ module contains functions for comparing images and creating diff images
"""
import numpy as np
from PIL import Image
from ssim import compute_ssim
from .utils import extract_colors
def euclidean_distance(image1, image2):
"""Calculate `euclidean distance <https://en.wikipedia.org/wiki/Euclidean_distance>`_ for each pixel in ``image1``
and ``image2``. Images must have same dimension.
:param image1: Numpy image array
:param image2: Numpy image array
:return: Array of euclidean distances
"""
r1, g1, b1, a1 = extract_colors(image1)
r2, g2, b2, a2 = extract_colors(image2)
return np.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2 + (a1 - a2) ** 2) / 2
def chebyshev_distance(image1, image2):
"""Calculate `chebyshev distance <https://en.wikipedia.org/wiki/Chebyshev_distance>`_ for each pixel in ``image1``
and ``image2``. Images must have same dimension.
:param image1: Numpy image array
:param image2: Numpy image array
:return: Array of chebyshev distances
"""
r1, g1, b1, a1 = extract_colors(image1)
r2, g2, b2, a2 = extract_colors(image2)
return np.maximum(np.maximum(np.maximum(np.fabs(r1 - r2), np.fabs(g1 - g2)), np.fabs(b1 - b2)), np.fabs(a1 - a2))
def diff(image1, image2, compare_colors_method, tolerance=0, diff_color=(1., 0, 1., 1.)):
"""Create a diff image of ``image1`` and ``image2``. Pixels are considered different if the distance of colors is
greater than ``tolerance`` using given ``compare_colors_method``. The result image is created by blending ``image1``
and ``image2`` together and replacing different pixels with the ``diff_color``.
:param image1: Numpy image array
:param image2: Numpy image array
:param compare_colors_method: Method that takes two numpy image arrays and return array of color distances in range from 0.0 to 1.0. You can use ``euclidean_distance``, ``chebyshev_distance`` or implement your own method.
:param tolerance: Defines the color distance that is acceptable and colors are considered the same
:param diff_color: RGBA color that should be used for different pixels
:return:
Tuple containing:
- ``diff_image`` Numpy image array
- ``diff_pctg`` Percentage of pixels where the color distance exceeded the acceptable tolerance
"""
mask = compare_colors_method(image1, image2) > tolerance
diff_pctg = mask[mask].size / mask.size
diff_image = image1 * 0.5 + image2 * 0.5
diff_image[mask] = diff_color
return diff_image, diff_pctg
def calculate_mse(image1, image2):
"""Calculate `mean squared error <https://en.wikipedia.org/wiki/Mean_squared_error>`_ for given images. The higher
the value of MSE is, the more different the images are.
:param image1: Numpy image array
:param image2: Numpy image array
:return: Float number representing mean squared error
"""
return np.sum((image1 - image2) ** 2) / float(image1.shape[0] * image1.shape[1])
def calculate_ssim(image1, image2):
"""Calculate `structural similarity index <https://en.wikipedia.org/wiki/Structural_similarity>`_ for given images.
If the value is 1.0 the images are same. The lower the value is, the more different the images are.
:param image1: Numpy image array
:param image2: Numpy image array
:return: Float number from -1.0 to 1.0 representing SSIM
"""
return compute_ssim(
Image.fromarray((image1[:, :, :3] * 255).astype(np.uint8), mode='RGB'),
Image.fromarray((image2[:, :, :3] * 255).astype(np.uint8), mode='RGB')
)
| gpl-3.0 |
DirtyPiece/dancestudio | Build/Tools/Python27/Lib/site-packages/pip/_vendor/requests/packages/urllib3/filepost.py | 551 | 2512 | # urllib3/filepost.py
# Copyright 2008-2013 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
import codecs
import mimetypes
from uuid import uuid4
from io import BytesIO
from .packages import six
from .packages.six import b
from .fields import RequestField
writer = codecs.lookup('utf-8')[3]
def choose_boundary():
"""
Our embarassingly-simple replacement for mimetools.choose_boundary.
"""
return uuid4().hex
def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field)
def iter_fields(fields):
"""
.. deprecated:: 1.6
Iterate over fields.
The addition of :class:`~urllib3.fields.RequestField` makes this function
obsolete. Instead, use :func:`iter_field_objects`, which returns
:class:`~urllib3.fields.RequestField` objects.
Supports list of (k, v) tuples and dicts.
"""
if isinstance(fields, dict):
return ((k, v) for k, v in six.iteritems(fields))
return ((k, v) for k, v in fields)
def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`.
"""
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for field in iter_field_objects(fields):
body.write(b('--%s\r\n' % (boundary)))
writer(body).write(field.render_headers())
data = field.data
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b'\r\n')
body.write(b('--%s--\r\n' % (boundary)))
content_type = str('multipart/form-data; boundary=%s' % boundary)
return body.getvalue(), content_type
| mit |
beeftornado/sentry | tests/acceptance/test_organization_events_v2.py | 1 | 24045 | from __future__ import absolute_import
import copy
import six
import pytest
import pytz
from sentry.utils.compat.mock import patch
from datetime import timedelta
from six.moves.urllib.parse import urlencode
from selenium.webdriver.common.keys import Keys
from sentry.discover.models import DiscoverSavedQuery
from sentry.testutils import AcceptanceTestCase, SnubaTestCase
from sentry.utils.samples import load_data
from sentry.testutils.helpers.datetime import iso_format, before_now, timestamp_format
FEATURE_NAMES = [
"organizations:discover-basic",
"organizations:discover-query",
"organizations:performance-view",
]
def all_events_query(**kwargs):
options = {
"sort": ["-timestamp"],
"field": ["title", "event.type", "project", "user.display", "timestamp"],
"name": ["All Events"],
}
options.update(kwargs)
return urlencode(options, doseq=True)
def errors_query(**kwargs):
options = {
"sort": ["-title"],
"name": ["Errors"],
"field": ["title", "count(id)", "count_unique(user)", "project"],
"query": ["event.type:error"],
}
options.update(kwargs)
return urlencode(options, doseq=True)
def transactions_query(**kwargs):
options = {
"sort": ["-count"],
"name": ["Transactions"],
"field": ["transaction", "project", "count()"],
"statsPeriod": ["14d"],
"query": ["event.type:transaction"],
}
options.update(kwargs)
return urlencode(options, doseq=True)
def generate_transaction(trace=None, span=None):
start_datetime = before_now(minutes=1, milliseconds=500)
end_datetime = before_now(minutes=1)
event_data = load_data(
"transaction",
timestamp=end_datetime,
start_timestamp=start_datetime,
trace=trace,
span=span,
)
event_data.update({"event_id": "a" * 32})
# generate and build up span tree
reference_span = event_data["spans"][0]
parent_span_id = reference_span["parent_span_id"]
span_tree_blueprint = {
"a": {},
"b": {"bb": {"bbb": {"bbbb": "bbbbb"}}},
"c": {},
"d": {},
"e": {},
}
time_offsets = {
"a": (timedelta(), timedelta(milliseconds=10)),
"b": (timedelta(milliseconds=120), timedelta(milliseconds=250)),
"bb": (timedelta(milliseconds=130), timedelta(milliseconds=10)),
"bbb": (timedelta(milliseconds=140), timedelta(milliseconds=10)),
"bbbb": (timedelta(milliseconds=150), timedelta(milliseconds=10)),
"bbbbb": (timedelta(milliseconds=160), timedelta(milliseconds=90)),
"c": (timedelta(milliseconds=260), timedelta(milliseconds=100)),
"d": (timedelta(milliseconds=375), timedelta(milliseconds=50)),
"e": (timedelta(milliseconds=400), timedelta(milliseconds=100)),
}
def build_span_tree(span_tree, spans, parent_span_id):
for span_id, child in sorted(span_tree.items(), key=lambda item: item[0]):
span = copy.deepcopy(reference_span)
# non-leaf node span
span["parent_span_id"] = parent_span_id.ljust(16, "0")
span["span_id"] = span_id.ljust(16, "0")
(start_delta, span_length) = time_offsets.get(span_id, (timedelta(), timedelta()))
span_start_time = start_datetime + start_delta
span["start_timestamp"] = timestamp_format(span_start_time)
span["timestamp"] = timestamp_format(span_start_time + span_length)
spans.append(span)
if isinstance(child, dict):
spans = build_span_tree(child, spans, span_id)
elif isinstance(child, six.string_types):
parent_span_id = span_id
span_id = child
span = copy.deepcopy(reference_span)
# leaf node span
span["parent_span_id"] = parent_span_id.ljust(16, "0")
span["span_id"] = span_id.ljust(16, "0")
(start_delta, span_length) = time_offsets.get(span_id, (timedelta(), timedelta()))
span_start_time = start_datetime + start_delta
span["start_timestamp"] = timestamp_format(span_start_time)
span["timestamp"] = timestamp_format(span_start_time + span_length)
spans.append(span)
return spans
event_data["spans"] = build_span_tree(span_tree_blueprint, [], parent_span_id)
return event_data
class OrganizationEventsV2Test(AcceptanceTestCase, SnubaTestCase):
def setUp(self):
super(OrganizationEventsV2Test, self).setUp()
self.user = self.create_user("foo@example.com", is_superuser=True)
self.org = self.create_organization(name="Rowdy Tiger")
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
self.create_member(user=self.user, organization=self.org, role="owner", teams=[self.team])
self.login_as(self.user)
self.landing_path = u"/organizations/{}/discover/queries/".format(self.org.slug)
self.result_path = u"/organizations/{}/discover/results/".format(self.org.slug)
def wait_until_loaded(self):
self.browser.wait_until_not(".loading-indicator")
self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
def test_events_default_landing(self):
with self.feature(FEATURE_NAMES):
self.browser.get(self.landing_path)
self.wait_until_loaded()
self.browser.snapshot("events-v2 - default landing")
def test_all_events_query_empty_state(self):
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + all_events_query())
self.wait_until_loaded()
self.browser.snapshot("events-v2 - all events query - empty state")
with self.feature(FEATURE_NAMES):
# expect table to expand to the right when no tags are provided
self.browser.get(self.result_path + "?" + all_events_query(tag=[]))
self.wait_until_loaded()
self.browser.snapshot("events-v2 - all events query - empty state - no tags")
@patch("django.utils.timezone.now")
def test_all_events_query(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
min_ago = iso_format(before_now(minutes=1))
two_min_ago = iso_format(before_now(minutes=2))
self.store_event(
data={
"event_id": "a" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
},
project_id=self.project.id,
assert_no_errors=False,
)
self.store_event(
data={
"event_id": "b" * 32,
"message": "this is bad.",
"timestamp": two_min_ago,
"fingerprint": ["group-2"],
"user": {
"id": "123",
"email": "someone@example.com",
"username": "haveibeenpwned",
"ip_address": "8.8.8.8",
"name": "Someone",
},
},
project_id=self.project.id,
assert_no_errors=False,
)
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + all_events_query())
self.wait_until_loaded()
# This test is flakey in that we sometimes load this page before the event is processed
# depend on pytest-retry to reload the page
self.browser.wait_until_not(
'[data-test-id="grid-editable"] [data-test-id="empty-state"]', timeout=2
)
self.browser.snapshot("events-v2 - all events query - list")
with self.feature(FEATURE_NAMES):
# expect table to expand to the right when no tags are provided
self.browser.get(self.result_path + "?" + all_events_query(tag=[]))
self.wait_until_loaded()
self.browser.snapshot("events-v2 - all events query - list - no tags")
def test_errors_query_empty_state(self):
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + errors_query())
self.wait_until_loaded()
self.browser.snapshot("events-v2 - errors query - empty state")
self.browser.click_when_visible('[data-test-id="grid-edit-enable"]')
self.browser.snapshot(
"events-v2 - errors query - empty state - querybuilder - column edit state"
)
@patch("django.utils.timezone.now")
def test_errors_query(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
min_ago = iso_format(before_now(minutes=1))
self.store_event(
data={
"event_id": "a" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
"type": "error",
},
project_id=self.project.id,
assert_no_errors=False,
)
self.store_event(
data={
"event_id": "b" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
"type": "error",
},
project_id=self.project.id,
assert_no_errors=False,
)
self.store_event(
data={
"event_id": "c" * 32,
"message": "this is bad.",
"timestamp": min_ago,
"fingerprint": ["group-2"],
"type": "error",
},
project_id=self.project.id,
assert_no_errors=False,
)
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + errors_query())
self.wait_until_loaded()
self.browser.snapshot("events-v2 - errors")
def test_transactions_query_empty_state(self):
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + transactions_query())
self.wait_until_loaded()
self.browser.snapshot("events-v2 - transactions query - empty state")
with self.feature(FEATURE_NAMES):
# expect table to expand to the right when no tags are provided
self.browser.get(self.result_path + "?" + transactions_query(tag=[]))
self.wait_until_loaded()
self.browser.snapshot("events-v2 - transactions query - empty state - no tags")
@patch("django.utils.timezone.now")
def test_transactions_query(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
event_data = generate_transaction()
self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
with self.feature(FEATURE_NAMES):
self.browser.get(self.result_path + "?" + transactions_query())
self.wait_until_loaded()
self.browser.wait_until_not(
'[data-test-id="grid-editable"] [data-test-id="empty-state"]', timeout=2
)
self.browser.snapshot("events-v2 - transactions query - list")
@patch("django.utils.timezone.now")
def test_event_detail_view_from_all_events(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
min_ago = iso_format(before_now(minutes=1))
event_data = load_data("python")
event_data.update(
{
"event_id": "a" * 32,
"timestamp": min_ago,
"received": min_ago,
"fingerprint": ["group-1"],
}
)
self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=False)
with self.feature(FEATURE_NAMES):
# Get the list page.
self.browser.get(self.result_path + "?" + all_events_query())
self.wait_until_loaded()
# View Event
self.browser.elements('[data-test-id="view-event"]')[0].click()
self.wait_until_loaded()
header = self.browser.element('[data-test-id="event-header"] span')
assert event_data["message"] in header.text
self.browser.snapshot("events-v2 - single error details view")
@patch("django.utils.timezone.now")
def test_event_detail_view_from_errors_view(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
event_data = load_data("javascript")
event_data.update(
{
"timestamp": iso_format(before_now(minutes=5)),
"event_id": "d" * 32,
"fingerprint": ["group-1"],
}
)
self.store_event(data=event_data, project_id=self.project.id)
with self.feature(FEATURE_NAMES):
# Get the list page
self.browser.get(self.result_path + "?" + errors_query() + "&statsPeriod=24h")
self.wait_until_loaded()
# Open the stack
self.browser.element('[data-test-id="open-stack"]').click()
self.wait_until_loaded()
# View Event
self.browser.elements('[data-test-id="view-event"]')[0].click()
self.wait_until_loaded()
self.browser.snapshot("events-v2 - error event detail view")
@patch("django.utils.timezone.now")
def test_event_detail_view_from_transactions_query(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
event_data = generate_transaction(trace="a" * 32, span="ab" * 8)
self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
# Create a child event that is linked to the parent so we have coverage
# of traversal buttons.
child_event = generate_transaction(
trace=event_data["contexts"]["trace"]["trace_id"], span="bc" * 8
)
child_event["event_id"] = "b" * 32
child_event["contexts"]["trace"]["parent_span_id"] = event_data["spans"][4]["span_id"]
child_event["transaction"] = "z-child-transaction"
child_event["spans"] = child_event["spans"][0:3]
self.store_event(data=child_event, project_id=self.project.id, assert_no_errors=True)
with self.feature(FEATURE_NAMES):
# Get the list page
self.browser.get(self.result_path + "?" + transactions_query())
self.wait_until_loaded()
# Open the stack
self.browser.elements('[data-test-id="open-stack"]')[0].click()
self.wait_until_loaded()
# View Event
self.browser.elements('[data-test-id="view-event"]')[0].click()
self.wait_until_loaded()
# Open a span detail so we can check the search by trace link.
# Click on the 6th one as a missing instrumentation span is inserted.
self.browser.elements('[data-test-id="span-row"]')[6].click()
# Wait until the child event loads.
child_button = '[data-test-id="view-child-transaction"]'
self.browser.wait_until(child_button)
self.browser.snapshot("events-v2 - transactions event detail view")
# Click on the child transaction.
self.browser.click(child_button)
self.wait_until_loaded()
@patch("django.utils.timezone.now")
def test_transaction_event_detail_view_ops_filtering(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
event_data = generate_transaction(trace="a" * 32, span="ab" * 8)
self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
with self.feature(FEATURE_NAMES):
# Get the list page
self.browser.get(self.result_path + "?" + transactions_query())
self.wait_until_loaded()
# Open the stack
self.browser.elements('[data-test-id="open-stack"]')[0].click()
self.wait_until_loaded()
# View Event
self.browser.elements('[data-test-id="view-event"]')[0].click()
self.wait_until_loaded()
# Interact with ops filter dropdown
self.browser.elements('[data-test-id="filter-button"]')[0].click()
# select all ops
self.browser.elements(
'[data-test-id="op-filter-dropdown"] [data-test-id="checkbox-fancy"]'
)[0].click()
# un-select django.middleware
self.browser.elements(
'[data-test-id="op-filter-dropdown"] [data-test-id="checkbox-fancy"]'
)[1].click()
self.browser.snapshot("events-v2 - transactions event detail view - ops filtering")
def test_create_saved_query(self):
# Simulate a custom query
query = {"field": ["project.id", "count()"], "query": "event.type:error"}
query_name = "A new custom query"
with self.feature(FEATURE_NAMES):
# Go directly to the query builder view
self.browser.get(self.result_path + "?" + urlencode(query, doseq=True))
self.wait_until_loaded()
# Open the save as drawer
self.browser.element('[data-test-id="button-save-as"]').click()
# Fill out name and submit form.
self.browser.element('input[name="query_name"]').send_keys(query_name)
self.browser.element('[data-test-id="button-save-query"]').click()
self.browser.wait_until(
'div[name="discover2-query-name"][value="{}"]'.format(query_name)
)
# Page title should update.
title_input = self.browser.element('div[name="discover2-query-name"]')
assert title_input.get_attribute("value") == query_name
# Saved query should exist.
assert DiscoverSavedQuery.objects.filter(name=query_name).exists()
def test_view_and_rename_saved_query(self):
# Create saved query to rename
query = DiscoverSavedQuery.objects.create(
name="Custom query",
organization=self.org,
version=2,
query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
)
with self.feature(FEATURE_NAMES):
# View the query list
self.browser.get(self.landing_path)
self.wait_until_loaded()
# Look at the results for our query.
self.browser.element('[data-test-id="card-{}"]'.format(query.name)).click()
self.wait_until_loaded()
input = self.browser.element('div[name="discover2-query-name"]')
input.click()
input.send_keys(Keys.END + "updated!")
# Move focus somewhere else to trigger a blur and update the query
self.browser.element("table").click()
new_name = "Custom queryupdated!"
new_card_selector = 'div[name="discover2-query-name"][value="{}"]'.format(new_name)
self.browser.wait_until(new_card_selector)
# Assert the name was updated.
assert DiscoverSavedQuery.objects.filter(name=new_name).exists()
def test_delete_saved_query(self):
# Create saved query with ORM
query = DiscoverSavedQuery.objects.create(
name="Custom query",
organization=self.org,
version=2,
query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
)
with self.feature(FEATURE_NAMES):
# View the query list
self.browser.get(self.landing_path)
self.wait_until_loaded()
# Get the card with the new query
card_selector = '[data-test-id="card-{}"]'.format(query.name)
card = self.browser.element(card_selector)
# Open the context menu
card.find_element_by_css_selector('[data-test-id="context-menu"]').click()
# Delete the query
card.find_element_by_css_selector('[data-test-id="delete-query"]').click()
# Wait for card to clear
self.browser.wait_until_not(card_selector)
assert DiscoverSavedQuery.objects.filter(name=query.name).exists() is False
def test_duplicate_query(self):
# Create saved query with ORM
query = DiscoverSavedQuery.objects.create(
name="Custom query",
organization=self.org,
version=2,
query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
)
with self.feature(FEATURE_NAMES):
# View the query list
self.browser.get(self.landing_path)
self.wait_until_loaded()
# Get the card with the new query
card_selector = '[data-test-id="card-{}"]'.format(query.name)
card = self.browser.element(card_selector)
# Open the context menu, and duplicate
card.find_element_by_css_selector('[data-test-id="context-menu"]').click()
card.find_element_by_css_selector('[data-test-id="duplicate-query"]').click()
duplicate_name = "{} copy".format(query.name)
# Wait for new element to show up.
self.browser.element('[data-test-id="card-{}"]'.format(duplicate_name))
# Assert the new query exists and has 'copy' added to the name.
assert DiscoverSavedQuery.objects.filter(name=duplicate_name).exists()
@pytest.mark.skip(reason="causing timeouts in github actions and travis")
@patch("django.utils.timezone.now")
def test_drilldown_result(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
min_ago = iso_format(before_now(minutes=1))
events = (
("a" * 32, "oh no", "group-1"),
("b" * 32, "oh no", "group-1"),
("c" * 32, "this is bad", "group-2"),
)
for event in events:
self.store_event(
data={
"event_id": event[0],
"message": event[1],
"timestamp": min_ago,
"fingerprint": [event[2]],
"type": "error",
},
project_id=self.project.id,
)
query = {"field": ["message", "project", "count()"], "query": "event.type:error"}
with self.feature(FEATURE_NAMES):
# Go directly to the query builder view
self.browser.get(self.result_path + "?" + urlencode(query, doseq=True))
self.wait_until_loaded()
# Click the first drilldown
self.browser.element('[data-test-id="expand-count"]').click()
self.wait_until_loaded()
assert self.browser.element_exists_by_test_id("grid-editable"), "table should exist."
headers = self.browser.elements('[data-test-id="grid-editable"] thead th')
expected = ["", "MESSAGE", "PROJECT", "ID"]
actual = [header.text for header in headers]
assert expected == actual
@pytest.mark.skip(reason="not done")
@patch("django.utils.timezone.now")
def test_usage(self, mock_now):
mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
# TODO: load events
# go to landing
# go to a precanned query
# save query 1
# add environment column
# update query
# add condition from facet map
# delete a column
# click and drag a column
# save as query 2
# load save query 1
# sort column
# update query
# delete save query 1
| bsd-3-clause |
kehao95/Wechat_LearnHelper | src/env/lib/python3.5/site-packages/werkzeug/filesystem.py | 162 | 2174 | # -*- coding: utf-8 -*-
"""
werkzeug.filesystem
~~~~~~~~~~~~~~~~~~~
Various utilities for the local filesystem.
:copyright: (c) 2015 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import codecs
import sys
import warnings
# We do not trust traditional unixes.
has_likely_buggy_unicode_filesystem = \
sys.platform.startswith('linux') or 'bsd' in sys.platform
def _is_ascii_encoding(encoding):
"""
Given an encoding this figures out if the encoding is actually ASCII (which
is something we don't actually want in most cases). This is necessary
because ASCII comes under many names such as ANSI_X3.4-1968.
"""
if encoding is None:
return False
try:
return codecs.lookup(encoding).name == 'ascii'
except LookupError:
return False
class BrokenFilesystemWarning(RuntimeWarning, UnicodeWarning):
'''The warning used by Werkzeug to signal a broken filesystem. Will only be
used once per runtime.'''
_warned_about_filesystem_encoding = False
def get_filesystem_encoding():
"""
Returns the filesystem encoding that should be used. Note that this is
different from the Python understanding of the filesystem encoding which
might be deeply flawed. Do not use this value against Python's unicode APIs
because it might be different. See :ref:`filesystem-encoding` for the exact
behavior.
The concept of a filesystem encoding in generally is not something you
should rely on. As such if you ever need to use this function except for
writing wrapper code reconsider.
"""
global _warned_about_filesystem_encoding
rv = sys.getfilesystemencoding()
if has_likely_buggy_unicode_filesystem and not rv \
or _is_ascii_encoding(rv):
if not _warned_about_filesystem_encoding:
warnings.warn(
'Detected a misconfigured UNIX filesystem: Will use UTF-8 as '
'filesystem encoding instead of {!r}'.format(rv),
BrokenFilesystemWarning)
_warned_about_filesystem_encoding = True
return 'utf-8'
return rv
| gpl-3.0 |
jayhetee/coveragepy | coverage/plugin_support.py | 18 | 7841 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
"""Support for plugins."""
import os.path
import sys
from coverage.misc import CoverageException
from coverage.plugin import CoveragePlugin, FileTracer, FileReporter
class Plugins(object):
"""The currently loaded collection of coverage.py plugins."""
def __init__(self):
self.order = []
self.names = {}
self.file_tracers = []
self.current_module = None
self.debug = None
@classmethod
def load_plugins(cls, modules, config, debug=None):
"""Load plugins from `modules`.
Returns a list of loaded and configured plugins.
"""
plugins = cls()
plugins.debug = debug
for module in modules:
plugins.current_module = module
__import__(module)
mod = sys.modules[module]
coverage_init = getattr(mod, "coverage_init", None)
if not coverage_init:
raise CoverageException(
"Plugin module %r didn't define a coverage_init function" % module
)
options = config.get_plugin_options(module)
coverage_init(plugins, options)
plugins.current_module = None
return plugins
def add_file_tracer(self, plugin):
"""Add a file tracer plugin.
`plugin` is an instance of a third-party plugin class. It must
implement the :meth:`CoveragePlugin.file_tracer` method.
"""
self._add_plugin(plugin, self.file_tracers)
def add_noop(self, plugin):
"""Add a plugin that does nothing.
This is only useful for testing the plugin support.
"""
self._add_plugin(plugin, None)
def _add_plugin(self, plugin, specialized):
"""Add a plugin object.
`plugin` is a :class:`CoveragePlugin` instance to add. `specialized`
is a list to append the plugin to.
"""
plugin_name = "%s.%s" % (self.current_module, plugin.__class__.__name__)
if self.debug and self.debug.should('plugin'):
self.debug.write("Loaded plugin %r: %r" % (self.current_module, plugin))
labelled = LabelledDebug("plugin %r" % (self.current_module,), self.debug)
plugin = DebugPluginWrapper(plugin, labelled)
# pylint: disable=attribute-defined-outside-init
plugin._coverage_plugin_name = plugin_name
plugin._coverage_enabled = True
self.order.append(plugin)
self.names[plugin_name] = plugin
if specialized is not None:
specialized.append(plugin)
def __nonzero__(self):
return bool(self.order)
__bool__ = __nonzero__
def __iter__(self):
return iter(self.order)
def get(self, plugin_name):
"""Return a plugin by name."""
return self.names[plugin_name]
class LabelledDebug(object):
"""A Debug writer, but with labels for prepending to the messages."""
def __init__(self, label, debug, prev_labels=()):
self.labels = list(prev_labels) + [label]
self.debug = debug
def add_label(self, label):
"""Add a label to the writer, and return a new `LabelledDebug`."""
return LabelledDebug(label, self.debug, self.labels)
def message_prefix(self):
"""The prefix to use on messages, combining the labels."""
prefixes = self.labels + ['']
return ":\n".join(" "*i+label for i, label in enumerate(prefixes))
def write(self, message):
"""Write `message`, but with the labels prepended."""
self.debug.write("%s%s" % (self.message_prefix(), message))
class DebugPluginWrapper(CoveragePlugin):
"""Wrap a plugin, and use debug to report on what it's doing."""
def __init__(self, plugin, debug):
super(DebugPluginWrapper, self).__init__()
self.plugin = plugin
self.debug = debug
def file_tracer(self, filename):
tracer = self.plugin.file_tracer(filename)
self.debug.write("file_tracer(%r) --> %r" % (filename, tracer))
if tracer:
debug = self.debug.add_label("file %r" % (filename,))
tracer = DebugFileTracerWrapper(tracer, debug)
return tracer
def file_reporter(self, filename):
reporter = self.plugin.file_reporter(filename)
self.debug.write("file_reporter(%r) --> %r" % (filename, reporter))
if reporter:
debug = self.debug.add_label("file %r" % (filename,))
reporter = DebugFileReporterWrapper(filename, reporter, debug)
return reporter
def sys_info(self):
return self.plugin.sys_info()
class DebugFileTracerWrapper(FileTracer):
"""A debugging `FileTracer`."""
def __init__(self, tracer, debug):
self.tracer = tracer
self.debug = debug
def _show_frame(self, frame):
"""A short string identifying a frame, for debug messages."""
return "%s@%d" % (
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
)
def source_filename(self):
sfilename = self.tracer.source_filename()
self.debug.write("source_filename() --> %r" % (sfilename,))
return sfilename
def has_dynamic_source_filename(self):
has = self.tracer.has_dynamic_source_filename()
self.debug.write("has_dynamic_source_filename() --> %r" % (has,))
return has
def dynamic_source_filename(self, filename, frame):
dyn = self.tracer.dynamic_source_filename(filename, frame)
self.debug.write("dynamic_source_filename(%r, %s) --> %r" % (
filename, self._show_frame(frame), dyn,
))
return dyn
def line_number_range(self, frame):
pair = self.tracer.line_number_range(frame)
self.debug.write("line_number_range(%s) --> %r" % (self._show_frame(frame), pair))
return pair
class DebugFileReporterWrapper(FileReporter):
"""A debugging `FileReporter`."""
def __init__(self, filename, reporter, debug):
super(DebugFileReporterWrapper, self).__init__(filename)
self.reporter = reporter
self.debug = debug
def relative_filename(self):
ret = self.reporter.relative_filename()
self.debug.write("relative_filename() --> %r" % (ret,))
return ret
def lines(self):
ret = self.reporter.lines()
self.debug.write("lines() --> %r" % (ret,))
return ret
def excluded_lines(self):
ret = self.reporter.excluded_lines()
self.debug.write("excluded_lines() --> %r" % (ret,))
return ret
def translate_lines(self, lines):
ret = self.reporter.translate_lines(lines)
self.debug.write("translate_lines(%r) --> %r" % (lines, ret))
return ret
def translate_arcs(self, arcs):
ret = self.reporter.translate_arcs(arcs)
self.debug.write("translate_arcs(%r) --> %r" % (arcs, ret))
return ret
def no_branch_lines(self):
ret = self.reporter.no_branch_lines()
self.debug.write("no_branch_lines() --> %r" % (ret,))
return ret
def exit_counts(self):
ret = self.reporter.exit_counts()
self.debug.write("exit_counts() --> %r" % (ret,))
return ret
def arcs(self):
ret = self.reporter.arcs()
self.debug.write("arcs() --> %r" % (ret,))
return ret
def source(self):
ret = self.reporter.source()
self.debug.write("source() --> %d chars" % (len(ret),))
return ret
def source_token_lines(self):
ret = list(self.reporter.source_token_lines())
self.debug.write("source_token_lines() --> %d tokens" % (len(ret),))
return ret
| apache-2.0 |
wd5/jangr | django/utils/datetime_safe.py | 496 | 2685 | # Python's datetime strftime doesn't handle dates before 1900.
# These classes override date and datetime to support the formatting of a date
# through its full "proleptic Gregorian" date range.
#
# Based on code submitted to comp.lang.python by Andrew Dalke
#
# >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was a %A")
# '1850/08/02 was a Friday'
from datetime import date as real_date, datetime as real_datetime
import re
import time
class date(real_date):
def strftime(self, fmt):
return strftime(self, fmt)
class datetime(real_datetime):
def strftime(self, fmt):
return strftime(self, fmt)
def combine(self, date, time):
return datetime(date.year, date.month, date.day, time.hour, time.minute, time.microsecond, time.tzinfo)
def date(self):
return date(self.year, self.month, self.day)
def new_date(d):
"Generate a safe date from a datetime.date object."
return date(d.year, d.month, d.day)
def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw)
# This library does not support strftime's "%s" or "%y" format strings.
# Allowed if there's an even number of "%"s because they are escaped.
_illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
def _findall(text, substr):
# Also finds overlaps
sites = []
i = 0
while 1:
j = text.find(substr, i)
if j == -1:
break
sites.append(j)
i=j+1
return sites
def strftime(dt, fmt):
if dt.year >= 1900:
return super(type(dt), dt).strftime(fmt)
illegal_formatting = _illegal_formatting.search(fmt)
if illegal_formatting:
raise TypeError("strftime of dates before 1900 does not handle" + illegal_formatting.group(0))
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400)
year = year + off
# Move to around the year 2000
year = year + ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year+28,) + timetuple[1:])
sites2 = _findall(s2, str(year+28))
sites = []
for site in sites1:
if site in sites2:
sites.append(site)
s = s1
syear = "%04d" % (dt.year,)
for site in sites:
s = s[:site] + syear + s[site+4:]
return s
| bsd-3-clause |
Yndal/ArduPilot-SensorPlatform | ardupilot/Tools/autotest/ROS/runsim.py | 16 | 8448 | #!/usr/bin/env python
# run a ROS simulator as a child process
import sys, os, pexpect, socket
import math, time, select, struct, signal, errno
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'pysim'))
import util, atexit
from pymavlink import fgFDM
class control_state(object):
def __init__(self):
self.aileron = 0
self.elevator = 0
self.throttle = 0
self.rudder = 0
self.ground_height = 0
sitl_state = control_state()
def interpret_address(addrstr):
'''interpret a IP:port string'''
a = addrstr.split(':')
a[1] = int(a[1])
return tuple(a)
def process_sitl_input(buf):
'''process control changes from SITL sim'''
global ros_out
control = list(struct.unpack('<14H', buf))
pwm = control[:11]
(speed, direction, turbulance) = control[11:]
global wind
wind.speed = speed*0.01
wind.direction = direction*0.01
wind.turbulance = turbulance*0.01
aileron = (pwm[0]-1500)/500.0
elevator = (pwm[1]-1500)/500.0
throttle = (pwm[2]-1000)/1000.0
if opts.revthr:
throttle = 1.0 - throttle
rudder = (pwm[3]-1500)/500.0
if opts.elevon:
# fake an elevon plane
ch1 = aileron
ch2 = elevator
aileron = (ch2-ch1)/2.0
# the minus does away with the need for RC2_REV=-1
elevator = -(ch2+ch1)/2.0
if opts.vtail:
# fake an elevon plane
ch1 = elevator
ch2 = rudder
# this matches VTAIL_OUTPUT==2
elevator = (ch2-ch1)/2.0
rudder = (ch2+ch1)/2.0
if aileron != sitl_state.aileron:
fdm_ctrls.set('left_aileron', pwm[0])
sitl_state.aileron = aileron
if elevator != sitl_state.elevator:
fdm_ctrls.set('elevator', pwm[1])
sitl_state.elevator = elevator
if rudder != sitl_state.rudder:
fdm_ctrls.set('rudder', pwm[3])
sitl_state.rudder = rudder
if throttle != sitl_state.throttle:
fdm_ctrls.set('rpm', pwm[2])
sitl_state.throttle = throttle
try:
ros_out.send(fdm_ctrls.pack())
except socket.error as e:
if e.errno not in [ errno.ECONNREFUSED ]:
raise
def process_ros_input(buf,frame_count):
'''process FG FDM input from ROS Simulator'''
global fdm, fg_out, sim_out
FG_FDM_FPS = 30
fdm.parse(buf)
if (fg_out and ((frame_count % FG_FDM_FPS) == 0)) :
try:
agl = fdm.get('agl', units='meters')
fdm.set('altitude', agl+sitl_state.ground_height, units='meters')
fdm.set('rpm', sitl_state.throttle*1000)
fg_out.send(fdm.pack())
except socket.error as e:
if e.errno not in [ errno.ECONNREFUSED ]:
raise
simbuf = struct.pack('<17dI',
fdm.get('latitude', units='degrees'),
fdm.get('longitude', units='degrees'),
fdm.get('altitude', units='meters'),
fdm.get('psi', units='degrees'),
fdm.get('v_north', units='mps'),
fdm.get('v_east', units='mps'),
fdm.get('v_down', units='mps'),
fdm.get('A_X_pilot', units='mpss'),
fdm.get('A_Y_pilot', units='mpss'),
fdm.get('A_Z_pilot', units='mpss'),
fdm.get('phidot', units='dps'),
fdm.get('thetadot', units='dps'),
fdm.get('psidot', units='dps'),
fdm.get('phi', units='degrees'),
fdm.get('theta', units='degrees'),
fdm.get('psi', units='degrees'),
fdm.get('vcas', units='mps'),
0x4c56414f)
try:
sim_out.send(simbuf)
except socket.error as e:
if e.errno not in [ errno.ECONNREFUSED ]:
raise
##################
# main program
from optparse import OptionParser
parser = OptionParser("runsim.py [options]")
parser.add_option("--simin", help="SITL input (IP:port)", default="127.0.0.1:5502")
parser.add_option("--simout", help="SITL output (IP:port)", default="127.0.0.1:5501")
parser.add_option("--fgout", help="FG display output (IP:port)", default="127.0.0.1:5503")
parser.add_option("--home", type='string', help="home lat,lng,alt,hdg") # Not implemented yet
parser.add_option("--script", type='string', help='jsbsim model script', default='jsbsim/rascal_test.xml') # Not implemented yet
parser.add_option("--options", type='string', help='ROS startup options')
parser.add_option("--elevon", action='store_true', default=False, help='assume elevon input')
parser.add_option("--revthr", action='store_true', default=False, help='reverse throttle')
parser.add_option("--vtail", action='store_true', default=False, help='assume vtail input')
parser.add_option("--wind", dest="wind", help="Simulate wind (speed,direction,turbulance)", default='0,0,0') # Not implemented yet
(opts, args) = parser.parse_args()
os.chdir(util.reltopdir('Tools/autotest'))
# kill off child when we exit
atexit.register(util.pexpect_close_all)
# start child
cmd = "roslaunch last_letter launcher.launch ArduPlane:=true"
if opts.options:
cmd += ' %s' % opts.options
ros = pexpect.spawn(cmd, logfile=sys.stdout, timeout=10)
ros.delaybeforesend = 0
util.pexpect_autoclose(ros)
ros_out_address = interpret_address("127.0.0.1:5505")
ros_in_address = interpret_address("127.0.0.1:5504")
# setup output to ROS
print("ROS listens for FG-FDM packets at %s" % str(ros_out_address))
ros_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ros_out.connect(ros_out_address)
# setup input from ROS
print("ROS sends FG-FDM packetes for the SITL at %s" % str(ros_in_address))
ros_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ros_in.bind(ros_in_address)
ros_in.setblocking(0)
# socket addresses
sim_out_address = interpret_address(opts.simout)
sim_in_address = interpret_address(opts.simin)
# setup input from SITL sim
sim_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sim_in.bind(sim_in_address)
sim_in.setblocking(0)
# setup output to SITL sim
sim_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sim_out.connect(interpret_address(opts.simout))
sim_out.setblocking(0)
# setup possible output to FlightGear for display
fg_out = None
if opts.fgout:
fg_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fg_out.connect(interpret_address(opts.fgout))
# setup wind generator
wind = util.Wind(opts.wind)
fdm = fgFDM.fgFDM()
fdm_ctrls = fgFDM.fgFDM() # Setup another fdm object to send ctrls to ROS
time.sleep(1.5)
print("Simulator ready to fly")
def main_loop():
'''run main loop'''
tnow = time.time()
last_report = tnow
last_sim_input = tnow
last_wind_update = tnow
frame_count = 0
paused = False
while True:
rin = [ros_in.fileno(), sim_in.fileno()]
try:
(rin, win, xin) = select.select(rin, [], [], 1.0)
except select.error:
util.check_parent()
continue
tnow = time.time()
if ros_in.fileno() in rin:
buf = ros_in.recv(fdm.packet_size())
process_ros_input(buf,frame_count)
frame_count += 1
if sim_in.fileno() in rin:
simbuf = sim_in.recv(28)
process_sitl_input(simbuf)
last_sim_input = tnow
if tnow - last_report > 3:
print("FPS %u asl=%.1f agl=%.1f roll=%.1f pitch=%.1f a=(%.2f %.2f %.2f)" % (
frame_count / (time.time() - last_report),
fdm.get('altitude', units='meters'),
fdm.get('agl', units='meters'),
fdm.get('phi', units='degrees'),
fdm.get('theta', units='degrees'),
fdm.get('A_X_pilot', units='mpss'),
fdm.get('A_Y_pilot', units='mpss'),
fdm.get('A_Z_pilot', units='mpss')))
frame_count = 0
last_report = time.time()
def exit_handler():
'''exit the sim'''
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
sys.exit(1)
signal.signal(signal.SIGINT, exit_handler)
signal.signal(signal.SIGTERM, exit_handler)
try:
main_loop()
except:
exit_handler()
raise
| mit |
livid/v2ex | v2ex/babel/da/__init__.py | 15 | 4403 | # coding=utf-8
# "da" means Data Access, this file contains various quick (or dirty) methods for accessing data.
import hashlib
import logging
import zlib
import pickle
from google.appengine.ext import db
from google.appengine.api import memcache
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Place
from v2ex.babel import Site
def GetKindByNum(kind, num):
K = str(kind.capitalize())
one = memcache.get(K + '_' + str(num))
if one:
return one
else:
q = db.GqlQuery("SELECT * FROM " + K + " WHERE num = :1", int(num))
if q.count() == 1:
one = q[0]
memcache.set(K + '_' + str(num), one, 86400)
return one
else:
return False
def GetKindByName(kind, name):
K = str(kind.capitalize())
one = memcache.get(K + '::' + str(name))
if one:
return one
else:
q = db.GqlQuery("SELECT * FROM " + K + " WHERE name = :1", str(name))
if q.count() == 1:
one = q[0]
memcache.set(K + '::' + str(name), one, 86400)
return one
else:
return False
def GetMemberByUsername(name):
one = memcache.get('Member::' + str(name).lower())
if one:
return one
else:
q = db.GqlQuery("SELECT * FROM Member WHERE username_lower = :1", str(name).lower())
if q.count() == 1:
one = q[0]
memcache.set('Member::' + str(name).lower(), one, 86400)
return one
else:
return False
def GetMemberByEmail(email):
cache = 'Member::email::' + hashlib.md5(email.lower()).hexdigest()
one = memcache.get(cache)
if one:
return one
else:
q = db.GqlQuery("SELECT * FROM Member WHERE email = :1", str(email).lower())
if q.count() == 1:
one = q[0]
memcache.set(cache, one, 86400)
return one
else:
return False
def ip2long(ip):
ip_array = ip.split('.')
ip_long = int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + int(ip_array[2]) * 256 + int(ip_array[3])
return ip_long
def GetPlaceByIP(ip):
cache = 'Place_' + ip
place = memcache.get(cache)
if place:
return place
else:
q = db.GqlQuery("SELECT * FROM Place WHERE ip = :1", ip)
if q.count() == 1:
place = q[0]
memcache.set(cache, place, 86400)
return place
else:
return False
def CreatePlaceByIP(ip):
place = Place()
q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'place.max')
if (q.count() == 1):
counter = q[0]
counter.value = counter.value + 1
else:
counter = Counter()
counter.name = 'place.max'
counter.value = 1
q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'place.total')
if (q2.count() == 1):
counter2 = q2[0]
counter2.value = counter2.value + 1
else:
counter2 = Counter()
counter2.name = 'place.total'
counter2.value = 1
place.num = ip2long(ip)
place.ip = ip
place.put()
counter.put()
counter2.put()
return place
def GetSite():
site = memcache.get('site')
if site is not None:
return site
else:
q = db.GqlQuery("SELECT * FROM Site WHERE num = 1")
if q.count() == 1:
site = q[0]
if site.l10n is None:
site.l10n = 'en'
if site.meta is None:
site.meta = ''
memcache.set('site', site, 86400)
return site
else:
site = Site()
site.num = 1
site.title = 'V2EX'
site.domain = 'v2ex.appspot.com'
site.slogan = 'way to explore'
site.l10n = 'en'
site.description = ''
site.meta = ''
site.put()
memcache.set('site', site, 86400)
return site
# input is a compressed string
# output is an object
def GetUnpacked(data):
decompressed = zlib.decompress(data)
return pickle.loads(decompressed)
# input is an object
# output is an compressed string
def GetPacked(data):
s = pickle.dumps(data)
return zlib.compress(s) | bsd-3-clause |
schreiberx/sweet | archive/benchmarks_plane/sl-rexi/run.py | 2 | 5235 | #! /usr/bin/python2
import subprocess
import sys
import os
import time
from subprocess import PIPE
import socket
default_params = ''
output_file_prefix = 'output'
if len(sys.argv) > 1:
output_file_prefix = sys.argv[1]
#
# http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python
#
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "w")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
#
# SCENARIO
#
# 0: radial dam break
# 1: gaussian
# 2: balanced steady state u
# 3: balanced steady state v
# 4: diamond initial condition
# 5: waves
#default_params = ' --initial-freq-x-mul=2 --initial-freq-y-mul=1 '
default_params = ' '
scenario_name = "Nonlinear-steady"
curdir_name = os.getcwd()
print ("Current working directory: "+curdir_name)
#os.chdir('../../../')
os.environ['OMP_PROC_BIND'] = "TRUE"
os.environ['OMP_NUM_THREADS'] = "4"
subprocess.call('scons --program=swe_rexi --plane-spectral-space=enable --mode=release --threading=off --gui=enable --parareal=none --rexi-parallel-sum=enable --plane-spectral-dealiasing=disable '.split(' '), shell=False)
#subprocess.call('scons --program=swe_rexi --rexi-parallel-sum=enable --plane-spectral-space=enable --plane-spectral-dealiasing=disable --mode=release '.split(' '), shell=False)
binary = './build/swe_rexi_spectral_libfft_gui_rexipar_gnu_release'
# './build/swe_rexi_spectral_libfft_rexipar_gnu_release'
if not os.path.isfile(binary):
print "Binary "+binary+" not found"
sys.exit(1)
#
# run for 1 seconds
#
#max_time = 1
#
# order of time step for RK
# Use order 4 to make time errors very small to make the spatial error dominate
#
timestep_order = 4
#
# default params
#
#default_params += ' -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 '
default_params += '-g 1 -f 1 -X 1 -Y 1 -H 10 --nonlinear 1 --compute-error 1 -G 0 -S 1 -v 2 -s 14 --timestepping-mode 1 --staggering 0'
#'-N 128 -C -0.0001 -t 0.001 '
# Use higher-order time stepping?
#default_params += ' -R '+str(timestep_order)
# Max time
T = 0.1
# time step size for coarse time steps
dt_list = [T/pow(2.0, i) for i in range(2, 20, +1)]
# epsilons
#eps_list = [1, 0.1, 0.01]
#eps_list = [0.01, 0.1, 1]
eps_list = [1]
# resolutions
#N_list = [16, 32, 64, 128, 256, 512]
#N_list = [16, 32, 64, 128, 256]
N_list = [ 256]
# h values for REXI
h_list = [0.2]
# M values for REXI
M_list = []
M = 4
while M < 2000:
M_list.append(M)
M *= 2;
# http://math.boisestate.edu/~wright/research/FlyerEtAl2012.pdf
#hyperviscosity = {}
#for n in N_list:
# hyperviscosity[n] = 4.*pow(float(n), float(-4))
# hyperviscosity[n] = 0
print "Time step size for coarse time step: "+str(dt_list)
print "Time step order: "+str(timestep_order)
print "Search range for h: "+str(h_list)
print "Search range for M: "+str(M_list)
#print "Used hyperviscosity: "+str(hyperviscosity)
def extract_errors(output):
match_list = [
'DIAGNOSTICS BENCHMARK DIFF H:',
'DIAGNOSTICS BENCHMARK DIFF U:',
'DIAGNOSTICS BENCHMARK DIFF V:'
]
vals = ["x" for i in range(3)]
ol = output.splitlines(True)
for o in ol:
o = o.replace('\n', '')
o = o.replace('\r', '')
for i in range(0, len(match_list)):
m = match_list[i]
if o[0:len(m)] == m:
vals[i] = o[len(m)+1:]
return vals
print
print "Running with time stepping mode 1:"
for h in h_list:
for n in N_list:
# redirect output
filename = curdir_name+'/'+output_file_prefix+"_n"+str(n)+".csv"
filename_dump = curdir_name+'/'+output_file_prefix+"_n"+str(n)+"dump.txt"
print "Writing output to "+filename
fd = open(filename, "w")
fd_dump = open(filename_dump, "w")
fd.write("#TI res="+str(n)+"x"+str(n)+", h="+str(h)+", Max time="+str(T)+" , "+scenario_name+" scenario\n")
fd.write("#TX REXI parameter M\n")
fd.write("#TY size of time step\n")
fd.write("# "+default_params+" \n")
fd.write("dT\M")
for M in M_list:
fd.write("\t"+str(M))
fd.write("\n")
fd.flush()
for dt in dt_list:
fd.write(str(dt))
fd.flush()
for M in M_list:
command = binary+' '+default_params
command += ' -C '+str(-dt)
command += ' -N '+str(n)
command += ' --rexi-m '+str(M)
command += ' -t '+str(T)
p = subprocess.Popen(command.split(' '), stdout=PIPE, stderr=PIPE, env=os.environ)
output, err = p.communicate()
fd_dump.write(output)
vals = extract_errors(output)
fd.write("\t"+str(vals[0]))
fd.flush()
print command
print vals
fd.write("\n")
print("FIN")
| mit |
costypetrisor/scikit-learn | sklearn/linear_model/tests/test_randomized_l1.py | 214 | 4690 | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# License: BSD 3 clause
import numpy as np
from scipy import sparse
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.linear_model.randomized_l1 import (lasso_stability_path,
RandomizedLasso,
RandomizedLogisticRegression)
from sklearn.datasets import load_diabetes, load_iris
from sklearn.feature_selection import f_regression, f_classif
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model.base import center_data
diabetes = load_diabetes()
X = diabetes.data
y = diabetes.target
X = StandardScaler().fit_transform(X)
X = X[:, [2, 3, 6, 7, 8]]
# test that the feature score of the best features
F, _ = f_regression(X, y)
def test_lasso_stability_path():
# Check lasso stability path
# Load diabetes data and add noisy features
scaling = 0.3
coef_grid, scores_path = lasso_stability_path(X, y, scaling=scaling,
random_state=42,
n_resampling=30)
assert_array_equal(np.argsort(F)[-3:],
np.argsort(np.sum(scores_path, axis=1))[-3:])
def test_randomized_lasso():
# Check randomized lasso
scaling = 0.3
selection_threshold = 0.5
# or with 1 alpha
clf = RandomizedLasso(verbose=False, alpha=1, random_state=42,
scaling=scaling,
selection_threshold=selection_threshold)
feature_scores = clf.fit(X, y).scores_
assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:])
# or with many alphas
clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42,
scaling=scaling,
selection_threshold=selection_threshold)
feature_scores = clf.fit(X, y).scores_
assert_equal(clf.all_scores_.shape, (X.shape[1], 2))
assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:])
X_r = clf.transform(X)
X_full = clf.inverse_transform(X_r)
assert_equal(X_r.shape[1], np.sum(feature_scores > selection_threshold))
assert_equal(X_full.shape, X.shape)
clf = RandomizedLasso(verbose=False, alpha='aic', random_state=42,
scaling=scaling)
feature_scores = clf.fit(X, y).scores_
assert_array_equal(feature_scores, X.shape[1] * [1.])
clf = RandomizedLasso(verbose=False, scaling=-0.1)
assert_raises(ValueError, clf.fit, X, y)
clf = RandomizedLasso(verbose=False, scaling=1.1)
assert_raises(ValueError, clf.fit, X, y)
def test_randomized_logistic():
# Check randomized sparse logistic regression
iris = load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
X = X[y != 2]
y = y[y != 2]
F, _ = f_classif(X, y)
scaling = 0.3
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
X_orig = X.copy()
feature_scores = clf.fit(X, y).scores_
assert_array_equal(X, X_orig) # fit does not modify X
assert_array_equal(np.argsort(F), np.argsort(feature_scores))
clf = RandomizedLogisticRegression(verbose=False, C=[1., 0.5],
random_state=42, scaling=scaling,
n_resampling=50, tol=1e-3)
feature_scores = clf.fit(X, y).scores_
assert_array_equal(np.argsort(F), np.argsort(feature_scores))
def test_randomized_logistic_sparse():
# Check randomized sparse logistic regression on sparse data
iris = load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
X = X[y != 2]
y = y[y != 2]
# center here because sparse matrices are usually not centered
X, y, _, _, _ = center_data(X, y, True, True)
X_sp = sparse.csr_matrix(X)
F, _ = f_classif(X, y)
scaling = 0.3
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
feature_scores = clf.fit(X, y).scores_
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
feature_scores_sp = clf.fit(X_sp, y).scores_
assert_array_equal(feature_scores, feature_scores_sp)
| bsd-3-clause |
cysuncn/python | spark/crm/PROC_O_CEN_CBOD_CICIFADR.py | 1 | 6303 | #coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_CEN_CBOD_CICIFADR').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
sc.setLogLevel('WARN')
if len(sys.argv) > 5:
if sys.argv[5] == "hive":
sqlContext = HiveContext(sc)
else:
sqlContext = SQLContext(sc)
hdfs = sys.argv[3]
dbname = sys.argv[4]
#处理需要使用的日期
etl_date = sys.argv[1]
#etl日期
V_DT = etl_date
#上一日日期
V_DT_LD = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8])) + timedelta(-1)).strftime("%Y%m%d")
#月初日期
V_DT_FMD = date(int(etl_date[0:4]), int(etl_date[4:6]), 1).strftime("%Y%m%d")
#上月末日期
V_DT_LMD = (date(int(etl_date[0:4]), int(etl_date[4:6]), 1) + timedelta(-1)).strftime("%Y%m%d")
#10位日期
V_DT10 = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8]))).strftime("%Y-%m-%d")
V_STEP = 0
#任务[12] 001-01::
V_STEP = V_STEP + 1
O_CI_CBOD_CICIFADR = sqlContext.read.parquet(hdfs+'/O_CI_CBOD_CICIFADR/*')
O_CI_CBOD_CICIFADR.registerTempTable("O_CI_CBOD_CICIFADR")
sql = """
SELECT ETLDT AS ETLDT
,FK_CICIF_KEY AS FK_CICIF_KEY
,CI_ADDR_COD AS CI_ADDR_COD
,CI_ADDR AS CI_ADDR
,CI_POSTCOD AS CI_POSTCOD
,CI_TEL_NO AS CI_TEL_NO
,CI_CNTY_COD AS CI_CNTY_COD
,CI_AREA_COD AS CI_AREA_COD
,CI_SUB_TEL AS CI_SUB_TEL
,CI_MOBILE_PHONE AS CI_MOBILE_PHONE
,CI_EMAIL AS CI_EMAIL
,CI_WEBSITE AS CI_WEBSITE
,CI_CNNT_DESC AS CI_CNNT_DESC
,CI_CRT_SYS AS CI_CRT_SYS
,CI_CRT_SCT_N AS CI_CRT_SCT_N
,CI_CRT_OPR AS CI_CRT_OPR
,CI_UPD_SYS AS CI_UPD_SYS
,CI_UPD_OPR AS CI_UPD_OPR
,CI_CRT_ORG AS CI_CRT_ORG
,CI_UPD_ORG AS CI_UPD_ORG
,CI_DB_PART_ID AS CI_DB_PART_ID
,CI_INSTN_COD AS CI_INSTN_COD
,FR_ID AS FR_ID
,V_DT AS ODS_ST_DATE
,'CEN' AS ODS_SYS_ID
FROM O_CI_CBOD_CICIFADR A --对私客户地址信息档
"""
sql = re.sub(r"\bV_DT\b", "'"+V_DT10+"'", sql)
F_CI_CBOD_CICIFADR_INNTMP1 = sqlContext.sql(sql)
F_CI_CBOD_CICIFADR_INNTMP1.registerTempTable("F_CI_CBOD_CICIFADR_INNTMP1")
F_CI_CBOD_CICIFADR = sqlContext.read.parquet(hdfs+'/F_CI_CBOD_CICIFADR/*')
F_CI_CBOD_CICIFADR.registerTempTable("F_CI_CBOD_CICIFADR")
sql = """
SELECT DST.ETLDT --平台日期:src.ETLDT
,DST.FK_CICIF_KEY --FK_CICIF_KEY:src.FK_CICIF_KEY
,DST.CI_ADDR_COD --地址编码:src.CI_ADDR_COD
,DST.CI_ADDR --地址:src.CI_ADDR
,DST.CI_POSTCOD --邮政编码:src.CI_POSTCOD
,DST.CI_TEL_NO --电话号码:src.CI_TEL_NO
,DST.CI_CNTY_COD --国家代码:src.CI_CNTY_COD
,DST.CI_AREA_COD --地区代码:src.CI_AREA_COD
,DST.CI_SUB_TEL --分机:src.CI_SUB_TEL
,DST.CI_MOBILE_PHONE --移动电话:src.CI_MOBILE_PHONE
,DST.CI_EMAIL --邮箱:src.CI_EMAIL
,DST.CI_WEBSITE --网址:src.CI_WEBSITE
,DST.CI_CNNT_DESC --联系描述:src.CI_CNNT_DESC
,DST.CI_CRT_SYS --创建系统:src.CI_CRT_SYS
,DST.CI_CRT_SCT_N --创建时间:src.CI_CRT_SCT_N
,DST.CI_CRT_OPR --创建人:src.CI_CRT_OPR
,DST.CI_UPD_SYS --更新系统:src.CI_UPD_SYS
,DST.CI_UPD_OPR --更新人:src.CI_UPD_OPR
,DST.CI_CRT_ORG --创建机构:src.CI_CRT_ORG
,DST.CI_UPD_ORG --更新机构:src.CI_UPD_ORG
,DST.CI_DB_PART_ID --分区键:src.CI_DB_PART_ID
,DST.CI_INSTN_COD --机构代号:src.CI_INSTN_COD
,DST.FR_ID --法人号:src.FR_ID
,DST.ODS_ST_DATE --系统日期:src.ODS_ST_DATE
,DST.ODS_SYS_ID --来源系统:src.ODS_SYS_ID
FROM F_CI_CBOD_CICIFADR DST
LEFT JOIN F_CI_CBOD_CICIFADR_INNTMP1 SRC
ON SRC.FK_CICIF_KEY = DST.FK_CICIF_KEY
AND SRC.CI_ADDR_COD = DST.CI_ADDR_COD
WHERE SRC.FK_CICIF_KEY IS NULL """
sql = re.sub(r"\bV_DT\b", "'"+V_DT10+"'", sql)
F_CI_CBOD_CICIFADR_INNTMP2 = sqlContext.sql(sql)
dfn="F_CI_CBOD_CICIFADR/"+V_DT+".parquet"
F_CI_CBOD_CICIFADR_INNTMP2=F_CI_CBOD_CICIFADR_INNTMP2.unionAll(F_CI_CBOD_CICIFADR_INNTMP1)
F_CI_CBOD_CICIFADR_INNTMP1.cache()
F_CI_CBOD_CICIFADR_INNTMP2.cache()
nrowsi = F_CI_CBOD_CICIFADR_INNTMP1.count()
nrowsa = F_CI_CBOD_CICIFADR_INNTMP2.count()
F_CI_CBOD_CICIFADR_INNTMP2.write.save(path = hdfs + '/' + dfn, mode='overwrite')
F_CI_CBOD_CICIFADR_INNTMP1.unpersist()
F_CI_CBOD_CICIFADR_INNTMP2.unpersist()
et = datetime.now()
print("Step %d start[%s] end[%s] use %d seconds, insert F_CI_CBOD_CICIFADR lines %d, all lines %d") % (V_STEP, st.strftime("%H:%M:%S"), et.strftime("%H:%M:%S"), (et-st).seconds, nrowsi, nrowsa)
ret = os.system("hdfs dfs -mv /"+dbname+"/F_CI_CBOD_CICIFADR/"+V_DT_LD+".parquet /"+dbname+"/F_CI_CBOD_CICIFADR_BK/")
ret = os.system("hdfs dfs -rm -r /"+dbname+"/F_CI_CBOD_CICIFADR/"+V_DT_LD+".parquet") | gpl-3.0 |
C4ptainCrunch/yapil | yapil/helpers.py | 1 | 1203 | import events
def eventize(line):
tokenized = tokenize(line)
event_type = events.BaseEvent
if tokenized['command'].decode().isnumeric():
event_type = events.NumericReply
elif tokenized['command'] == 'PING':
event_type = events.Ping
elif tokenized['command'] == 'PRIVMSG':
print tokenized
if not is_chan(tokenized['args'][0]):
print 'returning a privmsg'
event_type = events.Privmsg
else:
print 'Not handeld - chan message'
if not event_type == events.BaseEvent:
return event_type(tokenized)
def is_chan(name):
return name[0] in ('&', '#', '+', '!')
def tokenize(data):
'''Tokenize a line from the socket into : a prefix, a command and some args'''
prefix = ''
trailing = []
if not data:
return {'type' : 'empty'}
if data[0] == ':':
prefix, data = data[1:].split(' ', 1)
if data.find(' :') != -1:
data, trailing = data.split(' :', 1)
args = data.split()
args.append(trailing)
else:
args = data.split()
command = args.pop(0)
return {'prefix' : prefix,
'command' : command,
'args' : args} | agpl-3.0 |
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/src/twisted/conch/test/test_conch.py | 11 | 24651 | # -*- test-case-name: twisted.conch.test.test_conch -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import os, sys, socket
import subprocess
from itertools import count
from zope.interface import implementer
from twisted.conch.error import ConchError
from twisted.conch.avatar import ConchUser
from twisted.conch.ssh.session import ISession, SSHSession, wrapProtocol
from twisted.cred import portal
from twisted.internet import reactor, defer, protocol
from twisted.internet.error import ProcessExitedAlready
from twisted.internet.task import LoopingCall
from twisted.internet.utils import getProcessValue
from twisted.python import filepath, log, runtime
from twisted.python.compat import unicode
from twisted.trial import unittest
try:
from twisted.conch.scripts.conch import SSHSession as StdioInteractingSession
except ImportError as e:
StdioInteractingSession = None
_reason = str(e)
del e
from twisted.conch.test.test_ssh import ConchTestRealm
from twisted.python.procutils import which
from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
from twisted.conch.test.keydata import publicDSA_openssh, privateDSA_openssh
try:
from twisted.conch.test.test_ssh import ConchTestServerFactory, \
conchTestPublicKeyChecker
except ImportError:
pass
try:
import cryptography
except ImportError:
cryptography = None
try:
import pyasn1
except ImportError:
pyasn1 = None
class FakeStdio(object):
"""
A fake for testing L{twisted.conch.scripts.conch.SSHSession.eofReceived} and
L{twisted.conch.scripts.cftp.SSHSession.eofReceived}.
@ivar writeConnLost: A flag which records whether L{loserWriteConnection}
has been called.
"""
writeConnLost = False
def loseWriteConnection(self):
"""
Record the call to loseWriteConnection.
"""
self.writeConnLost = True
class StdioInteractingSessionTests(unittest.TestCase):
"""
Tests for L{twisted.conch.scripts.conch.SSHSession}.
"""
if StdioInteractingSession is None:
skip = _reason
def test_eofReceived(self):
"""
L{twisted.conch.scripts.conch.SSHSession.eofReceived} loses the
write half of its stdio connection.
"""
stdio = FakeStdio()
channel = StdioInteractingSession()
channel.stdio = stdio
channel.eofReceived()
self.assertTrue(stdio.writeConnLost)
class Echo(protocol.Protocol):
def connectionMade(self):
log.msg('ECHO CONNECTION MADE')
def connectionLost(self, reason):
log.msg('ECHO CONNECTION DONE')
def dataReceived(self, data):
self.transport.write(data)
if b'\n' in data:
self.transport.loseConnection()
class EchoFactory(protocol.Factory):
protocol = Echo
class ConchTestOpenSSHProcess(protocol.ProcessProtocol):
"""
Test protocol for launching an OpenSSH client process.
@ivar deferred: Set by whatever uses this object. Accessed using
L{_getDeferred}, which destroys the value so the Deferred is not
fired twice. Fires when the process is terminated.
"""
deferred = None
buf = b''
def _getDeferred(self):
d, self.deferred = self.deferred, None
return d
def outReceived(self, data):
self.buf += data
def processEnded(self, reason):
"""
Called when the process has ended.
@param reason: a Failure giving the reason for the process' end.
"""
if reason.value.exitCode != 0:
self._getDeferred().errback(
ConchError("exit code was not 0: {}".format(
reason.value.exitCode)))
else:
buf = self.buf.replace(b'\r\n', b'\n')
self._getDeferred().callback(buf)
class ConchTestForwardingProcess(protocol.ProcessProtocol):
"""
Manages a third-party process which launches a server.
Uses L{ConchTestForwardingPort} to connect to the third-party server.
Once L{ConchTestForwardingPort} has disconnected, kill the process and fire
a Deferred with the data received by the L{ConchTestForwardingPort}.
@ivar deferred: Set by whatever uses this object. Accessed using
L{_getDeferred}, which destroys the value so the Deferred is not
fired twice. Fires when the process is terminated.
"""
deferred = None
def __init__(self, port, data):
"""
@type port: L{int}
@param port: The port on which the third-party server is listening.
(it is assumed that the server is running on localhost).
@type data: L{str}
@param data: This is sent to the third-party server. Must end with '\n'
in order to trigger a disconnect.
"""
self.port = port
self.buffer = None
self.data = data
def _getDeferred(self):
d, self.deferred = self.deferred, None
return d
def connectionMade(self):
self._connect()
def _connect(self):
"""
Connect to the server, which is often a third-party process.
Tries to reconnect if it fails because we have no way of determining
exactly when the port becomes available for listening -- we can only
know when the process starts.
"""
cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self,
self.data)
d = cc.connectTCP('127.0.0.1', self.port)
d.addErrback(self._ebConnect)
return d
def _ebConnect(self, f):
reactor.callLater(.1, self._connect)
def forwardingPortDisconnected(self, buffer):
"""
The network connection has died; save the buffer of output
from the network and attempt to quit the process gracefully,
and then (after the reactor has spun) send it a KILL signal.
"""
self.buffer = buffer
self.transport.write(b'\x03')
self.transport.loseConnection()
reactor.callLater(0, self._reallyDie)
def _reallyDie(self):
try:
self.transport.signalProcess('KILL')
except ProcessExitedAlready:
pass
def processEnded(self, reason):
"""
Fire the Deferred at self.deferred with the data collected
from the L{ConchTestForwardingPort} connection, if any.
"""
self._getDeferred().callback(self.buffer)
class ConchTestForwardingPort(protocol.Protocol):
"""
Connects to server launched by a third-party process (managed by
L{ConchTestForwardingProcess}) sends data, then reports whatever it
received back to the L{ConchTestForwardingProcess} once the connection
is ended.
"""
def __init__(self, protocol, data):
"""
@type protocol: L{ConchTestForwardingProcess}
@param protocol: The L{ProcessProtocol} which made this connection.
@type data: str
@param data: The data to be sent to the third-party server.
"""
self.protocol = protocol
self.data = data
def connectionMade(self):
self.buffer = b''
self.transport.write(self.data)
def dataReceived(self, data):
self.buffer += data
def connectionLost(self, reason):
self.protocol.forwardingPortDisconnected(self.buffer)
def _makeArgs(args, mod="conch"):
start = [sys.executable, '-c'
"""
### Twisted Preamble
import sys, os
path = os.path.abspath(sys.argv[0])
while os.path.dirname(path) != path:
if os.path.basename(path).startswith('Twisted'):
sys.path.insert(0, path)
break
path = os.path.dirname(path)
from twisted.conch.scripts.%s import run
run()""" % mod]
madeArgs = []
for arg in start + list(args):
if isinstance(arg, unicode):
arg = arg.encode("utf-8")
madeArgs.append(arg)
return madeArgs
class ConchServerSetupMixin:
if not cryptography:
skip = "can't run without cryptography"
if not pyasn1:
skip = "Cannot run without PyASN1"
realmFactory = staticmethod(lambda: ConchTestRealm(b'testuser'))
def _createFiles(self):
for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub',
'kh_test']:
if os.path.exists(f):
os.remove(f)
with open('rsa_test','wb') as f:
f.write(privateRSA_openssh)
with open('rsa_test.pub','wb') as f:
f.write(publicRSA_openssh)
with open('dsa_test.pub','wb') as f:
f.write(publicDSA_openssh)
with open('dsa_test','wb') as f:
f.write(privateDSA_openssh)
os.chmod('dsa_test', 33152)
os.chmod('rsa_test', 33152)
with open('kh_test','wb') as f:
f.write(b'127.0.0.1 '+publicRSA_openssh)
def _getFreePort(self):
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
def _makeConchFactory(self):
"""
Make a L{ConchTestServerFactory}, which allows us to start a
L{ConchTestServer} -- i.e. an actually listening conch.
"""
realm = self.realmFactory()
p = portal.Portal(realm)
p.registerChecker(conchTestPublicKeyChecker())
factory = ConchTestServerFactory()
factory.portal = p
return factory
def setUp(self):
self._createFiles()
self.conchFactory = self._makeConchFactory()
self.conchFactory.expectedLoseConnection = 1
self.conchServer = reactor.listenTCP(0, self.conchFactory,
interface="127.0.0.1")
self.echoServer = reactor.listenTCP(0, EchoFactory())
self.echoPort = self.echoServer.getHost().port
self.echoServerV6 = reactor.listenTCP(0, EchoFactory(), interface="::1")
self.echoPortV6 = self.echoServerV6.getHost().port
def tearDown(self):
try:
self.conchFactory.proto.done = 1
except AttributeError:
pass
else:
self.conchFactory.proto.transport.loseConnection()
return defer.gatherResults([
defer.maybeDeferred(self.conchServer.stopListening),
defer.maybeDeferred(self.echoServer.stopListening),
defer.maybeDeferred(self.echoServerV6.stopListening)])
class ForwardingMixin(ConchServerSetupMixin):
"""
Template class for tests of the Conch server's ability to forward arbitrary
protocols over SSH.
These tests are integration tests, not unit tests. They launch a Conch
server, a custom TCP server (just an L{EchoProtocol}) and then call
L{execute}.
L{execute} is implemented by subclasses of L{ForwardingMixin}. It should
cause an SSH client to connect to the Conch server, asking it to forward
data to the custom TCP server.
"""
def test_exec(self):
"""
Test that we can use whatever client to send the command "echo goodbye"
to the Conch server. Make sure we receive "goodbye" back from the
server.
"""
d = self.execute('echo goodbye', ConchTestOpenSSHProcess())
return d.addCallback(self.assertEqual, b'goodbye\n')
def test_localToRemoteForwarding(self):
"""
Test that we can use whatever client to forward a local port to a
specified port on the server.
"""
localPort = self._getFreePort()
process = ConchTestForwardingProcess(localPort, b'test\n')
d = self.execute('', process,
sshArgs='-N -L%i:127.0.0.1:%i'
% (localPort, self.echoPort))
d.addCallback(self.assertEqual, b'test\n')
return d
def test_remoteToLocalForwarding(self):
"""
Test that we can use whatever client to forward a port from the server
to a port locally.
"""
localPort = self._getFreePort()
process = ConchTestForwardingProcess(localPort, b'test\n')
d = self.execute('', process,
sshArgs='-N -R %i:127.0.0.1:%i'
% (localPort, self.echoPort))
d.addCallback(self.assertEqual, b'test\n')
return d
# Conventionally there is a separate adapter object which provides ISession for
# the user, but making the user provide ISession directly works too. This isn't
# a full implementation of ISession though, just enough to make these tests
# pass.
@implementer(ISession)
class RekeyAvatar(ConchUser):
"""
This avatar implements a shell which sends 60 numbered lines to whatever
connects to it, then closes the session with a 0 exit status.
60 lines is selected as being enough to send more than 2kB of traffic, the
amount the client is configured to initiate a rekey after.
"""
def __init__(self):
ConchUser.__init__(self)
self.channelLookup[b'session'] = SSHSession
def openShell(self, transport):
"""
Write 60 lines of data to the transport, then exit.
"""
proto = protocol.Protocol()
proto.makeConnection(transport)
transport.makeConnection(wrapProtocol(proto))
# Send enough bytes to the connection so that a rekey is triggered in
# the client.
def write(counter):
i = next(counter)
if i == 60:
call.stop()
transport.session.conn.sendRequest(
transport.session, b'exit-status', b'\x00\x00\x00\x00')
transport.loseConnection()
else:
line = "line #%02d\n" % (i,)
line = line.encode("utf-8")
transport.write(line)
# The timing for this loop is an educated guess (and/or the result of
# experimentation) to exercise the case where a packet is generated
# mid-rekey. Since the other side of the connection is (so far) the
# OpenSSH command line client, there's no easy way to determine when the
# rekey has been initiated. If there were, then generating a packet
# immediately at that time would be a better way to test the
# functionality being tested here.
call = LoopingCall(write, count())
call.start(0.01)
def closed(self):
"""
Ignore the close of the session.
"""
class RekeyRealm:
"""
This realm gives out new L{RekeyAvatar} instances for any avatar request.
"""
def requestAvatar(self, avatarID, mind, *interfaces):
return interfaces[0], RekeyAvatar(), lambda: None
class RekeyTestsMixin(ConchServerSetupMixin):
"""
TestCase mixin which defines tests exercising L{SSHTransportBase}'s handling
of rekeying messages.
"""
realmFactory = RekeyRealm
def test_clientRekey(self):
"""
After a client-initiated rekey is completed, application data continues
to be passed over the SSH connection.
"""
process = ConchTestOpenSSHProcess()
d = self.execute("", process, '-o RekeyLimit=2K')
def finished(result):
expectedResult = '\n'.join(['line #%02d' % (i,) for i in range(60)]) + '\n'
expectedResult = expectedResult.encode("utf-8")
self.assertEqual(result, expectedResult)
d.addCallback(finished)
return d
class OpenSSHClientMixin:
if not which('ssh'):
skip = "no ssh command-line client available"
def execute(self, remoteCommand, process, sshArgs=''):
"""
Connects to the SSH server started in L{ConchServerSetupMixin.setUp} by
running the 'ssh' command line tool.
@type remoteCommand: str
@param remoteCommand: The command (with arguments) to run on the
remote end.
@type process: L{ConchTestOpenSSHProcess}
@type sshArgs: str
@param sshArgs: Arguments to pass to the 'ssh' process.
@return: L{defer.Deferred}
"""
# PubkeyAcceptedKeyTypes does not exist prior to OpenSSH 7.0 so we
# first need to check if we can set it. If we can, -V will just print
# the version without doing anything else; if we can't, we will get a
# configuration error.
d = getProcessValue(
which('ssh')[0], ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss', '-V'))
def hasPAKT(status):
if status == 0:
opts = '-oPubkeyAcceptedKeyTypes=ssh-dss '
else:
opts = ''
process.deferred = defer.Deferred()
# Pass -F /dev/null to avoid the user's configuration file from
# being loaded, as it may contain settings that cause our tests to
# fail or hang.
cmdline = ('ssh -2 -l testuser -p %i '
'-F /dev/null '
'-oUserKnownHostsFile=kh_test '
'-oPasswordAuthentication=no '
# Always use the RSA key, since that's the one in kh_test.
'-oHostKeyAlgorithms=ssh-rsa '
'-a '
'-i dsa_test ') + opts + sshArgs + \
' 127.0.0.1 ' + remoteCommand
port = self.conchServer.getHost().port
cmds = (cmdline % port).split()
encodedCmds = []
for cmd in cmds:
if isinstance(cmd, unicode):
cmd = cmd.encode("utf-8")
encodedCmds.append(cmd)
reactor.spawnProcess(process, which('ssh')[0], encodedCmds)
return process.deferred
return d.addCallback(hasPAKT)
class OpenSSHKeyExchangeTests(ConchServerSetupMixin, OpenSSHClientMixin,
unittest.TestCase):
"""
Tests L{SSHTransportBase}'s key exchange algorithm compatibility with
OpenSSH.
"""
def assertExecuteWithKexAlgorithm(self, keyExchangeAlgo):
"""
Call execute() method of L{OpenSSHClientMixin} with an ssh option that
forces the exclusive use of the key exchange algorithm specified by
keyExchangeAlgo
@type keyExchangeAlgo: L{str}
@param keyExchangeAlgo: The key exchange algorithm to use
@return: L{defer.Deferred}
"""
kexAlgorithms = []
try:
output = subprocess.check_output([which('ssh')[0], '-Q', 'kex'],
stderr=subprocess.STDOUT)
if not isinstance(output, str):
output = output.decode("utf-8")
kexAlgorithms = output.split()
except:
pass
if keyExchangeAlgo not in kexAlgorithms:
raise unittest.SkipTest(
"{} not supported by ssh client".format(
keyExchangeAlgo))
d = self.execute('echo hello', ConchTestOpenSSHProcess(),
'-oKexAlgorithms=' + keyExchangeAlgo)
return d.addCallback(self.assertEqual, b'hello\n')
def test_ECDHSHA256(self):
"""
The ecdh-sha2-nistp256 key exchange algorithm is compatible with
OpenSSH
"""
return self.assertExecuteWithKexAlgorithm(
'ecdh-sha2-nistp256')
def test_ECDHSHA384(self):
"""
The ecdh-sha2-nistp384 key exchange algorithm is compatible with
OpenSSH
"""
return self.assertExecuteWithKexAlgorithm(
'ecdh-sha2-nistp384')
def test_ECDHSHA521(self):
"""
The ecdh-sha2-nistp521 key exchange algorithm is compatible with
OpenSSH
"""
return self.assertExecuteWithKexAlgorithm(
'ecdh-sha2-nistp521')
def test_DH_GROUP1(self):
"""
The diffie-hellman-group1-sha1 key exchange algorithm is compatible
with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm(
'diffie-hellman-group1-sha1')
def test_DH_GROUP14(self):
"""
The diffie-hellman-group14-sha1 key exchange algorithm is compatible
with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm(
'diffie-hellman-group14-sha1')
def test_DH_GROUP_EXCHANGE_SHA1(self):
"""
The diffie-hellman-group-exchange-sha1 key exchange algorithm is
compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm(
'diffie-hellman-group-exchange-sha1')
def test_DH_GROUP_EXCHANGE_SHA256(self):
"""
The diffie-hellman-group-exchange-sha256 key exchange algorithm is
compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm(
'diffie-hellman-group-exchange-sha256')
def test_unsupported_algorithm(self):
"""
The list of key exchange algorithms supported
by OpenSSH client is obtained with C{ssh -Q kex}.
"""
self.assertRaises(unittest.SkipTest,
self.assertExecuteWithKexAlgorithm,
'unsupported-algorithm')
class OpenSSHClientForwardingTests(ForwardingMixin, OpenSSHClientMixin,
unittest.TestCase):
"""
Connection forwarding tests run against the OpenSSL command line client.
"""
def test_localToRemoteForwardingV6(self):
"""
Forwarding of arbitrary IPv6 TCP connections via SSH.
"""
localPort = self._getFreePort()
process = ConchTestForwardingProcess(localPort, b'test\n')
d = self.execute('', process,
sshArgs='-N -L%i:[::1]:%i'
% (localPort, self.echoPortV6))
d.addCallback(self.assertEqual, b'test\n')
return d
class OpenSSHClientRekeyTests(RekeyTestsMixin, OpenSSHClientMixin,
unittest.TestCase):
"""
Rekeying tests run against the OpenSSL command line client.
"""
class CmdLineClientTests(ForwardingMixin, unittest.TestCase):
"""
Connection forwarding tests run against the Conch command line client.
"""
if runtime.platformType == 'win32':
skip = "can't run cmdline client on win32"
def execute(self, remoteCommand, process, sshArgs='', conchArgs=None):
"""
As for L{OpenSSHClientTestCase.execute}, except it runs the 'conch'
command line tool, not 'ssh'.
"""
if conchArgs is None:
conchArgs = []
process.deferred = defer.Deferred()
port = self.conchServer.getHost().port
cmd = ('-p {} -l testuser '
'--known-hosts kh_test '
'--user-authentications publickey '
'-a '
'-i dsa_test '
'-v '.format(port) + sshArgs +
' 127.0.0.1 ' + remoteCommand)
cmds = _makeArgs(conchArgs + cmd.split())
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
encodedCmds = []
encodedEnv = {}
for cmd in cmds:
if isinstance(cmd, unicode):
cmd = cmd.encode("utf-8")
encodedCmds.append(cmd)
for var in env:
val = env[var]
if isinstance(var, unicode):
var = var.encode("utf-8")
if isinstance(val, unicode):
val = val.encode("utf-8")
encodedEnv[var] = val
reactor.spawnProcess(process, sys.executable, encodedCmds, env=encodedEnv)
return process.deferred
def test_runWithLogFile(self):
"""
It can store logs to a local file.
"""
def cb_check_log(result):
logContent = logPath.getContent()
self.assertIn(b'Log opened.', logContent)
logPath = filepath.FilePath(self.mktemp())
d = self.execute(
remoteCommand='echo goodbye',
process=ConchTestOpenSSHProcess(),
conchArgs=['--log', '--logfile', logPath.path,
'--host-key-algorithms', 'ssh-rsa']
)
d.addCallback(self.assertEqual, b'goodbye\n')
d.addCallback(cb_check_log)
return d
def test_runWithNoHostAlgorithmsSpecified(self):
"""
Do not use --host-key-algorithms flag on command line.
"""
d = self.execute(
remoteCommand='echo goodbye',
process=ConchTestOpenSSHProcess()
)
d.addCallback(self.assertEqual, b'goodbye\n')
return d
| mit |
anthonyfok/frescobaldi | frescobaldi_app/portmidi/ctypes_pypm.py | 2 | 5395 | # This module provides the same api via ctypes as John Harrison's pyrex-based
# PortMIDI binding.
# Don't use this module directly but via the toplevel API of this package.
# Copyright (c) 2011 - 2014 by Wilbert Berendsen, placed in the public domain.
import array
from ctypes import byref, create_string_buffer
from .pm_ctypes import (
libpm, libpt,
pmHostError, PmEvent,
PmTimeProcPtr, NullTimeProcPtr,
PortMidiStreamPtr,
)
from . import MidiException
__all__ = [
'TRUE',
'FALSE',
'Initialize',
'Terminate',
'CountDevices',
'GetDeviceInfo',
'GetDefaultInputDeviceID',
'GetDefaultOutputDeviceID',
'GetErrorText',
'Time',
'Input',
'Output',
]
FALSE = 0
TRUE = 1
def Initialize():
libpm.Pm_Initialize()
# equiv to TIME_START: start timer w/ ms accuracy
libpt.Pt_Start(1, NullTimeProcPtr, None)
def Terminate():
libpm.Pm_Terminate()
def GetDeviceInfo(device_id):
info_ptr = libpm.Pm_GetDeviceInfo(device_id)
if info_ptr:
info = info_ptr.contents
return (
info.interf,
info.name,
bool(info.input),
bool(info.output),
bool(info.opened),
)
CountDevices = libpm.Pm_CountDevices
GetDefaultInputDeviceID = libpm.Pm_GetDefaultInputDeviceID
GetDefaultOutputDeviceID = libpm.Pm_GetDefaultOutputDeviceID
GetErrorText = libpm.Pm_GetErrorText
Time = libpt.Pt_Time
class Output(object):
buffer_size = 1024
def __init__(self, device_id, latency=0):
self.device_id = device_id
self.latency = latency
self._midi_stream = PortMidiStreamPtr()
self._open = False
self._open_device()
def _open_device(self):
err = libpm.Pm_OpenOutput(byref(self._midi_stream), self.device_id,
None, 0, NullTimeProcPtr, None, self.latency)
_check_error(err)
self._open = True
def Close(self):
if self._open and GetDeviceInfo(self.device_id)[4]:
err = libpm.Pm_Abort(self._midi_stream)
_check_error(err)
err = libpm.Pm_Close(self._midi_stream)
_check_error(err)
self._open = False
__del__ = Close
def Write(self, data):
bufsize = self.buffer_size
if len(data) > bufsize:
raise ValueError("too much data for buffer")
BufferType = PmEvent * bufsize
buf = BufferType()
for i, event in enumerate(data):
msg, buf[i].timestamp = event
if len(msg) > 4 or len(msg) < 1:
raise ValueError("invalid message size")
message = 0
for j, byte in enumerate(msg):
message += ((byte & 0xFF) << (8*j))
buf[i].message = message
err = libpm.Pm_Write(self._midi_stream, buf, len(data))
_check_error(err)
def WriteShort(self, status, data1=0, data2=0):
buf = PmEvent()
buf.timestamp = libpt.Pt_Time()
buf.message = (((data2 << 16) & 0xFF0000) |
((data1 << 8) & 0xFF00) | (status & 0xFF))
err = libpm.Pm_Write(self._midi_stream, buf, 1)
_check_error(err)
def WriteSysEx(self, timestamp, msg):
"""msg may be a tuple or list of ints, or a bytes string."""
if isinstance(msg, (tuple, list)):
msg = array.array('B', msg).tostring()
cur_time = Time()
err = libpm.Pm_WriteSysEx(self._midi_stream, timestamp, msg)
_check_error(err)
while Time() == cur_time:
pass
class Input(object):
def __init__(self, device_id, bufsize=1024):
self.device_id = device_id
self.buffer_size = bufsize
self._midi_stream = PortMidiStreamPtr()
self._open = False
self._open_device()
def _open_device(self):
err = libpm.Pm_OpenInput(byref(self._midi_stream), self.device_id,
None, 100, NullTimeProcPtr, None)
_check_error(err)
self._open = True
def Close(self):
"""Closes a midi stream, flushing any pending buffers."""
if self._open and GetDeviceInfo(self.device_id)[4]:
err = libpm.Pm_Close(self._midi_stream)
_check_error(err)
self._open = False
__del__ = Close
def Poll(self):
return libpm.Pm_Poll(self._midi_stream)
def Read(self, length):
bufsize = self.buffer_size
BufferType = PmEvent * bufsize
buf = BufferType()
if not 1 <= length <= bufsize:
raise ValueError("invalid length")
num_events = libpm.Pm_Read(self._midi_stream, buf, length)
_check_error(num_events)
data = []
for i in range(num_events):
ev = buf[i]
msg = ev.message
msg = (msg & 255, (msg>>8) & 255, (msg>>16) & 255, (msg>>24) & 255)
data.append((msg, ev.timestamp))
return data
def _check_error(err_no):
if err_no < 0:
if err_no == pmHostError:
err_msg = create_string_buffer(b'\000' * 256)
libpm.Pm_GetHostErrorText(err_msg, 256)
err_msg = err_msg.value
else:
err_msg = libpm.Pm_GetErrorText(err_no)
raise MidiException(
"PortMIDI-ctypes error [{0}]: {1}".format(err_no,
err_msg.decode('utf-8')))
| gpl-2.0 |
chango/hustle | integration_test/test_join.py | 3 | 5774 | import unittest
from hustle import select, Table, h_sum, h_count
from setup import IMPS, PIXELS
from hustle.core.settings import Settings, overrides
class TestJoin(unittest.TestCase):
def setUp(self):
overrides['server'] = 'disco://localhost'
overrides['dump'] = False
overrides['nest'] = False
self.settings = Settings()
def tearDown(self):
pass
def test_simple_join(self):
imps = Table.from_tag(IMPS)
pix = Table.from_tag(PIXELS)
imp_sites = [(s, a) for (s, a) in select(imps.site_id, imps.ad_id,
where=imps.date < '2014-01-13', purge=True)]
pix_sites = [(s, a) for (s, a) in select(pix.site_id, pix.amount,
where=pix.date < '2014-01-13', purge=True)]
join = []
for imp_site, imp_ad_id in imp_sites:
for pix_site, pix_amount in pix_sites:
if imp_site == pix_site:
join.append((imp_ad_id, pix_amount))
res = select(imps.ad_id, pix.amount,
where=(imps.date < '2014-01-13', pix.date < '2014-01-13'),
join=(imps.site_id, pix.site_id),
order_by='amount')
results = list(res)
self.assertEqual(len(results), len(join))
res.purge()
for jtup in join:
self.assertIn(jtup, results)
lowest = 0
for ad_id, amount in results:
self.assertLessEqual(lowest, amount)
lowest = amount
def test_nested_join(self):
imps = Table.from_tag(IMPS)
pix = Table.from_tag(PIXELS)
imp_sites = list(select(imps.site_id, imps.ad_id,
where=imps.date < '2014-01-13', purge=True))
pix_sites = list(select(pix.site_id, pix.amount,
where=((pix.date < '2014-01-13') &
(pix.isActive == True),), purge=True))
join = []
for imp_site, imp_ad_id in imp_sites:
for pix_site, pix_amount in pix_sites:
if imp_site == pix_site:
join.append((imp_ad_id, pix_amount))
sub_pix = select(pix.site_id, pix.amount, pix.date,
where=((pix.date < '2014-01-15') & (pix.isActive == True)),
nest=True)
res = select(imps.ad_id, sub_pix.amount,
where=(imps.date < '2014-01-13', sub_pix.date < '2014-01-13'),
join=(imps.site_id, sub_pix.site_id))
results = [tuple(c) for c in res]
self.assertEqual(len(results), len(join))
res.purge()
for jtup in join:
self.assertIn(jtup, results)
def test_nested_self_join(self):
"""
A self join is joining the table against itself. This requires the use of aliases.
"""
imps = Table.from_tag(IMPS)
early_res = select(imps.ad_id, imps.cpm_millis,
where=imps.date < '2014-01-20')
early = list(early_res)
late_res = select(imps.ad_id, imps.cpm_millis,
where=imps.date >= '2014-01-20')
late = list(late_res)
join = {}
for eid, ecpm in early:
for lid, lcpm in late:
if eid == lid:
if eid not in join:
join[eid] = [0, 0, 0]
join[eid][0] += ecpm
join[eid][1] += lcpm
join[eid][2] += 1
early = select(imps.ad_id, imps.cpm_millis, where=imps.date < '2014-01-20', nest=True)
late = select(imps.ad_id, imps.cpm_millis, where=imps.date >= '2014-01-20', nest=True)
jimmy = select(early.ad_id.named('adididid'),
h_sum(early.cpm_millis).named('emillis'),
h_sum(late.cpm_millis).named('lmillis'),
h_count(),
where=(early, late),
join='ad_id')
james = list(jimmy)
self.assertEqual(len(join), len(james))
for (ad_id, emillis, lmillis, cnt) in james:
ecpm, lcpm, ocnt = join[ad_id]
self.assertEqual(emillis, ecpm)
self.assertEqual(lmillis, lcpm)
self.assertEqual(cnt, ocnt)
early_res.purge()
late_res.purge()
jimmy.purge()
def test_aggregate_join(self):
imps = Table.from_tag(IMPS)
pix = Table.from_tag(PIXELS)
imp_sites_res = select(imps.site_id, imps.ad_id,
where=imps.date < '2014-01-13')
pix_sites_res = select(pix.site_id, pix.amount,
where=pix.date < '2014-01-13')
imp_sites = list(imp_sites_res)
pix_sites = list(pix_sites_res)
join = {}
for imp_site, imp_ad_id in imp_sites:
for pix_site, pix_amount in pix_sites:
if imp_site == pix_site:
if imp_ad_id not in join:
join[imp_ad_id] = [0, 0]
join[imp_ad_id][0] += pix_amount
join[imp_ad_id][1] += 1
res = select(imps.ad_id, h_sum(pix.amount), h_count(),
where=(imps.date < '2014-01-13', pix.date < '2014-01-13'),
join=(imps.site_id, pix.site_id))
results = list(res)
self.assertEqual(len(results), len(join))
for (ad_id, amount, count) in results:
ramount, rcount = join[ad_id]
self.assertEqual(ramount, amount)
self.assertEqual(rcount, count)
imp_sites_res.purge()
pix_sites_res.purge()
res.purge()
| mit |
JohnHowland/kivy | examples/tutorials/pong/steps/step4/main.py | 57 | 1208 | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random import randint
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
def move(self):
self.pos = Vector(*self.velocity) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
def serve_ball(self):
self.ball.center = self.center
self.ball.velocity = Vector(4, 0).rotate(randint(0, 360))
def update(self, dt):
self.ball.move()
#bounce off top and bottom
if (self.ball.y < 0) or (self.ball.top > self.height):
self.ball.velocity_y *= -1
#bounce off left and right
if (self.ball.x < 0) or (self.ball.right > self.width):
self.ball.velocity_x *= -1
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
PongApp().run()
| mit |
singingwolfboy/flask-dance | flask_dance/contrib/dropbox.py | 1 | 4670 | from flask_dance.consumer import OAuth2ConsumerBlueprint
from functools import partial
from flask.globals import LocalProxy, _lookup_app_object
from flask import _app_ctx_stack as stack
__maintainer__ = "David Baumgold <david@davidbaumgold.com>"
def make_dropbox_blueprint(
app_key=None,
app_secret=None,
*,
scope=None,
offline=False,
force_reapprove=False,
disable_signup=False,
require_role=None,
redirect_url=None,
redirect_to=None,
login_url=None,
authorized_url=None,
session_class=None,
storage=None,
rule_kwargs=None,
):
"""
Make a blueprint for authenticating with Dropbox using OAuth 2. This requires
a client ID and client secret from Dropbox. You should either pass them to
this constructor, or make sure that your Flask application config defines
them, using the variables :envvar:`DROPBOX_OAUTH_CLIENT_ID` and
:envvar:`DROPBOX_OAUTH_CLIENT_SECRET`.
For more information about the ``force_reapprove``, ``disable_signup``,
and ``require_role`` arguments, `check the Dropbox API documentation
<https://www.dropbox.com/developers/documentation/http/overview>`_.
Args:
app_key (str): The client ID for your application on Dropbox.
app_secret (str): The client secret for your application on Dropbox
scope (str, optional): Comma-separated list of scopes for the OAuth token
offline (bool): Whether to request `Dropbox offline access
<https://www.dropbox.com/lp/developers/reference/oauth-guide>`_
for the OAuth token. Defaults to False
force_reapprove (bool): Force the user to approve the app again
if they've already done so.
disable_signup (bool): Prevent users from seeing a sign-up link
on the authorization page.
require_role (str): Pass the string ``work`` to require a Dropbox
for Business account, or the string ``personal`` to require a
personal account.
redirect_url (str): the URL to redirect to after the authentication
dance is complete
redirect_to (str): if ``redirect_url`` is not defined, the name of the
view to redirect to after the authentication dance is complete.
The actual URL will be determined by :func:`flask.url_for`
login_url (str, optional): the URL path for the ``login`` view.
Defaults to ``/dropbox``
authorized_url (str, optional): the URL path for the ``authorized`` view.
Defaults to ``/dropbox/authorized``.
session_class (class, optional): The class to use for creating a
Requests session. Defaults to
:class:`~flask_dance.consumer.requests.OAuth2Session`.
storage: A token storage class, or an instance of a token storage
class, to use for this blueprint. Defaults to
:class:`~flask_dance.consumer.storage.session.SessionStorage`.
rule_kwargs (dict, optional): Additional arguments that should be passed when adding
the login and authorized routes. Defaults to ``None``.
:rtype: :class:`~flask_dance.consumer.OAuth2ConsumerBlueprint`
:returns: A :doc:`blueprint <flask:blueprints>` to attach to your Flask app.
"""
authorization_url_params = {}
if offline:
authorization_url_params["token_access_type"] = "offline"
if force_reapprove:
authorization_url_params["force_reapprove"] = "true"
if disable_signup:
authorization_url_params["disable_signup"] = "true"
if require_role:
authorization_url_params["require_role"] = require_role
dropbox_bp = OAuth2ConsumerBlueprint(
"dropbox",
__name__,
client_id=app_key,
client_secret=app_secret,
scope=scope,
base_url="https://api.dropbox.com/2/",
authorization_url="https://www.dropbox.com/oauth2/authorize",
token_url="https://api.dropbox.com/oauth2/token",
redirect_url=redirect_url,
redirect_to=redirect_to,
login_url=login_url,
authorized_url=authorized_url,
authorization_url_params=authorization_url_params,
session_class=session_class,
storage=storage,
rule_kwargs=rule_kwargs,
)
dropbox_bp.from_config["client_id"] = "DROPBOX_OAUTH_CLIENT_ID"
dropbox_bp.from_config["client_secret"] = "DROPBOX_OAUTH_CLIENT_SECRET"
@dropbox_bp.before_app_request
def set_applocal_session():
ctx = stack.top
ctx.dropbox_oauth = dropbox_bp.session
return dropbox_bp
dropbox = LocalProxy(partial(_lookup_app_object, "dropbox_oauth"))
| mit |
olivierdalang/QGIS | tests/src/python/test_qgslocaldefaultsettings.py | 36 | 2306 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLocalDefaultSettings.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Nyall Dawson'
__date__ = '09/01/2020'
__copyright__ = 'Copyright 2020, The QGIS Project'
import qgis # NOQA
from qgis.core import (QgsSettings,
QgsLocalDefaultSettings,
QgsBearingNumericFormat)
from qgis.PyQt.QtCore import QCoreApplication
from qgis.testing import start_app, unittest
from utilities import (unitTestDataPath)
TEST_DATA_DIR = unitTestDataPath()
class TestQgsLocalDefaultSettings(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Run before all tests"""
QCoreApplication.setOrganizationName("QGIS_Test")
QCoreApplication.setOrganizationDomain("TestPyQgsWFSProvider.com")
QCoreApplication.setApplicationName("TestPyQgsWFSProvider")
QgsSettings().clear()
start_app()
def testBearingFormat(self):
s = QgsLocalDefaultSettings()
format = QgsBearingNumericFormat()
format.setNumberDecimalPlaces(9)
format.setDirectionFormat(QgsBearingNumericFormat.UseRange0To360)
s.setBearingFormat(format)
self.assertEqual(s.bearingFormat().numberDecimalPlaces(), 9)
self.assertEqual(s.bearingFormat().directionFormat(), QgsBearingNumericFormat.UseRange0To360)
format = QgsBearingNumericFormat()
format.setNumberDecimalPlaces(3)
format.setDirectionFormat(QgsBearingNumericFormat.UseRangeNegative180ToPositive180)
s.setBearingFormat(format)
self.assertEqual(s.bearingFormat().numberDecimalPlaces(), 3)
self.assertEqual(s.bearingFormat().directionFormat(), QgsBearingNumericFormat.UseRangeNegative180ToPositive180)
# new settings object, should persist.
s2 = QgsLocalDefaultSettings()
self.assertEqual(s2.bearingFormat().numberDecimalPlaces(), 3)
self.assertEqual(s2.bearingFormat().directionFormat(), QgsBearingNumericFormat.UseRangeNegative180ToPositive180)
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
spaceone/univention-management-console | univention/umc/__main__.py | 1 | 1358 | # -*- coding: utf-8 -*-
#
# Univention Management Console
#
# Copyright 2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.
from univention.umc import main
if __name__ == '__main__':
import sys
if sys.argv[0].endswith('__main__.py'):
sys.argv[0] = 'umc-server'
main()
| agpl-3.0 |
stevenzhang18/Indeed-Flask | lib/jinja2/utils.py | 323 | 16560 | # -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import errno
from collections import deque
from threading import Lock
from jinja2._compat import text_type, string_types, implements_iterator, \
url_quote
_word_split_re = re.compile(r'(\s+)')
_punctuation_re = re.compile(
'^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
'|'.join(map(re.escape, ('(', '<', '<'))),
'|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '>')))
)
)
_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_digits = '0123456789'
# special singleton representing missing values for the runtime
missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
# internal code
internal_code = set()
concat = u''.join
def contextfunction(f):
"""This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
"""
f.contextfunction = True
return f
def evalcontextfunction(f):
"""This decorator can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfunction = True
return f
def environmentfunction(f):
"""This decorator can be used to mark a function or method as environment
callable. This decorator works exactly like the :func:`contextfunction`
decorator just that the first argument is the active :class:`Environment`
and not context.
"""
f.environmentfunction = True
return f
def internalcode(f):
"""Marks the function as internally used"""
internal_code.add(f.__code__)
return f
def is_undefined(obj):
"""Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
"""
from jinja2.runtime import Undefined
return isinstance(obj, Undefined)
def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
messuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
def open_if_exists(filename, mode='rb'):
"""Returns a file descriptor for the filename if that file exists,
otherwise `None`.
"""
try:
return open(filename, mode)
except IOError as e:
if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL):
raise
def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return 'None'
elif obj is Ellipsis:
return 'Ellipsis'
# __builtin__ in 2.x, builtins in 3.x
if obj.__class__.__module__ in ('__builtin__', 'builtins'):
name = obj.__class__.__name__
else:
name = obj.__class__.__module__ + '.' + obj.__class__.__name__
return '%s object' % name
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
def urlize(text, trim_url_limit=None, nofollow=False, target=None):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(text_type(escape(text)))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
if target is not None and isinstance(target, string_types):
target_attr = ' target="%s"' % target
else:
target_attr = ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
not middle.startswith('https://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s%s>%s</a>' % (middle,
nofollow_attr, target_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s%s>%s</a>' % (middle,
nofollow_attr, target_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words)
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
"""Generate some lorem ipsum for the template."""
from jinja2.constants import LOREM_IPSUM_WORDS
from random import choice, randrange
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in range(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(range(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ','
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += '.'
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p = u' '.join(p)
if p.endswith(','):
p = p[:-1] + '.'
elif not p.endswith('.'):
p += '.'
result.append(p)
if not html:
return u'\n\n'.join(result)
return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = for_qs and b'' or b'/'
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
class LRUCache(object):
"""A simple LRU Cache implementation."""
# this is fast for small capacities (something below 1000) but doesn't
# scale. But as long as it's only used as storage for templates this
# won't do any harm.
def __init__(self, capacity):
self.capacity = capacity
self._mapping = {}
self._queue = deque()
self._postinit()
def _postinit(self):
# alias all queue methods for faster lookup
self._popleft = self._queue.popleft
self._pop = self._queue.pop
self._remove = self._queue.remove
self._wlock = Lock()
self._append = self._queue.append
def __getstate__(self):
return {
'capacity': self.capacity,
'_mapping': self._mapping,
'_queue': self._queue
}
def __setstate__(self, d):
self.__dict__.update(d)
self._postinit()
def __getnewargs__(self):
return (self.capacity,)
def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release()
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
def __contains__(self, key):
"""Check if a key exists in this cache."""
return key in self._mapping
def __len__(self):
"""Return the current size of the cache."""
return len(self._mapping)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self._mapping
)
def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise a `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
except ValueError:
# if something removed the key from the container
# when we read, ignore the ValueError that we would
# get otherwise.
pass
self._append(key)
return rv
finally:
self._wlock.release()
def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
self._remove(key)
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release()
def __delitem__(self, key):
"""Remove an item from the cache dict.
Raise a `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
del self._mapping[key]
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
finally:
self._wlock.release()
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
def iteritems(self):
"""Iterate over all items."""
return iter(self.items())
def values(self):
"""Return a list of all values."""
return [x[1] for x in self.items()]
def itervalue(self):
"""Iterate over all values."""
return iter(self.values())
def keys(self):
"""Return a list of all keys ordered by most recent usage."""
return list(self)
def iterkeys(self):
"""Iterate over all keys in the cache dict, ordered by
the most recent usage.
"""
return reversed(tuple(self._queue))
__iter__ = iterkeys
def __reversed__(self):
"""Iterate over the values in the cache dict, oldest items
coming first.
"""
return iter(tuple(self._queue))
__copy__ = copy
# register the LRU cache as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(LRUCache)
except ImportError:
pass
@implements_iterator
class Cycler(object):
"""A cycle helper for templates."""
def __init__(self, *items):
if not items:
raise RuntimeError('at least one item has to be provided')
self.items = items
self.reset()
def reset(self):
"""Resets the cycle."""
self.pos = 0
@property
def current(self):
"""Returns the current item."""
return self.items[self.pos]
def __next__(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
class Joiner(object):
"""A joining helper for templates."""
def __init__(self, sep=u', '):
self.sep = sep
self.used = False
def __call__(self):
if not self.used:
self.used = True
return u''
return self.sep
# Imported here because that's where it was in the past
from markupsafe import Markup, escape, soft_unicode
| apache-2.0 |
dkodnik/arp | addons/account_analytic_plans/report/crossovered_analytic.py | 321 | 8149 | # -*- 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 osv
from openerp.report import report_sxw
class crossovered_analytic(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(crossovered_analytic, self).__init__(cr, uid, name, context = context)
self.localcontext.update( {
'time': time,
'lines': self._lines,
'ref_lines': self._ref_lines,
'find_children': self.find_children,
})
self.base_amount = 0.00
def find_children(self, ref_ids):
if not ref_ids: return []
to_return_ids = []
final_list = []
parent_list = []
set_list = []
analytic_obj = self.pool.get('account.analytic.account')
for id in ref_ids:
# to avoid duplicate entries
if id not in to_return_ids:
to_return_ids.append(analytic_obj.search(self.cr,self.uid,[('parent_id','child_of',[id])]))
data_accnt = analytic_obj.browse(self.cr,self.uid,to_return_ids[0])
for data in data_accnt:
if data.parent_id and data.parent_id.id == ref_ids[0]:
parent_list.append(data.id)
final_list.append(ref_ids[0])
set_list = self.set_account(parent_list)
final_list.extend(set_list)
return final_list #to_return_ids[0]
def set_account(self, cats):
lst = []
category = self.pool.get('account.analytic.account').read(self.cr, self.uid, cats)
for cat in category:
lst.append(cat['id'])
if cat['child_ids']:
lst.extend(self.set_account(cat['child_ids']))
return lst
def _ref_lines(self, form):
result = []
res = {}
acc_pool = self.pool.get('account.analytic.account')
line_pool = self.pool.get('account.analytic.line')
self.dict_acc_ref = {}
if form['journal_ids']:
journal = " in (" + ','.join(map(lambda x: str(x), form['journal_ids'])) + ")"
else:
journal = 'is not null'
query_general = "SELECT id FROM account_analytic_line WHERE (journal_id " + journal +") AND date>='"+ str(form['date1']) +"'"" AND date<='" + str(form['date2']) + "'"
self.cr.execute(query_general)
l_ids = self.cr.fetchall()
line_ids = [x[0] for x in l_ids]
obj_line = line_pool.browse(self.cr,self.uid,line_ids)
#this structure will be usefull for easily knowing the account_analytic_line that are related to the reference account. At this purpose, we save the move_id of analytic lines.
self.dict_acc_ref[form['ref']] = []
children_list = acc_pool.search(self.cr, self.uid, [('parent_id', 'child_of', [form['ref']])])
for obj in obj_line:
if obj.account_id.id in children_list:
if obj.move_id and obj.move_id.id not in self.dict_acc_ref[form['ref']]:
self.dict_acc_ref[form['ref']].append(obj.move_id.id)
res['ref_name'] = acc_pool.name_get(self.cr, self.uid, [form['ref']])[0][1]
res['ref_code'] = acc_pool.browse(self.cr, self.uid, form['ref']).code
self.final_list = children_list
selected_ids = line_pool.search(self.cr, self.uid, [('account_id', 'in' ,self.final_list)])
res['ref_qty'] = 0.0
res['ref_amt'] = 0.0
self.base_amount = 0.0
if selected_ids:
query = "SELECT SUM(aal.amount) AS amt, SUM(aal.unit_amount) AS qty FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id = aaa.id AND aal.id IN ("+','.join(map(str,selected_ids))+") AND (aal.journal_id " + journal +") AND aal.date>='"+ str(form['date1']) +"'"" AND aal.date<='" + str(form['date2']) + "'"
self.cr.execute(query)
info=self.cr.dictfetchall()
res['ref_qty'] = info[0]['qty']
res['ref_amt'] = info[0]['amt']
self.base_amount = info[0]['amt']
result.append(res)
return result
def _lines(self, form, ids=None):
if ids is None:
ids = {}
if not ids:
ids = self.ids
if form['journal_ids']:
journal=" in (" + ','.join(map(lambda x: str(x), form['journal_ids'])) + ")"
else:
journal= 'is not null'
acc_pool = self.pool.get('account.analytic.account')
line_pool = self.pool.get('account.analytic.line')
acc_id = []
final = []
self.list_ids = []
self.final_list = self.find_children(ids)
for acc_id in self.final_list:
selected_ids = line_pool.search(self.cr, self.uid, [('account_id','=',acc_id), ('move_id', 'in', self.dict_acc_ref[form['ref']])])
if selected_ids:
query="SELECT aaa.code AS code, SUM(aal.amount) AS amt, SUM(aal.unit_amount) AS qty, aaa.name AS acc_name, aal.account_id AS id FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id=aaa.id AND aal.id IN ("+','.join(map(str,selected_ids))+") AND (aal.journal_id " + journal +") AND aal.date>='"+ str(form['date1']) +"'"" AND aal.date<='" + str(form['date2']) + "'"" GROUP BY aal.account_id,aaa.name,aaa.code ORDER BY aal.account_id"
self.cr.execute(query)
res = self.cr.dictfetchall()
if res:
for element in res:
if self.base_amount <> 0.00:
element['perc'] = (element['amt'] / self.base_amount) * 100.00
else:
element['perc'] = 0.00
else:
result = {}
res = []
result['id'] = acc_id
data_account = acc_pool.browse(self.cr, self.uid, acc_id)
result['acc_name'] = data_account.name
result['code'] = data_account.code
result['amt'] = result['qty'] = result['perc'] = 0.00
if not form['empty_line']:
res.append(result)
else:
result = {}
res = []
result['id'] = acc_id
data_account = acc_pool.browse(self.cr, self.uid, acc_id)
result['acc_name'] = data_account.name
result['code'] = data_account.code
result['amt'] = result['qty'] = result['perc'] = 0.00
if not form['empty_line']:
res.append(result)
for item in res:
obj_acc = acc_pool.name_get(self.cr,self.uid,[item['id']])
item['acc_name'] = obj_acc[0][1]
final.append(item)
return final
class report_crossoveredanalyticplans(osv.AbstractModel):
_name = 'report.account_analytic_plans.report_crossoveredanalyticplans'
_inherit = 'report.abstract_report'
_template = 'account_analytic_plans.report_crossoveredanalyticplans'
_wrapped_report_class = crossovered_analytic
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
inova-tecnologias/jenova | src/test/tests/dlists_tests.py | 1 | 4051 | from test.base import BaseTest
import unittest, socket, requests, json
from time import sleep
from unittest import TestCase
# supress ssl warnings.
requests.packages.urllib3.disable_warnings(
requests
.packages
.urllib3
.exceptions
.InsecureRequestWarning)
class DlistsTestCase(TestCase, BaseTest):
def setUp(self):
BaseTest.setUp(self)
self.dlists_url = '%s/services/%s/domains/%s/dlists' % (self.general['api_url'],
self.service_zimbra['name'],
self.domain['name'],)
def tearDown(self):
BaseTest.tearDown(self)
# -------------------------------------------------------------------- tests
def test_create_dlist_pass(self):
# create dlist
d = json.dumps({
'dlist' : self.dlists['dlist_valid'],
'accounts' : self.dlists['accounts'],
})
r = requests.post(self.dlists_url, headers=self.general['headers'],
data=d, verify=False)
if not r.status_code in [201]:
self.assertTrue(False)
print 'PASS: create Dlist'
def test_create_dlist_fail(self):
#try create dlist with invalid name/domain
#PASS if test fails
d = json.dumps({
'dlist' : self.dlists['dlist_invalid'],
'accounts' : self.dlists['accounts'],
})
r = requests.post(self.dlists_url, headers=self.general['headers'],
data=d, verify=False)
if not r.status_code in [201]:
self.assertTrue(True)
print 'PASS: fail on create invalid Dlist'
def test_get_dlist_pass(self):
url_get = self.dlists_url + '/' + self.dlists['dlist_valid']
r = requests.get(url_get, headers=self.general['headers'], verify=False)
if not r.status_code in [200]:
self.assertTrue(False)
print 'PASS: get Dlist retunr result'
def test_get_dlist_fail(self):
url_get = self.dlists_url + '/' + self.dlists['dlist_invalid']
r = requests.get(url_get, headers=self.general['headers'], verify=False)
if r.status_code == 404:
self.assertTrue(True)
print 'PASS: get Dlist invalid, retunr not found'
def test_get_all_dlist_pass(self):
url_get = self.dlists_url
r = requests.get(url_get, headers=self.general['headers'], verify=False)
if not r.status_code in [200]:
self.assertTrue(False)
print 'PASS: get Dlist retunr result'
def test_update_dlist_pass(self):
# update dlist, removing actual members and add news
d = json.dumps({
'dlist' : self.dlists['dlist_valid'],
'accounts' : self.dlists['accounts_to_update'],
})
url_put = self.dlists_url + '/' + self.dlists['dlist_valid']
r = requests.put(url_put, headers=self.general['headers'],
data=d, verify=False)
if not r.status_code in [201]:
self.assertTrue(False)
print 'PASS: Updated Dlist'
def test_update_dlist_fail(self):
# try update invalid dlist,
# Pass when test fails
d = json.dumps({
'dlist' : self.dlists['dlist_invalid'],
'accounts' : self.dlists['accounts_to_update'],
})
url_put = self.dlists_url + '/' + self.dlists['dlist_invalid']
r = requests.put(url_put, headers=self.general['headers'],
data=d, verify=False)
if r.status_code == 400:
self.assertTrue(True)
print 'PASS: Updated Dlist fails on update invalid dlist'
def test_delete_dlist_pass(self):
url_put = self.dlists_url + '/' + self.dlists['dlist_valid']
r = requests.delete(url_put, headers=self.general['headers'],verify=False)
if r.status_code == 204:
self.assertTrue(True)
print 'PASS: Delete Dlist Sucessful'
def test_delete_dlist_fail(self):
url_put = self.dlists_url + '/' + self.dlists['dlist_invalid']
r = requests.delete(url_put, headers=self.general['headers'],verify=False)
if not r.status_code == 204:
self.assertTrue(True)
print 'PASS: Try delete Dlist invalid fails'
if __name__ == "__main__":
unittest.main() | apache-2.0 |
dongjoon-hyun/tensorflow | tensorflow/contrib/learn/python/learn/estimators/state_saving_rnn_estimator_test.py | 19 | 24449 | # 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 learn.estimators.state_saving_rnn_estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
import numpy as np
from tensorflow.contrib import lookup
from tensorflow.contrib.layers.python.layers import feature_column
from tensorflow.contrib.layers.python.layers import target_column as target_column_lib
from tensorflow.contrib.learn.python.learn.estimators import constants
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.estimators import rnn_common
from tensorflow.contrib.learn.python.learn.estimators import run_config
from tensorflow.contrib.learn.python.learn.estimators import state_saving_rnn_estimator as ssre
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
class PrepareInputsForRnnTest(test.TestCase):
def _test_prepare_inputs_for_rnn(self, sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected):
features_by_time = ssre._prepare_inputs_for_rnn(sequence_features,
context_features,
sequence_feature_columns,
num_unroll)
with self.cached_session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(lookup_ops.tables_initializer())
features_val = sess.run(features_by_time)
self.assertAllEqual(expected, features_val)
def testPrepareInputsForRnnBatchSize1(self):
num_unroll = 3
expected = [
np.array([[11., 31., 5., 7.]]), np.array([[12., 32., 5., 7.]]),
np.array([[13., 33., 5., 7.]])
]
sequence_features = {
'seq_feature0': constant_op.constant([[11., 12., 13.]]),
'seq_feature1': constant_op.constant([[31., 32., 33.]])
}
sequence_feature_columns = [
feature_column.real_valued_column(
'seq_feature0', dimension=1),
feature_column.real_valued_column(
'seq_feature1', dimension=1),
]
context_features = {
'ctx_feature0': constant_op.constant([[5.]]),
'ctx_feature1': constant_op.constant([[7.]])
}
self._test_prepare_inputs_for_rnn(sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected)
def testPrepareInputsForRnnBatchSize2(self):
num_unroll = 3
expected = [
np.array([[11., 31., 5., 7.], [21., 41., 6., 8.]]),
np.array([[12., 32., 5., 7.], [22., 42., 6., 8.]]),
np.array([[13., 33., 5., 7.], [23., 43., 6., 8.]])
]
sequence_features = {
'seq_feature0':
constant_op.constant([[11., 12., 13.], [21., 22., 23.]]),
'seq_feature1':
constant_op.constant([[31., 32., 33.], [41., 42., 43.]])
}
sequence_feature_columns = [
feature_column.real_valued_column(
'seq_feature0', dimension=1),
feature_column.real_valued_column(
'seq_feature1', dimension=1),
]
context_features = {
'ctx_feature0': constant_op.constant([[5.], [6.]]),
'ctx_feature1': constant_op.constant([[7.], [8.]])
}
self._test_prepare_inputs_for_rnn(sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected)
def testPrepareInputsForRnnNoContext(self):
num_unroll = 3
expected = [
np.array([[11., 31.], [21., 41.]]), np.array([[12., 32.], [22., 42.]]),
np.array([[13., 33.], [23., 43.]])
]
sequence_features = {
'seq_feature0':
constant_op.constant([[11., 12., 13.], [21., 22., 23.]]),
'seq_feature1':
constant_op.constant([[31., 32., 33.], [41., 42., 43.]])
}
sequence_feature_columns = [
feature_column.real_valued_column(
'seq_feature0', dimension=1),
feature_column.real_valued_column(
'seq_feature1', dimension=1),
]
context_features = None
self._test_prepare_inputs_for_rnn(sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected)
def testPrepareInputsForRnnSparse(self):
num_unroll = 2
embedding_dimension = 8
expected = [
np.array([[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.]]),
np.array([[1., 1., 1., 1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1., 1., 1., 1.]])
]
sequence_features = {
'wire_cast':
sparse_tensor.SparseTensor(
indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1],
[2, 0, 0], [2, 1, 1]],
values=[
b'marlo', b'stringer', b'omar', b'stringer', b'marlo',
b'marlo', b'omar'
],
dense_shape=[3, 2, 2])
}
wire_cast = feature_column.sparse_column_with_keys(
'wire_cast', ['marlo', 'omar', 'stringer'])
sequence_feature_columns = [
feature_column.embedding_column(
wire_cast,
dimension=embedding_dimension,
combiner='sum',
initializer=init_ops.ones_initializer())
]
context_features = None
self._test_prepare_inputs_for_rnn(sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected)
def testPrepareInputsForRnnSparseAndDense(self):
num_unroll = 2
embedding_dimension = 8
dense_dimension = 2
expected = [
np.array([[1., 1., 1., 1., 1., 1., 1., 1., 111., 112.],
[1., 1., 1., 1., 1., 1., 1., 1., 211., 212.],
[1., 1., 1., 1., 1., 1., 1., 1., 311., 312.]]),
np.array([[1., 1., 1., 1., 1., 1., 1., 1., 121., 122.],
[2., 2., 2., 2., 2., 2., 2., 2., 221., 222.],
[1., 1., 1., 1., 1., 1., 1., 1., 321., 322.]])
]
sequence_features = {
'wire_cast':
sparse_tensor.SparseTensor(
indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1],
[2, 0, 0], [2, 1, 1]],
values=[
b'marlo', b'stringer', b'omar', b'stringer', b'marlo',
b'marlo', b'omar'
],
dense_shape=[3, 2, 2]),
'seq_feature0':
constant_op.constant([[[111., 112.], [121., 122.]],
[[211., 212.], [221., 222.]],
[[311., 312.], [321., 322.]]])
}
wire_cast = feature_column.sparse_column_with_keys(
'wire_cast', ['marlo', 'omar', 'stringer'])
wire_cast_embedded = feature_column.embedding_column(
wire_cast,
dimension=embedding_dimension,
combiner='sum',
initializer=init_ops.ones_initializer())
seq_feature0_column = feature_column.real_valued_column(
'seq_feature0', dimension=dense_dimension)
sequence_feature_columns = [seq_feature0_column, wire_cast_embedded]
context_features = None
self._test_prepare_inputs_for_rnn(sequence_features, context_features,
sequence_feature_columns, num_unroll,
expected)
class StateSavingRnnEstimatorTest(test.TestCase):
def testPrepareFeaturesForSQSS(self):
mode = model_fn_lib.ModeKeys.TRAIN
seq_feature_name = 'seq_feature'
sparse_seq_feature_name = 'wire_cast'
ctx_feature_name = 'ctx_feature'
sequence_length = 4
embedding_dimension = 8
features = {
sparse_seq_feature_name:
sparse_tensor.SparseTensor(
indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1],
[2, 0, 0], [2, 1, 1]],
values=[
b'marlo', b'stringer', b'omar', b'stringer', b'marlo',
b'marlo', b'omar'
],
dense_shape=[3, 2, 2]),
seq_feature_name:
constant_op.constant(
1.0, shape=[sequence_length]),
ctx_feature_name:
constant_op.constant(2.0)
}
labels = constant_op.constant(5.0, shape=[sequence_length])
wire_cast = feature_column.sparse_column_with_keys(
'wire_cast', ['marlo', 'omar', 'stringer'])
sequence_feature_columns = [
feature_column.real_valued_column(
seq_feature_name, dimension=1), feature_column.embedding_column(
wire_cast,
dimension=embedding_dimension,
initializer=init_ops.ones_initializer())
]
context_feature_columns = [
feature_column.real_valued_column(
ctx_feature_name, dimension=1)
]
expected_sequence = {
rnn_common.RNNKeys.LABELS_KEY:
np.array([5., 5., 5., 5.]),
seq_feature_name:
np.array([1., 1., 1., 1.]),
sparse_seq_feature_name:
sparse_tensor.SparseTensor(
indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1],
[2, 0, 0], [2, 1, 1]],
values=[
b'marlo', b'stringer', b'omar', b'stringer', b'marlo',
b'marlo', b'omar'
],
dense_shape=[3, 2, 2]),
}
expected_context = {ctx_feature_name: 2.}
sequence, context = ssre._prepare_features_for_sqss(
features, labels, mode, sequence_feature_columns,
context_feature_columns)
def assert_equal(expected, got):
self.assertEqual(sorted(expected), sorted(got))
for k, v in expected.items():
if isinstance(v, sparse_tensor.SparseTensor):
self.assertAllEqual(v.values.eval(), got[k].values)
self.assertAllEqual(v.indices.eval(), got[k].indices)
self.assertAllEqual(v.dense_shape.eval(), got[k].dense_shape)
else:
self.assertAllEqual(v, got[k])
with self.cached_session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(lookup_ops.tables_initializer())
actual_sequence, actual_context = sess.run(
[sequence, context])
assert_equal(expected_sequence, actual_sequence)
assert_equal(expected_context, actual_context)
def _getModelFnOpsForMode(self, mode):
"""Helper for testGetRnnModelFn{Train,Eval,Infer}()."""
num_units = [4]
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=1)
]
features = {
'inputs': constant_op.constant([1., 2., 3.]),
}
labels = constant_op.constant([1., 0., 1.])
model_fn = ssre._get_rnn_model_fn(
cell_type='basic_rnn',
target_column=target_column_lib.multi_class_target(n_classes=2),
optimizer='SGD',
num_unroll=2,
num_units=num_units,
num_threads=1,
queue_capacity=10,
batch_size=1,
# Only CLASSIFICATION yields eval metrics to test for.
problem_type=constants.ProblemType.CLASSIFICATION,
sequence_feature_columns=seq_columns,
context_feature_columns=None,
learning_rate=0.1)
model_fn_ops = model_fn(features=features, labels=labels, mode=mode)
return model_fn_ops
# testGetRnnModelFn{Train,Eval,Infer}() test which fields
# of ModelFnOps are set depending on mode.
def testGetRnnModelFnTrain(self):
model_fn_ops = self._getModelFnOpsForMode(model_fn_lib.ModeKeys.TRAIN)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNotNone(model_fn_ops.loss)
self.assertIsNotNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept neither.
self.assertNotEqual(len(model_fn_ops.eval_metric_ops), 0)
def testGetRnnModelFnEval(self):
model_fn_ops = self._getModelFnOpsForMode(model_fn_lib.ModeKeys.EVAL)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNotNone(model_fn_ops.loss)
self.assertIsNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept neither.
self.assertNotEqual(len(model_fn_ops.eval_metric_ops), 0)
def testGetRnnModelFnInfer(self):
model_fn_ops = self._getModelFnOpsForMode(model_fn_lib.ModeKeys.INFER)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNone(model_fn_ops.loss)
self.assertIsNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept both.
self.assertFalse(model_fn_ops.eval_metric_ops)
def testExport(self):
input_feature_key = 'magic_input_feature_key'
batch_size = 8
num_units = [4]
sequence_length = 10
num_unroll = 2
num_classes = 2
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=4)
]
def get_input_fn(mode, seed):
def input_fn():
features = {}
random_sequence = random_ops.random_uniform(
[sequence_length + 1], 0, 2, dtype=dtypes.int32, seed=seed)
labels = array_ops.slice(random_sequence, [0], [sequence_length])
inputs = math_ops.to_float(
array_ops.slice(random_sequence, [1], [sequence_length]))
features = {'inputs': inputs}
if mode == model_fn_lib.ModeKeys.INFER:
input_examples = array_ops.placeholder(dtypes.string)
features[input_feature_key] = input_examples
labels = None
return features, labels
return input_fn
model_dir = tempfile.mkdtemp()
def estimator_fn():
return ssre.StateSavingRnnEstimator(
constants.ProblemType.CLASSIFICATION,
num_units=num_units,
num_unroll=num_unroll,
batch_size=batch_size,
sequence_feature_columns=seq_columns,
num_classes=num_classes,
predict_probabilities=True,
model_dir=model_dir,
queue_capacity=2 + batch_size,
seed=1234)
# Train a bit to create an exportable checkpoint.
estimator_fn().fit(input_fn=get_input_fn(
model_fn_lib.ModeKeys.TRAIN, seed=1234),
steps=100)
# Now export, but from a fresh estimator instance, like you would
# in an export binary. That means .export() has to work without
# .fit() being called on the same object.
export_dir = tempfile.mkdtemp()
print('Exporting to', export_dir)
estimator_fn().export(
export_dir,
input_fn=get_input_fn(
model_fn_lib.ModeKeys.INFER, seed=4321),
use_deprecated_input_fn=False,
input_feature_key=input_feature_key)
# Smoke tests to ensure deprecated constructor functions still work.
class LegacyConstructorTest(test.TestCase):
def _get_input_fn(self,
sequence_length,
seed=None):
def input_fn():
random_sequence = random_ops.random_uniform(
[sequence_length + 1], 0, 2, dtype=dtypes.int32, seed=seed)
labels = array_ops.slice(random_sequence, [0], [sequence_length])
inputs = math_ops.to_float(
array_ops.slice(random_sequence, [1], [sequence_length]))
return {'inputs': inputs}, labels
return input_fn
# TODO(jtbates): move all tests below to a benchmark test.
class StateSavingRNNEstimatorLearningTest(test.TestCase):
"""Learning tests for state saving RNN Estimators."""
def testLearnSineFunction(self):
"""Tests learning a sine function."""
batch_size = 8
num_unroll = 5
sequence_length = 64
train_steps = 250
eval_steps = 20
num_rnn_layers = 1
num_units = [4] * num_rnn_layers
learning_rate = 0.3
loss_threshold = 0.035
def get_sin_input_fn(sequence_length, increment, seed=None):
def input_fn():
start = random_ops.random_uniform(
(), minval=0, maxval=(np.pi * 2.0), dtype=dtypes.float32, seed=seed)
sin_curves = math_ops.sin(
math_ops.linspace(start, (sequence_length - 1) * increment,
sequence_length + 1))
inputs = array_ops.slice(sin_curves, [0], [sequence_length])
labels = array_ops.slice(sin_curves, [1], [sequence_length])
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=1)
]
config = run_config.RunConfig(tf_random_seed=1234)
dropout_keep_probabilities = [0.9] * (num_rnn_layers + 1)
sequence_estimator = ssre.StateSavingRnnEstimator(
constants.ProblemType.LINEAR_REGRESSION,
num_units=num_units,
cell_type='lstm',
num_unroll=num_unroll,
batch_size=batch_size,
sequence_feature_columns=seq_columns,
learning_rate=learning_rate,
dropout_keep_probabilities=dropout_keep_probabilities,
config=config,
queue_capacity=2 * batch_size,
seed=1234)
train_input_fn = get_sin_input_fn(sequence_length, np.pi / 32, seed=1234)
eval_input_fn = get_sin_input_fn(sequence_length, np.pi / 32, seed=4321)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
loss = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)['loss']
self.assertLess(loss, loss_threshold,
'Loss should be less than {}; got {}'.format(loss_threshold,
loss))
def testLearnShiftByOne(self):
"""Tests that learning a 'shift-by-one' example.
Each label sequence consists of the input sequence 'shifted' by one place.
The RNN must learn to 'remember' the previous input.
"""
batch_size = 16
num_classes = 2
num_unroll = 32
sequence_length = 32
train_steps = 300
eval_steps = 20
num_units = [4]
learning_rate = 0.5
accuracy_threshold = 0.9
def get_shift_input_fn(sequence_length, seed=None):
def input_fn():
random_sequence = random_ops.random_uniform(
[sequence_length + 1], 0, 2, dtype=dtypes.int32, seed=seed)
labels = array_ops.slice(random_sequence, [0], [sequence_length])
inputs = math_ops.to_float(
array_ops.slice(random_sequence, [1], [sequence_length]))
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=1)
]
config = run_config.RunConfig(tf_random_seed=21212)
sequence_estimator = ssre.StateSavingRnnEstimator(
constants.ProblemType.CLASSIFICATION,
num_units=num_units,
cell_type='lstm',
num_unroll=num_unroll,
batch_size=batch_size,
sequence_feature_columns=seq_columns,
num_classes=num_classes,
learning_rate=learning_rate,
config=config,
predict_probabilities=True,
queue_capacity=2 + batch_size,
seed=1234)
train_input_fn = get_shift_input_fn(sequence_length, seed=12321)
eval_input_fn = get_shift_input_fn(sequence_length, seed=32123)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
evaluation = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)
accuracy = evaluation['accuracy']
self.assertGreater(accuracy, accuracy_threshold,
'Accuracy should be higher than {}; got {}'.format(
accuracy_threshold, accuracy))
# Testing `predict` when `predict_probabilities=True`.
prediction_dict = sequence_estimator.predict(
input_fn=eval_input_fn, as_iterable=False)
self.assertListEqual(
sorted(list(prediction_dict.keys())),
sorted([
prediction_key.PredictionKey.CLASSES,
prediction_key.PredictionKey.PROBABILITIES, ssre._get_state_name(0)
]))
predictions = prediction_dict[prediction_key.PredictionKey.CLASSES]
probabilities = prediction_dict[prediction_key.PredictionKey.PROBABILITIES]
self.assertListEqual(list(predictions.shape), [batch_size, sequence_length])
self.assertListEqual(
list(probabilities.shape), [batch_size, sequence_length, 2])
def testLearnLyrics(self):
lyrics = 'if I go there will be trouble and if I stay it will be double'
lyrics_list = lyrics.split()
sequence_length = len(lyrics_list)
vocab = set(lyrics_list)
batch_size = 16
num_classes = len(vocab)
num_unroll = 7 # not a divisor of sequence_length
train_steps = 350
eval_steps = 30
num_units = [4]
learning_rate = 0.4
accuracy_threshold = 0.65
def get_lyrics_input_fn(seed):
def input_fn():
start = random_ops.random_uniform(
(), minval=0, maxval=sequence_length, dtype=dtypes.int32, seed=seed)
# Concatenate lyrics_list so inputs and labels wrap when start > 0.
lyrics_list_concat = lyrics_list + lyrics_list
inputs_dense = array_ops.slice(lyrics_list_concat, [start],
[sequence_length])
indices = array_ops.constant(
[[i, 0] for i in range(sequence_length)], dtype=dtypes.int64)
dense_shape = [sequence_length, 1]
inputs = sparse_tensor.SparseTensor(
indices=indices, values=inputs_dense, dense_shape=dense_shape)
table = lookup.string_to_index_table_from_tensor(
mapping=list(vocab), default_value=-1, name='lookup')
labels = table.lookup(
array_ops.slice(lyrics_list_concat, [start + 1], [sequence_length]))
return {'lyrics': inputs}, labels
return input_fn
sequence_feature_columns = [
feature_column.embedding_column(
feature_column.sparse_column_with_keys('lyrics', vocab),
dimension=8)
]
config = run_config.RunConfig(tf_random_seed=21212)
sequence_estimator = ssre.StateSavingRnnEstimator(
constants.ProblemType.CLASSIFICATION,
num_units=num_units,
cell_type='basic_rnn',
num_unroll=num_unroll,
batch_size=batch_size,
sequence_feature_columns=sequence_feature_columns,
num_classes=num_classes,
learning_rate=learning_rate,
config=config,
predict_probabilities=True,
queue_capacity=2 + batch_size,
seed=1234)
train_input_fn = get_lyrics_input_fn(seed=12321)
eval_input_fn = get_lyrics_input_fn(seed=32123)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
evaluation = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)
accuracy = evaluation['accuracy']
self.assertGreater(accuracy, accuracy_threshold,
'Accuracy should be higher than {}; got {}'.format(
accuracy_threshold, accuracy))
if __name__ == '__main__':
test.main()
| apache-2.0 |
NoahFlowa/glowing-spoon | venv/lib/python2.7/site-packages/sqlalchemy/testing/suite/test_update_delete.py | 203 | 1582 | from .. import fixtures, config
from ..assertions import eq_
from sqlalchemy import Integer, String
from ..schema import Table, Column
class SimpleUpdateDeleteTest(fixtures.TablesTest):
run_deletes = 'each'
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table('plain_pk', metadata,
Column('id', Integer, primary_key=True),
Column('data', String(50))
)
@classmethod
def insert_data(cls):
config.db.execute(
cls.tables.plain_pk.insert(),
[
{"id": 1, "data": "d1"},
{"id": 2, "data": "d2"},
{"id": 3, "data": "d3"},
]
)
def test_update(self):
t = self.tables.plain_pk
r = config.db.execute(
t.update().where(t.c.id == 2),
data="d2_new"
)
assert not r.is_insert
assert not r.returns_rows
eq_(
config.db.execute(t.select().order_by(t.c.id)).fetchall(),
[
(1, "d1"),
(2, "d2_new"),
(3, "d3")
]
)
def test_delete(self):
t = self.tables.plain_pk
r = config.db.execute(
t.delete().where(t.c.id == 2)
)
assert not r.is_insert
assert not r.returns_rows
eq_(
config.db.execute(t.select().order_by(t.c.id)).fetchall(),
[
(1, "d1"),
(3, "d3")
]
)
__all__ = ('SimpleUpdateDeleteTest', )
| apache-2.0 |
edevil/django | django/db/backends/oracle/introspection.py | 5 | 11440 | import re
import cx_Oracle
from django.db.backends import BaseDatabaseIntrospection, FieldInfo, TableInfo
from django.utils.encoding import force_text
foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
class DatabaseIntrospection(BaseDatabaseIntrospection):
# Maps type objects to Django Field types.
data_types_reverse = {
cx_Oracle.BLOB: 'BinaryField',
cx_Oracle.CLOB: 'TextField',
cx_Oracle.DATETIME: 'DateField',
cx_Oracle.FIXED_CHAR: 'CharField',
cx_Oracle.NCLOB: 'TextField',
cx_Oracle.NUMBER: 'DecimalField',
cx_Oracle.STRING: 'CharField',
cx_Oracle.TIMESTAMP: 'DateTimeField',
}
try:
data_types_reverse[cx_Oracle.NATIVE_FLOAT] = 'FloatField'
except AttributeError:
pass
try:
data_types_reverse[cx_Oracle.UNICODE] = 'CharField'
except AttributeError:
pass
def get_field_type(self, data_type, description):
# If it's a NUMBER with scale == 0, consider it an IntegerField
if data_type == cx_Oracle.NUMBER:
precision, scale = description[4:6]
if scale == 0:
if precision > 11:
return 'BigIntegerField'
elif precision == 1:
return 'BooleanField'
else:
return 'IntegerField'
elif scale == -127:
return 'FloatField'
return super(DatabaseIntrospection, self).get_field_type(data_type, description)
def get_table_list(self, cursor):
"""
Returns a list of table and view names in the current database.
"""
cursor.execute("SELECT TABLE_NAME, 't' FROM USER_TABLES UNION ALL "
"SELECT VIEW_NAME, 'v' FROM USER_VIEWS")
return [TableInfo(row[0].lower(), row[1]) for row in cursor.fetchall()]
def get_table_description(self, cursor, table_name):
"Returns a description of the table, with the DB-API cursor.description interface."
cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % self.connection.ops.quote_name(table_name))
description = []
for desc in cursor.description:
name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3
name = name % {} # cx_Oracle, for some reason, doubles percent signs.
description.append(FieldInfo(*(name.lower(),) + desc[1:]))
return description
def table_name_converter(self, name):
"Table name comparison is case insensitive under Oracle"
return name.lower()
def _name_to_index(self, cursor, table_name):
"""
Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.
"""
return {d[0]: i for i, d in enumerate(self.get_table_description(cursor, table_name))}
def get_relations(self, cursor, table_name):
"""
Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.
"""
table_name = table_name.upper()
cursor.execute("""
SELECT ta.column_id - 1, tb.table_name, tb.column_id - 1
FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
user_tab_cols ta, user_tab_cols tb
WHERE user_constraints.table_name = %s AND
ta.table_name = user_constraints.table_name AND
ta.column_name = ca.column_name AND
ca.table_name = ta.table_name AND
user_constraints.constraint_name = ca.constraint_name AND
user_constraints.r_constraint_name = cb.constraint_name AND
cb.table_name = tb.table_name AND
cb.column_name = tb.column_name AND
ca.position = cb.position""", [table_name])
relations = {}
for row in cursor.fetchall():
relations[row[0]] = (row[2], row[1].lower())
return relations
def get_key_columns(self, cursor, table_name):
cursor.execute("""
SELECT ccol.column_name, rcol.table_name AS referenced_table, rcol.column_name AS referenced_column
FROM user_constraints c
JOIN user_cons_columns ccol
ON ccol.constraint_name = c.constraint_name
JOIN user_cons_columns rcol
ON rcol.constraint_name = c.r_constraint_name
WHERE c.table_name = %s AND c.constraint_type = 'R'""", [table_name.upper()])
return [tuple(cell.lower() for cell in row)
for row in cursor.fetchall()]
def get_indexes(self, cursor, table_name):
sql = """
SELECT LOWER(uic1.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1 ELSE 0
END AS is_primary_key,
CASE user_indexes.uniqueness
WHEN 'UNIQUE' THEN 1 ELSE 0
END AS is_unique
FROM user_constraints, user_indexes, user_ind_columns uic1
WHERE user_constraints.constraint_type (+) = 'P'
AND user_constraints.index_name (+) = uic1.index_name
AND user_indexes.uniqueness (+) = 'UNIQUE'
AND user_indexes.index_name (+) = uic1.index_name
AND uic1.table_name = UPPER(%s)
AND uic1.column_position = 1
AND NOT EXISTS (
SELECT 1
FROM user_ind_columns uic2
WHERE uic2.index_name = uic1.index_name
AND uic2.column_position = 2
)
"""
cursor.execute(sql, [table_name])
indexes = {}
for row in cursor.fetchall():
indexes[row[0]] = {'primary_key': bool(row[1]),
'unique': bool(row[2])}
return indexes
def get_constraints(self, cursor, table_name):
"""
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
"""
constraints = {}
# Loop over the constraints, getting PKs and uniques
cursor.execute("""
SELECT
user_constraints.constraint_name,
LOWER(cols.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1
ELSE 0
END AS is_primary_key,
CASE user_indexes.uniqueness
WHEN 'UNIQUE' THEN 1
ELSE 0
END AS is_unique,
CASE user_constraints.constraint_type
WHEN 'C' THEN 1
ELSE 0
END AS is_check_constraint
FROM
user_constraints
INNER JOIN
user_indexes ON user_indexes.index_name = user_constraints.index_name
LEFT OUTER JOIN
user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name
WHERE
(
user_constraints.constraint_type = 'P' OR
user_constraints.constraint_type = 'U'
)
AND user_constraints.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column, pk, unique, check in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": pk,
"unique": unique,
"foreign_key": None,
"check": check,
"index": True, # All P and U come with index, see inner join above
}
# Record the details
constraints[constraint]['columns'].append(column)
# Check constraints
cursor.execute("""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name
FROM
user_constraints cons
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'C' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": None,
"check": True,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Foreign key constraints
cursor.execute("""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name,
LOWER(rcons.table_name),
LOWER(rcols.column_name)
FROM
user_constraints cons
INNER JOIN
user_constraints rcons ON cons.r_constraint_name = rcons.constraint_name
INNER JOIN
user_cons_columns rcols ON rcols.constraint_name = rcons.constraint_name
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'R' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column, other_table, other_column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": (other_table, other_column),
"check": False,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get indexes
cursor.execute("""
SELECT
index_name,
LOWER(column_name)
FROM
user_ind_columns cols
WHERE
table_name = UPPER(%s) AND
NOT EXISTS (
SELECT 1
FROM user_constraints cons
WHERE cols.index_name = cons.index_name
)
ORDER BY cols.column_position
""", [table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": None,
"check": False,
"index": True,
}
# Record the details
constraints[constraint]['columns'].append(column)
return constraints
| bsd-3-clause |
themass/zulip | zerver/lib/bugdown/codehilite.py | 116 | 8441 | """
CodeHilite Extension for Python-Markdown
========================================
Adds code/syntax highlighting to standard Python-Markdown code blocks.
Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
Project website: <http://packages.python.org/Markdown/extensions/code_hilite.html>
Contact: markdown@freewisdom.org
License: BSD (see ../LICENSE.md for details)
Dependencies:
* [Python 2.3+](http://python.org/)
* [Markdown 2.0+](http://packages.python.org/Markdown/)
* [Pygments](http://pygments.org/)
"""
import markdown
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer
from pygments.formatters import HtmlFormatter
pygments = True
except ImportError:
pygments = False
# ------------------ The Main CodeHilite Class ----------------------
class CodeHilite:
"""
Determine language of source code, and pass it into the pygments hilighter.
Basic Usage:
>>> code = CodeHilite(src = 'some text')
>>> html = code.hilite()
* src: Source string or any object with a .readline attribute.
* force_linenos: (Boolean) Force line numbering 'on' (True) or 'off' (False).
If not specified, number lines iff a shebang line is present.
* guess_lang: (Boolean) Turn language auto-detection 'on' or 'off' (on by default).
* css_class: Set class name of wrapper div ('codehilite' by default).
Low Level Usage:
>>> code = CodeHilite()
>>> code.src = 'some text' # String or anything with a .readline attr.
>>> code.linenos = True # True or False; Turns line numbering on or of.
>>> html = code.hilite()
"""
def __init__(self, src=None, force_linenos=None, guess_lang=True,
css_class="codehilite", lang=None, style='default',
noclasses=False, tab_length=4):
self.src = src
self.lang = lang
self.linenos = force_linenos
self.guess_lang = guess_lang
self.css_class = css_class
self.style = style
self.noclasses = noclasses
self.tab_length = tab_length
def hilite(self):
"""
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
optional line numbers. The output should then be styled with css to
your liking. No styles are applied by default - only styling hooks
(i.e.: <span class="k">).
returns : A string of html.
"""
self.src = self.src.strip('\n')
if self.lang is None:
self._getLang()
if pygments:
try:
lexer = get_lexer_by_name(self.lang)
except ValueError:
try:
if self.guess_lang:
lexer = guess_lexer(self.src)
else:
lexer = TextLexer()
except ValueError:
lexer = TextLexer()
formatter = HtmlFormatter(linenos=bool(self.linenos),
cssclass=self.css_class,
style=self.style,
noclasses=self.noclasses)
return highlight(self.src, lexer, formatter)
else:
# just escape and build markup usable by JS highlighting libs
txt = self.src.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
txt = txt.replace('"', '"')
classes = []
if self.lang:
classes.append('language-%s' % self.lang)
if self.linenos:
classes.append('linenums')
class_str = ''
if classes:
class_str = ' class="%s"' % ' '.join(classes)
return '<pre class="%s"><code%s>%s</code></pre>\n'% \
(self.css_class, class_str, txt)
def _getLang(self):
"""
Determines language of a code block from shebang line and whether said
line should be removed or left in place. If the sheband line contains a
path (even a single /) then it is assumed to be a real shebang line and
left alone. However, if no path is given (e.i.: #!python or :::python)
then it is assumed to be a mock shebang for language identifitation of a
code fragment and removed from the code block prior to processing for
code highlighting. When a mock shebang (e.i: #!python) is found, line
numbering is turned on. When colons are found in place of a shebang
(e.i.: :::python), line numbering is left in the current state - off
by default.
"""
import re
#split text into lines
lines = self.src.split("\n")
#pull first line to examine
fl = lines.pop(0)
c = re.compile(r'''
(?:(?:^::+)|(?P<shebang>^[#]!)) # Shebang or 2 or more colons.
(?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
(?P<lang>[\w+-]*) # The language
''', re.VERBOSE)
# search first line for shebang
m = c.search(fl)
if m:
# we have a match
try:
self.lang = m.group('lang').lower()
except IndexError:
self.lang = None
if m.group('path'):
# path exists - restore first line
lines.insert(0, fl)
if m.group('shebang') and self.linenos is None:
# shebang exists - use line numbers
self.linenos = True
else:
# No match
lines.insert(0, fl)
self.src = "\n".join(lines).strip("\n")
# ------------------ The Markdown Extension -------------------------------
class HiliteTreeprocessor(markdown.treeprocessors.Treeprocessor):
""" Hilight source code in code blocks. """
def run(self, root):
""" Find code blocks and store in htmlStash. """
blocks = root.getiterator('pre')
for block in blocks:
children = block.getchildren()
if len(children) == 1 and children[0].tag == 'code':
code = CodeHilite(children[0].text,
force_linenos=self.config['force_linenos'],
guess_lang=self.config['guess_lang'],
css_class=self.config['css_class'],
style=self.config['pygments_style'],
noclasses=self.config['noclasses'],
tab_length=self.markdown.tab_length)
placeholder = self.markdown.htmlStash.store(code.hilite(),
safe=True)
# Clear codeblock in etree instance
block.clear()
# Change to p element which will later
# be removed when inserting raw html
block.tag = 'p'
block.text = placeholder
class CodeHiliteExtension(markdown.Extension):
""" Add source code hilighting to markdown codeblocks. """
def __init__(self, configs):
# define default configs
self.config = {
'force_linenos' : [None, "Force line numbers - Default: detect based on shebang"],
'guess_lang' : [True, "Automatic language detection - Default: True"],
'css_class' : ["codehilite",
"Set class name for wrapper <div> - Default: codehilite"],
'pygments_style' : ['default', 'Pygments HTML Formatter Style (Colorscheme) - Default: default'],
'noclasses': [False, 'Use inline styles instead of CSS classes - Default false']
}
# Override defaults with user settings
for key, value in configs:
# convert strings to booleans
if value == 'True': value = True
if value == 'False': value = False
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
""" Add HilitePostprocessor to Markdown instance. """
hiliter = HiliteTreeprocessor(md)
hiliter.config = self.getConfigs()
md.treeprocessors.add("hilite", hiliter, "<inline")
md.registerExtension(self)
def makeExtension(configs={}):
return CodeHiliteExtension(configs=configs)
| apache-2.0 |
maniteja123/sympy | sympy/diffgeom/diffgeom.py | 43 | 56771 | from __future__ import print_function, division
from itertools import permutations
from sympy.matrices import Matrix
from sympy.core import Basic, Expr, Dummy, Function, sympify, diff, Pow, Mul, Add, symbols, Tuple
from sympy.core.compatibility import range
from sympy.core.numbers import Zero
from sympy.solvers import solve
from sympy.functions import factorial
from sympy.simplify import simplify
from sympy.core.compatibility import reduce
from sympy.combinatorics import Permutation
# TODO you are a bit excessive in the use of Dummies
# TODO dummy point, literal field
# TODO too often one needs to call doit or simplify on the output, check the
# tests and find out why
class Manifold(Basic):
"""Object representing a mathematical manifold.
The only role that this object plays is to keep a list of all patches
defined on the manifold. It does not provide any means to study the
topological characteristics of the manifold that it represents.
"""
def __new__(cls, name, dim):
name = sympify(name)
dim = sympify(dim)
obj = Basic.__new__(cls, name, dim)
obj.name = name
obj.dim = dim
obj.patches = []
# The patches list is necessary if a Patch instance needs to enumerate
# other Patch instance on the same manifold.
return obj
def _latex(self, printer, *args):
return r'\mathrm{%s}' % self.name
class Patch(Basic):
"""Object representing a patch on a manifold.
On a manifold one can have many patches that do not always include the
whole manifold. On these patches coordinate charts can be defined that
permit the parametrization of any point on the patch in terms of a tuple
of real numbers (the coordinates).
This object serves as a container/parent for all coordinate system charts
that can be defined on the patch it represents.
Examples
========
Define a Manifold and a Patch on that Manifold:
>>> from sympy.diffgeom import Manifold, Patch
>>> m = Manifold('M', 3)
>>> p = Patch('P', m)
>>> p in m.patches
True
"""
# Contains a reference to the parent manifold in order to be able to access
# other patches.
def __new__(cls, name, manifold):
name = sympify(name)
obj = Basic.__new__(cls, name, manifold)
obj.name = name
obj.manifold = manifold
obj.manifold.patches.append(obj)
obj.coord_systems = []
# The list of coordinate systems is necessary for an instance of
# CoordSystem to enumerate other coord systems on the patch.
return obj
@property
def dim(self):
return self.manifold.dim
def _latex(self, printer, *args):
return r'\mathrm{%s}_{%s}' % (self.name, self.manifold._latex(printer, *args))
class CoordSystem(Basic):
"""Contains all coordinate transformation logic.
Examples
========
Define a Manifold and a Patch, and then define two coord systems on that
patch:
>>> from sympy import symbols, sin, cos, pi
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
>>> from sympy.simplify import simplify
>>> r, theta = symbols('r, theta')
>>> m = Manifold('M', 2)
>>> patch = Patch('P', m)
>>> rect = CoordSystem('rect', patch)
>>> polar = CoordSystem('polar', patch)
>>> rect in patch.coord_systems
True
Connect the coordinate systems. An inverse transformation is automatically
found by ``solve`` when possible:
>>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])
>>> polar.coord_tuple_transform_to(rect, [0, 2])
Matrix([
[0],
[0]])
>>> polar.coord_tuple_transform_to(rect, [2, pi/2])
Matrix([
[0],
[2]])
>>> rect.coord_tuple_transform_to(polar, [1, 1]).applyfunc(simplify)
Matrix([
[sqrt(2)],
[ pi/4]])
Calculate the jacobian of the polar to cartesian transformation:
>>> polar.jacobian(rect, [r, theta])
Matrix([
[cos(theta), -r*sin(theta)],
[sin(theta), r*cos(theta)]])
Define a point using coordinates in one of the coordinate systems:
>>> p = polar.point([1, 3*pi/4])
>>> rect.point_to_coords(p)
Matrix([
[-sqrt(2)/2],
[ sqrt(2)/2]])
Define a basis scalar field (i.e. a coordinate function), that takes a
point and returns its coordinates. It is an instance of ``BaseScalarField``.
>>> rect.coord_function(0)(p)
-sqrt(2)/2
>>> rect.coord_function(1)(p)
sqrt(2)/2
Define a basis vector field (i.e. a unit vector field along the coordinate
line). Vectors are also differential operators on scalar fields. It is an
instance of ``BaseVectorField``.
>>> v_x = rect.base_vector(0)
>>> x = rect.coord_function(0)
>>> v_x(x)
1
>>> v_x(v_x(x))
0
Define a basis oneform field:
>>> dx = rect.base_oneform(0)
>>> dx(v_x)
1
If you provide a list of names the fields will print nicely:
- without provided names:
>>> x, v_x, dx
(rect_0, e_rect_0, drect_0)
- with provided names
>>> rect = CoordSystem('rect', patch, ['x', 'y'])
>>> rect.coord_function(0), rect.base_vector(0), rect.base_oneform(0)
(x, e_x, dx)
"""
# Contains a reference to the parent patch in order to be able to access
# other coordinate system charts.
def __new__(cls, name, patch, names=None):
name = sympify(name)
# names is not in args because it is related only to printing, not to
# identifying the CoordSystem instance.
if not names:
names = ['%s_%d' % (name, i) for i in range(patch.dim)]
if isinstance(names, Tuple):
obj = Basic.__new__(cls, name, patch, names)
else:
names = Tuple(*symbols(names))
obj = Basic.__new__(cls, name, patch, names)
obj.name = name
obj._names = [str(i) for i in names.args]
obj.patch = patch
obj.patch.coord_systems.append(obj)
obj.transforms = {}
# All the coordinate transformation logic is in this dictionary in the
# form of:
# key = other coordinate system
# value = tuple of # TODO make these Lambda instances
# - list of `Dummy` coordinates in this coordinate system
# - list of expressions as a function of the Dummies giving
# the coordinates in another coordinate system
obj._dummies = [Dummy(str(n)) for n in names]
obj._dummy = Dummy()
return obj
@property
def dim(self):
return self.patch.dim
##########################################################################
# Coordinate transformations.
##########################################################################
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
"""Register the transformation used to switch to another coordinate system.
Parameters
==========
to_sys
another instance of ``CoordSystem``
from_coords
list of symbols in terms of which ``to_exprs`` is given
to_exprs
list of the expressions of the new coordinate tuple
inverse
try to deduce and register the inverse transformation
fill_in_gaps
try to deduce other transformation that are made
possible by composing the present transformation with other already
registered transformation
"""
from_coords, to_exprs = dummyfy(from_coords, to_exprs)
self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
if inverse:
to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
if fill_in_gaps:
self._fill_gaps_in_transformations()
@staticmethod
def _inv_transf(from_coords, to_exprs):
# TODO, check for results, get solve to return results in definite
# format instead of wondering dict/tuple/whatever.
# As it is at the moment this is an ugly hack for changing the format
inv_from = [i.as_dummy() for i in from_coords]
inv_to = solve(
[t[0] - t[1] for t in zip(inv_from, to_exprs)], list(from_coords))
if isinstance(inv_to, dict):
inv_to = [inv_to[fc] for fc in from_coords]
else:
inv_to = inv_to[0]
return Matrix(inv_from), Matrix(inv_to)
@staticmethod
def _fill_gaps_in_transformations():
raise NotImplementedError
# TODO
def coord_tuple_transform_to(self, to_sys, coords):
"""Transform ``coords`` to coord system ``to_sys``.
See the docstring of ``CoordSystem`` for examples."""
coords = Matrix(coords)
if self != to_sys:
transf = self.transforms[to_sys]
coords = transf[1].subs(list(zip(transf[0], coords)))
return coords
def jacobian(self, to_sys, coords):
"""Return the jacobian matrix of a transformation."""
with_dummies = self.coord_tuple_transform_to(
to_sys, self._dummies).jacobian(self._dummies)
return with_dummies.subs(list(zip(self._dummies, coords)))
##########################################################################
# Base fields.
##########################################################################
def coord_function(self, coord_index):
"""Return a ``BaseScalarField`` that takes a point and returns one of the coords.
Takes a point and returns its coordinate in this coordinate system.
See the docstring of ``CoordSystem`` for examples."""
return BaseScalarField(self, coord_index)
def coord_functions(self):
"""Returns a list of all coordinate functions.
For more details see the ``coord_function`` method of this class."""
return [self.coord_function(i) for i in range(self.dim)]
def base_vector(self, coord_index):
"""Return a basis vector field.
The basis vector field for this coordinate system. It is also an
operator on scalar fields.
See the docstring of ``CoordSystem`` for examples."""
return BaseVectorField(self, coord_index)
def base_vectors(self):
"""Returns a list of all base vectors.
For more details see the ``base_vector`` method of this class."""
return [self.base_vector(i) for i in range(self.dim)]
def base_oneform(self, coord_index):
"""Return a basis 1-form field.
The basis one-form field for this coordinate system. It is also an
operator on vector fields.
See the docstring of ``CoordSystem`` for examples."""
return Differential(self.coord_function(coord_index))
def base_oneforms(self):
"""Returns a list of all base oneforms.
For more details see the ``base_oneform`` method of this class."""
return [self.base_oneform(i) for i in range(self.dim)]
##########################################################################
# Points.
##########################################################################
def point(self, coords):
"""Create a ``Point`` with coordinates given in this coord system.
See the docstring of ``CoordSystem`` for examples."""
return Point(self, coords)
def point_to_coords(self, point):
"""Calculate the coordinates of a point in this coord system.
See the docstring of ``CoordSystem`` for examples."""
return point.coords(self)
##########################################################################
# Printing.
##########################################################################
def _latex(self, printer, *args):
return r'\mathrm{%s}^{\mathrm{%s}}_{%s}' % (
self.name, self.patch.name, self.patch.manifold._latex(printer, *args))
class Point(Basic):
"""Point in a Manifold object.
To define a point you must supply coordinates and a coordinate system.
The usage of this object after its definition is independent of the
coordinate system that was used in order to define it, however due to
limitations in the simplification routines you can arrive at complicated
expressions if you use inappropriate coordinate systems.
Examples
========
Define the boilerplate Manifold, Patch and coordinate systems:
>>> from sympy import symbols, sin, cos, pi
>>> from sympy.diffgeom import (
... Manifold, Patch, CoordSystem, Point)
>>> r, theta = symbols('r, theta')
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> rect = CoordSystem('rect', p)
>>> polar = CoordSystem('polar', p)
>>> polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)])
Define a point using coordinates from one of the coordinate systems:
>>> p = Point(polar, [r, 3*pi/4])
>>> p.coords()
Matrix([
[ r],
[3*pi/4]])
>>> p.coords(rect)
Matrix([
[-sqrt(2)*r/2],
[ sqrt(2)*r/2]])
"""
def __init__(self, coord_sys, coords):
super(Point, self).__init__()
self._coord_sys = coord_sys
self._coords = Matrix(coords)
self._args = self._coord_sys, self._coords
def coords(self, to_sys=None):
"""Coordinates of the point in a given coordinate system.
If ``to_sys`` is ``None`` it returns the coordinates in the system in
which the point was defined."""
if to_sys:
return self._coord_sys.coord_tuple_transform_to(to_sys, self._coords)
else:
return self._coords
@property
def free_symbols(self):
raise NotImplementedError
return self._coords.free_symbols
class BaseScalarField(Expr):
"""Base Scalar Field over a Manifold for a given Coordinate System.
A scalar field takes a point as an argument and returns a scalar.
A base scalar field of a coordinate system takes a point and returns one of
the coordinates of that point in the coordinate system in question.
To define a scalar field you need to choose the coordinate system and the
index of the coordinate.
The use of the scalar field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in
the simplification routines you may arrive at more complicated
expression if you use unappropriate coordinate systems.
You can build complicated scalar fields by just building up SymPy
expressions containing ``BaseScalarField`` instances.
Examples
========
Define boilerplate Manifold, Patch and coordinate systems:
>>> from sympy import symbols, sin, cos, pi, Function
>>> from sympy.diffgeom import (
... Manifold, Patch, CoordSystem, Point, BaseScalarField)
>>> r0, theta0 = symbols('r0, theta0')
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> rect = CoordSystem('rect', p)
>>> polar = CoordSystem('polar', p)
>>> polar.connect_to(rect, [r0, theta0], [r0*cos(theta0), r0*sin(theta0)])
Point to be used as an argument for the filed:
>>> point = polar.point([r0, 0])
Examples of fields:
>>> fx = BaseScalarField(rect, 0)
>>> fy = BaseScalarField(rect, 1)
>>> (fx**2+fy**2).rcall(point)
r0**2
>>> g = Function('g')
>>> ftheta = BaseScalarField(polar, 1)
>>> fg = g(ftheta-pi)
>>> fg.rcall(point)
g(-pi)
"""
is_commutative = True
def __new__(cls, coord_sys, index):
obj = Expr.__new__(cls, coord_sys, sympify(index))
obj._coord_sys = coord_sys
obj._index = index
return obj
def __call__(self, *args):
"""Evaluating the field at a point or doing nothing.
If the argument is a ``Point`` instance, the field is evaluated at that
point. The field is returned itself if the argument is any other
object. It is so in order to have working recursive calling mechanics
for all fields (check the ``__call__`` method of ``Expr``).
"""
point = args[0]
if len(args) != 1 or not isinstance(point, Point):
return self
coords = point.coords(self._coord_sys)
# XXX Calling doit is necessary with all the Subs expressions
# XXX Calling simplify is necessary with all the trig expressions
return simplify(coords[self._index]).doit()
# XXX Workaround for limitations on the content of args
free_symbols = set()
def doit(self):
return self
class BaseVectorField(Expr):
r"""Vector Field over a Manifold.
A vector field is an operator taking a scalar field and returning a
directional derivative (which is also a scalar field).
A base vector field is the same type of operator, however the derivation is
specifically done with respect to a chosen coordinate.
To define a base vector field you need to choose the coordinate system and
the index of the coordinate.
The use of the vector field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in the
simplification routines you may arrive at more complicated expression if you
use unappropriate coordinate systems.
Examples
========
Use the predefined R2 manifold, setup some boilerplate.
>>> from sympy import symbols, pi, Function
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
>>> from sympy.diffgeom import BaseVectorField
>>> from sympy import pprint
>>> x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0')
Points to be used as arguments for the field:
>>> point_p = R2_p.point([r0, theta0])
>>> point_r = R2_r.point([x0, y0])
Scalar field to operate on:
>>> g = Function('g')
>>> s_field = g(R2.x, R2.y)
>>> s_field.rcall(point_r)
g(x0, y0)
>>> s_field.rcall(point_p)
g(r0*cos(theta0), r0*sin(theta0))
Vector field:
>>> v = BaseVectorField(R2_r, 1)
>>> pprint(v(s_field))
/ d \|
|-----(g(x, xi_2))||
\dxi_2 /|xi_2=y
>>> pprint(v(s_field).rcall(point_r).doit())
d
---(g(x0, y0))
dy0
>>> pprint(v(s_field).rcall(point_p).doit())
/ d \|
|-----(g(r0*cos(theta0), xi_2))||
\dxi_2 /|xi_2=r0*sin(theta0)
"""
is_commutative = False
def __new__(cls, coord_sys, index):
index = sympify(index)
obj = Expr.__new__(cls, coord_sys, index)
obj._coord_sys = coord_sys
obj._index = index
return obj
def __call__(self, scalar_field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field an error is raised.
"""
if covariant_order(scalar_field) or contravariant_order(scalar_field):
raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
base_scalars = list(scalar_field.atoms(BaseScalarField))
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
d_var = self._coord_sys._dummy
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(d_var) for i,
b in enumerate(base_scalars)]
d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
d_result = d_result.diff(d_var)
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
coords = self._coord_sys._dummies
d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
d_funcs_deriv_sub = []
for b in base_scalars:
jac = self._coord_sys.jacobian(b._coord_sys, coords)
d_funcs_deriv_sub.append(jac[b._index, self._index])
d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
# Remove the dummies
result = d_result.subs(list(zip(d_funcs, base_scalars)))
result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
return result.doit() # XXX doit for the Subs instances
class Commutator(Expr):
r"""Commutator of two vector fields.
The commutator of two vector fields `v_1` and `v_2` is defined as the
vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
to `v_1(v_2(f)) - v_2(v_1(f))`.
Examples
========
Use the predefined R2 manifold, setup some boilerplate.
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import Commutator
>>> from sympy import pprint
>>> from sympy.simplify import simplify
Vector fields:
>>> e_x, e_y, e_r = R2.e_x, R2.e_y, R2.e_r
>>> c_xy = Commutator(e_x, e_y)
>>> c_xr = Commutator(e_x, e_r)
>>> c_xy
0
Unfortunately, the current code is not able to compute everything:
>>> c_xr
Commutator(e_x, e_r)
>>> simplify(c_xr(R2.y**2).doit())
-2*cos(theta)*y**2/(x**2 + y**2)
"""
def __new__(cls, v1, v2):
if (covariant_order(v1) or contravariant_order(v1) != 1
or covariant_order(v2) or contravariant_order(v2) != 1):
raise ValueError(
'Only commutators of vector fields are supported.')
if v1 == v2:
return Zero()
coord_sys = set().union(*[v.atoms(CoordSystem) for v in (v1, v2)])
if len(coord_sys) == 1:
# Only one coordinate systems is used, hence it is easy enough to
# actually evaluate the commutator.
if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
return Zero()
bases_1, bases_2 = [list(v.atoms(BaseVectorField))
for v in (v1, v2)]
coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
res = 0
for c1, b1 in zip(coeffs_1, bases_1):
for c2, b2 in zip(coeffs_2, bases_2):
res += c1*b1(c2)*b2 - c2*b2(c1)*b1
return res
else:
return super(Commutator, cls).__new__(cls, v1, v2)
def __init__(self, v1, v2):
super(Commutator, self).__init__()
self._args = (v1, v2)
self._v1 = v1
self._v2 = v2
def __call__(self, scalar_field):
"""Apply on a scalar field.
If the argument is not a scalar field an error is raised.
"""
return self._v1(self._v2(scalar_field)) - self._v2(self._v1(scalar_field))
class Differential(Expr):
"""Return the differential (exterior derivative) of a form field.
The differential of a form (i.e. the exterior derivative) has a complicated
definition in the general case.
The differential `df` of the 0-form `f` is defined for any vector field `v`
as `df(v) = v(f)`.
Examples
========
Use the predefined R2 manifold, setup some boilerplate.
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import Differential
>>> from sympy import pprint
Scalar field (0-forms):
>>> g = Function('g')
>>> s_field = g(R2.x, R2.y)
Vector fields:
>>> e_x, e_y, = R2.e_x, R2.e_y
Differentials:
>>> dg = Differential(s_field)
>>> dg
d(g(x, y))
>>> pprint(dg(e_x))
/ d \|
|-----(g(xi_1, y))||
\dxi_1 /|xi_1=x
>>> pprint(dg(e_y))
/ d \|
|-----(g(x, xi_2))||
\dxi_2 /|xi_2=y
Applying the exterior derivative operator twice always results in:
>>> Differential(dg)
0
"""
is_commutative = False
def __new__(cls, form_field):
if contravariant_order(form_field):
raise ValueError(
'A vector field was supplied as an argument to Differential.')
if isinstance(form_field, Differential):
return Zero()
else:
return super(Differential, cls).__new__(cls, form_field)
def __init__(self, form_field):
super(Differential, self).__init__()
self._form_field = form_field
self._args = (self._form_field, )
def __call__(self, *vector_fields):
"""Apply on a list of vector_fields.
If the number of vector fields supplied is not equal to 1 + the order of
the form field inside the differential the result is undefined.
For 1-forms (i.e. differentials of scalar fields) the evaluation is
done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
field, the differential is returned unchanged. This is done in order to
permit partial contractions for higher forms.
In the general case the evaluation is done by applying the form field
inside the differential on a list with one less elements than the number
of elements in the original list. Lowering the number of vector fields
is achieved through replacing each pair of fields by their
commutator.
If the arguments are not vectors or ``None``s an error is raised.
"""
if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
for a in vector_fields):
raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
k = len(vector_fields)
if k == 1:
if vector_fields[0]:
return vector_fields[0].rcall(self._form_field)
return self
else:
# For higher form it is more complicated:
# Invariant formula:
# http://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
# df(v1, ... vn) = +/- vi(f(v1..no i..vn))
# +/- f([vi,vj],v1..no i, no j..vn)
f = self._form_field
v = vector_fields
ret = 0
for i in range(k):
t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
ret += (-1)**i*t
for j in range(i + 1, k):
c = Commutator(v[i], v[j])
if c: # TODO this is ugly - the Commutator can be Zero and
# this causes the next line to fail
t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
ret += (-1)**(i + j)*t
return ret
class TensorProduct(Expr):
"""Tensor product of forms.
The tensor product permits the creation of multilinear functionals (i.e.
higher order tensors) out of lower order forms (e.g. 1-forms). However, the
higher tensors thus created lack the interesting features provided by the
other type of product, the wedge product, namely they are not antisymmetric
and hence are not form fields.
Examples
========
Use the predefined R2 manifold, setup some boilerplate.
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import TensorProduct
>>> from sympy import pprint
>>> TensorProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y)
1
>>> TensorProduct(R2.dx, R2.dy)(R2.e_y, R2.e_x)
0
>>> TensorProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)
x**2
You can nest tensor products.
>>> tp1 = TensorProduct(R2.dx, R2.dy)
>>> TensorProduct(tp1, R2.dx)(R2.e_x, R2.e_y, R2.e_x)
1
You can make partial contraction for instance when 'raising an index'.
Putting ``None`` in the second argument of ``rcall`` means that the
respective position in the tensor product is left as it is.
>>> TP = TensorProduct
>>> metric = TP(R2.dx, R2.dx) + 3*TP(R2.dy, R2.dy)
>>> metric.rcall(R2.e_y, None)
3*dy
Or automatically pad the args with ``None`` without specifying them.
>>> metric.rcall(R2.e_y)
3*dy
"""
def __new__(cls, *args):
if any(contravariant_order(a) for a in args):
raise ValueError('A vector field was supplied as an argument to TensorProduct.')
scalar = Mul(*[m for m in args if covariant_order(m) == 0])
forms = [m for m in args if covariant_order(m)]
if forms:
if len(forms) == 1:
return scalar*forms[0]
return scalar*super(TensorProduct, cls).__new__(cls, *forms)
else:
return scalar
def __init__(self, *args):
super(TensorProduct, self).__init__()
self._args = args
def __call__(self, *v_fields):
"""Apply on a list of vector_fields.
If the number of vector fields supplied is not equal to the order of
the form field the list of arguments is padded with ``None``'s.
The list of arguments is divided in sublists depending on the order of
the forms inside the tensor product. The sublists are provided as
arguments to these forms and the resulting expressions are given to the
constructor of ``TensorProduct``.
"""
tot_order = covariant_order(self)
tot_args = len(v_fields)
if tot_args != tot_order:
v_fields = list(v_fields) + [None]*(tot_order - tot_args)
orders = [covariant_order(f) for f in self._args]
indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
v_fields = [v_fields[i:j] for i, j in zip([0] + indices, indices + [None])]
multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, v_fields)]
return TensorProduct(*multipliers)
def _latex(self, printer, *args):
elements = [printer._print(a) for a in self.args]
return r'\otimes'.join(elements)
class WedgeProduct(TensorProduct):
"""Wedge product of forms.
In the context of integration only completely antisymmetric forms make
sense. The wedge product permits the creation of such forms.
Examples
========
Use the predefined R2 manifold, setup some boilerplate.
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import WedgeProduct
>>> from sympy import pprint
>>> WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y)
1
>>> WedgeProduct(R2.dx, R2.dy)(R2.e_y, R2.e_x)
-1
>>> WedgeProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)
x**2
You can nest wedge products.
>>> wp1 = WedgeProduct(R2.dx, R2.dy)
>>> WedgeProduct(wp1, R2.dx)(R2.e_x, R2.e_y, R2.e_x)
0
"""
# TODO the calculation of signatures is slow
# TODO you do not need all these permutations (neither the prefactor)
def __call__(self, *vector_fields):
"""Apply on a list of vector_fields.
The expression is rewritten internally in terms of tensor products and evaluated."""
orders = (covariant_order(e) for e in self.args)
mul = 1/Mul(*(factorial(o) for o in orders))
perms = permutations(vector_fields)
perms_par = (Permutation(
p).signature() for p in permutations(list(range(len(vector_fields)))))
tensor_prod = TensorProduct(*self.args)
return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
class LieDerivative(Expr):
"""Lie derivative with respect to a vector field.
The transport operator that defines the Lie derivative is the pushforward of
the field to be derived along the integral curve of the field with respect
to which one derives.
Examples
========
>>> from sympy.diffgeom import (LieDerivative, TensorProduct)
>>> from sympy.diffgeom.rn import R2
>>> LieDerivative(R2.e_x, R2.y)
0
>>> LieDerivative(R2.e_x, R2.x)
1
>>> LieDerivative(R2.e_x, R2.e_x)
0
The Lie derivative of a tensor field by another tensor field is equal to
their commutator:
>>> LieDerivative(R2.e_x, R2.e_r)
Commutator(e_x, e_r)
>>> LieDerivative(R2.e_x + R2.e_y, R2.x)
1
>>> tp = TensorProduct(R2.dx, R2.dy)
>>> LieDerivative(R2.e_x, tp)
LieDerivative(e_x, TensorProduct(dx, dy))
>>> LieDerivative(R2.e_x, tp).doit()
LieDerivative(e_x, TensorProduct(dx, dy))
"""
def __new__(cls, v_field, expr):
expr_form_ord = covariant_order(expr)
if contravariant_order(v_field) != 1 or covariant_order(v_field):
raise ValueError('Lie derivatives are defined only with respect to'
' vector fields. The supplied argument was not a '
'vector field.')
if expr_form_ord > 0:
return super(LieDerivative, cls).__new__(cls, v_field, expr)
if expr.atoms(BaseVectorField):
return Commutator(v_field, expr)
else:
return v_field.rcall(expr)
def __init__(self, v_field, expr):
super(LieDerivative, self).__init__()
self._v_field = v_field
self._expr = expr
self._args = (self._v_field, self._expr)
def __call__(self, *args):
v = self._v_field
expr = self._expr
lead_term = v(expr(*args))
rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
for i in range(len(args))])
return lead_term - rest
class BaseCovarDerivativeOp(Expr):
"""Covariant derivative operator with respect to a base vector.
Examples
========
>>> from sympy.diffgeom.rn import R2, R2_r
>>> from sympy.diffgeom import BaseCovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
>>> ch
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
>>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
>>> cvd(R2.x)
1
>>> cvd(R2.x*R2.e_x)
e_x
"""
def __init__(self, coord_sys, index, christoffel):
super(BaseCovarDerivativeOp, self).__init__()
self._coord_sys = coord_sys
self._index = index
self._christoffel = christoffel
self._args = self._coord_sys, self._index, self._christoffel
def __call__(self, field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field the behaviour is undefined.
"""
if covariant_order(field) != 0:
raise NotImplementedError()
field = vectors_in_basis(field, self._coord_sys)
wrt_vector = self._coord_sys.base_vector(self._index)
wrt_scalar = self._coord_sys.coord_function(self._index)
vectors = list(field.atoms(BaseVectorField))
# First step: replace all vectors with something susceptible to
# derivation and do the derivation
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
b in enumerate(vectors)]
d_result = field.subs(list(zip(vectors, d_funcs)))
d_result = wrt_vector(d_result)
# Second step: backsubstitute the vectors in
d_result = d_result.subs(list(zip(d_funcs, vectors)))
# Third step: evaluate the derivatives of the vectors
derivs = []
for v in vectors:
d = Add(*[(self._christoffel[k][wrt_vector._index][v._index]
*v._coord_sys.base_vector(k))
for k in range(v._coord_sys.dim)])
derivs.append(d)
to_subs = [wrt_vector(d) for d in d_funcs]
result = d_result.subs(list(zip(to_subs, derivs)))
return result # TODO .doit() # XXX doit for the Subs instances
class CovarDerivativeOp(Expr):
"""Covariant derivative operator.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import CovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
>>> ch
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
>>> cvd = CovarDerivativeOp(R2.x*R2.e_x, ch)
>>> cvd(R2.x)
x
>>> cvd(R2.x*R2.e_x)
x*e_x
"""
def __init__(self, wrt, christoffel):
super(CovarDerivativeOp, self).__init__()
if len(set(v._coord_sys for v in wrt.atoms(BaseVectorField))) > 1:
raise NotImplementedError()
if contravariant_order(wrt) != 1 or covariant_order(wrt):
raise ValueError('Covariant derivatives are defined only with '
'respect to vector fields. The supplied argument '
'was not a vector field.')
self._wrt = wrt
self._christoffel = christoffel
self._args = self._wrt, self._christoffel
def __call__(self, field):
vectors = list(self._wrt.atoms(BaseVectorField))
base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
for v in vectors]
return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
def _latex(self, printer, *args):
return r'\mathbb{\nabla}_{%s}' % printer._print(self._wrt)
###############################################################################
# Integral curves on vector fields
###############################################################################
def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
r"""Return the series expansion for an integral curve of the field.
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This equation can also be decomposed of a basis of coordinate functions
`V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
This function returns a series expansion of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
See Also
========
intcurve_diffequ
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which coresponds to `\gamma(0)`
n
the order to which to expand
coord_sys
the coordinate system in which to expand
coeffs (default False) - if True return a list of elements of the expansion
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t, x, y
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
>>> from sympy.diffgeom import intcurve_series
Specify a starting point and a vector field:
>>> start_point = R2_r.point([x, y])
>>> vector_field = R2_r.e_x
Calculate the series:
>>> intcurve_series(vector_field, t, start_point, n=3)
Matrix([
[t + x],
[ y]])
Or get the elements of the expansion in a list:
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
>>> series[0]
Matrix([
[x],
[y]])
>>> series[1]
Matrix([
[t],
[0]])
>>> series[2]
Matrix([
[0],
[0]])
The series in the polar coordinate system:
>>> series = intcurve_series(vector_field, t, start_point,
... n=3, coord_sys=R2_p, coeffs=True)
>>> series[0]
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> series[1]
Matrix([
[t*x/sqrt(x**2 + y**2)],
[ -t*y/(x**2 + y**2)]])
>>> series[2]
Matrix([
[t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
[ t**2*x*y/(x**2 + y**2)**2]])
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
def iter_vfield(scalar_field, i):
"""Return ``vector_field`` called `i` times on ``scalar_field``."""
return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
def taylor_terms_per_coord(coord_function):
"""Return the series for one of the coordinates."""
return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
for i in range(n)]
coord_sys = coord_sys if coord_sys else start_point._coord_sys
coord_functions = coord_sys.coord_functions()
taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
if coeffs:
return [Matrix(t) for t in zip(*taylor_terms)]
else:
return Matrix([sum(c) for c in taylor_terms])
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
r"""Return the differential equation for an integral curve of the field.
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This function returns the differential equation of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
See Also
========
intcurve_series
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which coresponds to `\gamma(0)`
coord_sys
the coordinate system in which to give the equations
Returns
=======
a tuple of (equations, initial conditions)
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
>>> from sympy.diffgeom import intcurve_diffequ
Specify a starting point and a vector field:
>>> start_point = R2_r.point([0, 1])
>>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
Get the equation:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
>>> equations
[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
>>> init_cond
[f_0(0), f_1(0) - 1]
The series in the polar coordinate system:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
>>> equations
[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
>>> init_cond
[f_0(0) - 1, f_1(0) - pi/2]
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
coord_sys = coord_sys if coord_sys else start_point._coord_sys
gammas = [Function('f_%d' % i)(param) for i in range(
start_point._coord_sys.dim)]
arbitrary_p = Point(coord_sys, gammas)
coord_functions = coord_sys.coord_functions()
equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
for cf in coord_functions]
init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
for cf in coord_functions]
return equations, init_cond
###############################################################################
# Helpers
###############################################################################
def dummyfy(args, exprs):
# TODO Is this a good idea?
d_args = Matrix([s.as_dummy() for s in args])
d_exprs = Matrix([sympify(expr).subs(list(zip(args, d_args))) for expr in exprs])
return d_args, d_exprs
def list_to_tuple_rec(the_list):
# TODO remove in favor of tensor classes
if isinstance(the_list, list):
return tuple(list_to_tuple_rec(e) for e in the_list)
return the_list
###############################################################################
# Helpers
###############################################################################
def contravariant_order(expr, _strict=False):
"""Return the contravariant order of an expression.
Examples
========
>>> from sympy.diffgeom import contravariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> contravariant_order(a)
0
>>> contravariant_order(a*R2.x + 2)
0
>>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [contravariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing contravariant fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [contravariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between vectors.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a vector.')
return 0
elif isinstance(expr, BaseVectorField):
return 1
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
def covariant_order(expr, _strict=False):
"""Return the covariant order of an expression.
Examples
========
>>> from sympy.diffgeom import covariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> covariant_order(a)
0
>>> covariant_order(a*R2.x + 2)
0
>>> covariant_order(a*R2.x*R2.dy + R2.dx)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [covariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing form fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [covariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between forms.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a form.')
return 0
elif isinstance(expr, Differential):
return covariant_order(*expr.args) + 1
elif isinstance(expr, TensorProduct):
return sum(covariant_order(a) for a in expr.args)
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
###############################################################################
# Coordinate transformation functions
###############################################################################
def vectors_in_basis(expr, to_sys):
"""Transform all base vectors in base vectors of a specified coord basis.
While the new base vectors are in the new coordinate system basis, any
coefficients are kept in the old system.
Examples
========
>>> from sympy.diffgeom import vectors_in_basis
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> vectors_in_basis(R2_r.e_x, R2_p)
-y*e_theta/(x**2 + y**2) + x*e_r/sqrt(x**2 + y**2)
>>> vectors_in_basis(R2_p.e_r, R2_r)
sin(theta)*e_y + cos(theta)*e_x
"""
vectors = list(expr.atoms(BaseVectorField))
new_vectors = []
for v in vectors:
cs = v._coord_sys
jac = cs.jacobian(to_sys, cs.coord_functions())
new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
new_vectors.append(new)
return expr.subs(list(zip(vectors, new_vectors)))
###############################################################################
# Coordinate-dependent functions
###############################################################################
def twoform_to_matrix(expr):
"""Return the matrix representing the twoform.
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
where `e_i` is the i-th base vector field for the coordinate system in
which the expression of `w` is given.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
>>> TP = TensorProduct
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[1, 0],
[0, 1]])
>>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[x, 0],
[0, 1]])
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
Matrix([
[ 1, 0],
[-1/2, 1]])
"""
if covariant_order(expr) != 2 or contravariant_order(expr):
raise ValueError('The input expression is not a two-form.')
coord_sys = expr.atoms(CoordSystem)
if len(coord_sys) != 1:
raise ValueError('The input expression concerns more than one '
'coordinate systems, hence there is no unambiguous '
'way to choose a coordinate system for the matrix.')
coord_sys = coord_sys.pop()
vectors = coord_sys.base_vectors()
expr = expr.expand()
matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
for v2 in vectors]
return Matrix(matrix_content)
def metric_to_Christoffel_1st(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of first kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
>>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
(((1/2, 0), (0, 0)), ((0, 0), (0, 0)))
"""
matrix = twoform_to_matrix(expr)
if not matrix.is_symmetric():
raise ValueError(
'The two-form representing the metric is not symmetric.')
coord_sys = expr.atoms(CoordSystem).pop()
deriv_matrices = [matrix.applyfunc(lambda a: d(a))
for d in coord_sys.base_vectors()]
indices = list(range(coord_sys.dim))
christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
for k in indices]
for j in indices]
for i in indices]
return list_to_tuple_rec(christoffel)
def metric_to_Christoffel_2nd(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of second kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
>>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
(((1/(2*x), 0), (0, 0)), ((0, 0), (0, 0)))
"""
ch_1st = metric_to_Christoffel_1st(expr)
coord_sys = expr.atoms(CoordSystem).pop()
indices = list(range(coord_sys.dim))
# XXX workaround, inverting a matrix does not work if it contains non
# symbols
#matrix = twoform_to_matrix(expr).inv()
matrix = twoform_to_matrix(expr)
s_fields = set()
for e in matrix:
s_fields.update(e.atoms(BaseScalarField))
s_fields = list(s_fields)
dums = coord_sys._dummies
matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
# XXX end of workaround
christoffel = [[[Add(*[matrix[i, l]*ch_1st[l][j][k] for l in indices])
for k in indices]
for j in indices]
for i in indices]
return list_to_tuple_rec(christoffel)
def metric_to_Riemann_components(expr):
"""Return the components of the Riemann tensor expressed in a given basis.
Given a metric it calculates the components of the Riemann tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import pprint, exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
((((0, 0), (0, 0)), ((0, 0), (0, 0))), (((0, 0), (0, 0)), ((0, 0),
(0, 0))))
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*r)*TensorProduct(dr, dr) + r**2*TensorProduct(dtheta, dtheta)
>>> riemann = metric_to_Riemann_components(non_trivial_metric)
>>> riemann[0]
(((0, 0), (0, 0)), ((0, exp(-2*r)*r), (-exp(-2*r)*r, 0)))
>>> riemann[1]
(((0, -1/r), (1/r, 0)), ((0, 0), (0, 0)))
"""
ch_2nd = metric_to_Christoffel_2nd(expr)
coord_sys = expr.atoms(CoordSystem).pop()
indices = list(range(coord_sys.dim))
deriv_ch = [[[[d(ch_2nd[i][j][k])
for d in coord_sys.base_vectors()]
for k in indices]
for j in indices]
for i in indices]
riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann_b = [[[[Add(*[ch_2nd[rho][l][mu]*ch_2nd[l][sig][nu] - ch_2nd[rho][l][nu]*ch_2nd[l][sig][mu] for l in indices])
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
return list_to_tuple_rec(riemann)
def metric_to_Ricci_components(expr):
"""Return the components of the Ricci tensor expressed in a given basis.
Given a metric it calculates the components of the Ricci tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import pprint, exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
((0, 0), (0, 0))
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*r)*TensorProduct(dr, dr) + r**2*TensorProduct(dtheta, dtheta)
>>> metric_to_Ricci_components(non_trivial_metric)
((1/r, 0), (0, exp(-2*r)*r))
"""
riemann = metric_to_Riemann_components(expr)
coord_sys = expr.atoms(CoordSystem).pop()
indices = list(range(coord_sys.dim))
ricci = [[Add(*[riemann[k][i][k][j] for k in indices])
for j in indices]
for i in indices]
return list_to_tuple_rec(ricci)
| bsd-3-clause |
dominicelse/scipy | scipy/sparse/spfuncs.py | 149 | 2823 | """ Functions that operate on sparse matrices
"""
from __future__ import division, print_function, absolute_import
__all__ = ['count_blocks','estimate_blocksize']
from .csr import isspmatrix_csr, csr_matrix
from .csc import isspmatrix_csc
from ._sparsetools import csr_count_blocks
def extract_diagonal(A):
raise NotImplementedError('use .diagonal() instead')
#def extract_diagonal(A):
# """extract_diagonal(A) returns the main diagonal of A."""
# #TODO extract k-th diagonal
# if isspmatrix_csr(A) or isspmatrix_csc(A):
# fn = getattr(sparsetools, A.format + "_diagonal")
# y = empty( min(A.shape), dtype=upcast(A.dtype) )
# fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y)
# return y
# elif isspmatrix_bsr(A):
# M,N = A.shape
# R,C = A.blocksize
# y = empty( min(M,N), dtype=upcast(A.dtype) )
# fn = sparsetools.bsr_diagonal(M//R, N//C, R, C, \
# A.indptr, A.indices, ravel(A.data), y)
# return y
# else:
# return extract_diagonal(csr_matrix(A))
def estimate_blocksize(A,efficiency=0.7):
"""Attempt to determine the blocksize of a sparse matrix
Returns a blocksize=(r,c) such that
- A.nnz / A.tobsr( (r,c) ).nnz > efficiency
"""
if not (isspmatrix_csr(A) or isspmatrix_csc(A)):
A = csr_matrix(A)
if A.nnz == 0:
return (1,1)
if not 0 < efficiency < 1.0:
raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0')
high_efficiency = (1.0 + efficiency) / 2.0
nnz = float(A.nnz)
M,N = A.shape
if M % 2 == 0 and N % 2 == 0:
e22 = nnz / (4 * count_blocks(A,(2,2)))
else:
e22 = 0.0
if M % 3 == 0 and N % 3 == 0:
e33 = nnz / (9 * count_blocks(A,(3,3)))
else:
e33 = 0.0
if e22 > high_efficiency and e33 > high_efficiency:
e66 = nnz / (36 * count_blocks(A,(6,6)))
if e66 > efficiency:
return (6,6)
else:
return (3,3)
else:
if M % 4 == 0 and N % 4 == 0:
e44 = nnz / (16 * count_blocks(A,(4,4)))
else:
e44 = 0.0
if e44 > efficiency:
return (4,4)
elif e33 > efficiency:
return (3,3)
elif e22 > efficiency:
return (2,2)
else:
return (1,1)
def count_blocks(A,blocksize):
"""For a given blocksize=(r,c) count the number of occupied
blocks in a sparse matrix A
"""
r,c = blocksize
if r < 1 or c < 1:
raise ValueError('r and c must be positive')
if isspmatrix_csr(A):
M,N = A.shape
return csr_count_blocks(M,N,r,c,A.indptr,A.indices)
elif isspmatrix_csc(A):
return count_blocks(A.T,(c,r))
else:
return count_blocks(csr_matrix(A),blocksize)
| bsd-3-clause |
mottosso/mindbender-setup | bin/pythonpath/raven/contrib/django/resolver.py | 1 | 2907 | from __future__ import absolute_import
import re
try:
from django.urls import get_resolver
except ImportError:
from django.core.urlresolvers import get_resolver
class RouteResolver(object):
_optional_group_matcher = re.compile(r'\(\?\:([^\)]+)\)')
_named_group_matcher = re.compile(r'\(\?P<(\w+)>[^\)]+\)')
_non_named_group_matcher = re.compile(r'\([^\)]+\)')
# [foo|bar|baz]
_either_option_matcher = re.compile(r'\[([^\]]+)\|([^\]]+)\]')
_camel_re = re.compile(r'([A-Z]+)([a-z])')
_cache = {}
def _simplify(self, pattern):
"""
Clean up urlpattern regexes into something readable by humans:
From:
> "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
To:
> "{sport_slug}/athletes/{athlete_slug}/"
"""
# remove optional params
# TODO(dcramer): it'd be nice to change these into [%s] but it currently
# conflicts with the other rules because we're doing regexp matches
# rather than parsing tokens
result = self._optional_group_matcher.sub(lambda m: '%s' % m.group(1), pattern)
# handle named groups first
result = self._named_group_matcher.sub(lambda m: '{%s}' % m.group(1), result)
# handle non-named groups
result = self._non_named_group_matcher.sub('{var}', result)
# handle optional params
result = self._either_option_matcher.sub(lambda m: m.group(1), result)
# clean up any outstanding regex-y characters.
result = result.replace('^', '').replace('$', '') \
.replace('?', '').replace('//', '/').replace('\\', '')
return result
def _resolve(self, resolver, path, parents=None):
match = resolver.regex.search(path)
if not match:
return
if parents is None:
parents = [resolver]
elif resolver not in parents:
parents = parents + [resolver]
new_path = path[match.end():]
for pattern in resolver.url_patterns:
# this is an include()
if not pattern.callback:
match = self._resolve(pattern, new_path, parents)
if match:
return match
continue
elif not pattern.regex.search(new_path):
continue
try:
return self._cache[pattern]
except KeyError:
pass
prefix = ''.join(self._simplify(p.regex.pattern) for p in parents)
result = prefix + self._simplify(pattern.regex.pattern)
if not result.startswith('/'):
result = '/' + result
self._cache[pattern] = result
return result
def resolve(self, path, urlconf=None):
resolver = get_resolver(urlconf)
match = self._resolve(resolver, path)
return match or path
| mit |
endlessm/chromium-browser | third_party/chromite/lib/firmware/ap_firmware_config/volteer.py | 1 | 2219 | # -*- coding: utf-8 -*-
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Volteer configs."""
from __future__ import print_function
from chromite.lib import cros_logging as logging
BUILD_WORKON_PACKAGES = None
BUILD_PACKAGES = ('chromeos-bootimage',)
# TODO: Remove this line once VBoot is working on Volteer.
DEPLOY_SERVO_FORCE_FLASHROM = True
def get_commands(servo):
"""Get specific flash commands for Volteer
Each board needs specific commands including the voltage for Vref, to turn
on and turn off the SPI flash. The get_*_commands() functions provide a
board-specific set of commands for these tasks. The voltage for this board
needs to be set to 3.3 V.
Args:
servo (servo_lib.Servo): The servo connected to the target DUT.
Returns:
list: [dut_control_on, dut_control_off, flashrom_cmd, futility_cmd]
dut_control*=2d arrays formmated like [["cmd1", "arg1", "arg2"],
["cmd2", "arg3", "arg4"]]
where cmd1 will be run before cmd2
flashrom_cmd=command to flash via flashrom
futility_cmd=command to flash via futility
"""
dut_control_on = [['cpu_fw_spi:on']]
dut_control_off = [['cpu_fw_spi:off']]
if servo.is_v2:
programmer = 'ft2232_spi:type=google-servo-v2,serial=%s' % servo.serial
elif servo.is_micro:
# TODO (jacobraz): remove warning once http://b/147679336 is resolved
logging.warning('servo_micro has not been functioning properly consider '
'using a different servo if this fails')
programmer = 'raiden_debug_spi:serial=%s' % servo.serial
elif servo.is_ccd:
# Note nothing listed for flashing with ccd_cr50 on go/volteer-care.
# These commands were based off the commands for other boards.
programmer = 'raiden_debug_spi:target=AP,serial=%s' % servo.serial
else:
raise Exception('%s not supported' % servo.version)
futility_cmd = ['futility', 'update', '-p', programmer, '-i']
flashrom_cmd = ['flashrom', '-p', programmer, '-w']
return [dut_control_on, dut_control_off, flashrom_cmd, futility_cmd]
| bsd-3-clause |
avnr/mailplate | setup.py | 1 | 1028 | from setuptools import setup
setup(
name = 'mailplate',
packages = [ 'mailplate' ],
package_data = { 'mailplate': [ 'driver/*.py' ]},
version = '0.601',
description = 'Send Muli-Language Multi-Transport Template-Driven Email',
author = 'Avner Herskovits',
author_email = 'avnr_ at outlook.com',
url = 'https://github.com/avnr/mailplate',
download_url = 'https://github.com/avnr/mailplate/tarball/0.601',
install_requires=[],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: No Input/Output (Daemon)',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Communications :: Email',
'Topic :: Utilities',
],
)
| mit |
Caoimhinmg/PmagPy | programs/nrm_specimens_magic.py | 1 | 8629 | #! /usr/bin/env python
from __future__ import print_function
from builtins import str
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
nrm_specimens_magic.py
DESCRIPTION
converts NRM data in a magic_measurements type file to
geographic and tilt corrected data in a pmag_specimens type file
SYNTAX
nrm_specimens_magic.py [-h][command line options]
OPTIONS:
-h prints the help message and quits
-f MFILE: specify input file
-fsa SFILE: specify er_samples format file [with orientations]
-F PFILE: specify output file
-A do not average replicate measurements
-crd [g, t]: specify coordinate system ([g]eographic or [t]ilt adjusted)
NB: you must have the SFILE in this directory
DEFAULTS
MFILE: magic_measurements.txt
PFILE: nrm_specimens.txt
SFILE: er_samples.txt
coord: specimen
average replicate measurements?: YES
"""
#
# define some variables
#
beg,end,pole,geo,tilt,askave,save=0,0,[],0,0,0,0
samp_file=1
args=sys.argv
geo,tilt,orient=0,0,0
doave=1
user,comment,doave,coord="","",1,""
dir_path='.'
if "-h" in args:
print(main.__doc__)
sys.exit()
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
meas_file=dir_path+"/magic_measurements.txt"
pmag_file=dir_path+"/nrm_specimens.txt"
samp_file=dir_path+"/er_samples.txt"
if "-A" in args: doave=0
if "-f" in args:
ind=args.index("-f")
meas_file=sys.argv[ind+1]
if "-F" in args:
ind=args.index("-F")
pmag_file=dir_path+'/'+sys.argv[ind+1]
speclist=[]
if "-fsa" in args:
ind=args.index("-fsa")
samp_file=dir_path+'/'+sys.argv[ind+1]
if "-crd" in args:
ind=args.index("-crd")
coord=sys.argv[ind+1]
if coord=="g":
geo,orient=1,1
if coord=="t":
tilt,orient,geo=1,1,1
#
# read in data
if samp_file!="":
samp_data,file_type=pmag.magic_read(samp_file)
if file_type != 'er_samples':
print(file_type)
print("This is not a valid er_samples file ")
sys.exit()
else: print(samp_file,' read in with ',len(samp_data),' records')
else:
print('no orientations - will create file in specimen coordinates')
geo,tilt,orient=0,0,0
#
#
meas_data,file_type=pmag.magic_read(meas_file)
if file_type != 'magic_measurements':
print(file_type)
print(file_type,"This is not a valid magic_measurements file ")
sys.exit()
#
if orient==1:
# set orientation priorities
SO_methods=[]
orientation_priorities={'0':'SO-SUN','1':'SO-GPS-DIFF','2':'SO-SIGHT-BACK','3':'SO-CMD-NORTH','4':'SO-MAG'}
for rec in samp_data:
if "magic_method_codes" in rec:
methlist=rec["magic_method_codes"]
for meth in methlist.split(":"):
if "SO" in meth and "SO-POM" not in meth.strip():
if meth.strip() not in SO_methods: SO_methods.append(meth.strip())
#
# sort the sample names
#
sids=pmag.get_specs(meas_data)
#
#
PmagSpecRecs=[]
for s in sids:
skip=0
recnum=0
PmagSpecRec={}
PmagSpecRec["er_analyst_mail_names"]=user
method_codes,inst_code=[],""
# find the data from the meas_data file for this sample
#
# collect info for the PmagSpecRec dictionary
#
meas_meth=[]
for rec in meas_data: # copy of vital stats to PmagSpecRec from first spec record
if rec["er_specimen_name"]==s:
PmagSpecRec["er_specimen_name"]=s
PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
PmagSpecRec["er_site_name"]=rec["er_site_name"]
PmagSpecRec["er_location_name"]=rec["er_location_name"]
PmagSpecRec["er_citation_names"]="This study"
PmagSpecRec["magic_instrument_codes"]=""
if "magic_experiment_name" not in list(rec.keys()):
rec["magic_experiment_name"]=""
if "magic_instrument_codes" not in list(rec.keys()):
rec["magic_instrument_codes"]=""
else:
PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
if len(rec["magic_instrument_codes"]) > len(inst_code):
inst_code=rec["magic_instrument_codes"]
PmagSpecRec["magic_instrument_codes"]=inst_code # copy over instruments
break
#
# now check for correct method labels for all measurements
#
nrm_data=[]
for meas_rec in meas_data:
if meas_rec['er_specimen_name']==PmagSpecRec['er_specimen_name']:
meths=meas_rec["magic_method_codes"].split(":")
for meth in meths:
if meth.strip() not in meas_meth:meas_meth.append(meth)
if "LT-NO" in meas_meth:nrm_data.append(meas_rec)
#
data,units=pmag.find_dmag_rec(s,nrm_data)
#
datablock=data
#
# find replicate measurements at NRM step and average them
#
Specs=[]
if doave==1:
step_meth,avedata=pmag.vspec(data)
if len(avedata) != len(datablock):
method_codes.append("DE-VM")
SpecRec=avedata[0]
print('averaging data ')
else: SpecRec=data[0]
Specs.append(SpecRec)
else:
for spec in data:Specs.append(spec)
for SpecRec in Specs:
#
# do geo or stratigraphic correction now
#
if geo==1:
#
# find top priority orientation method
redo,p=1,0
if len(SO_methods)<=1:
az_type=SO_methods[0]
orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
if orient["sample_azimuth"] !="": method_codes.append(az_type)
redo=0
while redo==1:
if p>=len(orientation_priorities):
print("no orientation data for ",s)
skip,redo=1,0
break
az_type=orientation_priorities[str(p)]
orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
if orient["sample_azimuth"] !="":
method_codes.append(az_type.strip())
redo=0
elif orient["sample_azimuth"] =="":
p+=1
#
# if stratigraphic selected, get stratigraphic correction
#
if skip==0 and orient["sample_azimuth"]!="" and orient["sample_dip"]!="":
d_geo,i_geo=pmag.dogeo(SpecRec[1],SpecRec[2],orient["sample_azimuth"],orient["sample_dip"])
SpecRec[1]=d_geo
SpecRec[2]=i_geo
if tilt==1 and "sample_bed_dip" in list(orient.keys()) and orient['sample_bed_dip']!="":
d_tilt,i_tilt=pmag.dotilt(d_geo,i_geo,orient["sample_bed_dip_direction"],orient["sample_bed_dip"])
SpecRec[1]=d_tilt
SpecRec[2]=i_tilt
if skip==0:
PmagSpecRec["specimen_dec"]='%7.1f ' %(SpecRec[1])
PmagSpecRec["specimen_inc"]='%7.1f ' %(SpecRec[2])
if geo==1 and tilt==0:PmagSpecRec["specimen_tilt_correction"]='0'
if geo==1 and tilt==1: PmagSpecRec["specimen_tilt_correction"]='100'
if geo==0 and tilt==0: PmagSpecRec["specimen_tilt_correction"]='-1'
PmagSpecRec["specimen_direction_type"]='l'
PmagSpecRec["magic_method_codes"]="LT-NO"
if len(method_codes) != 0:
methstring=""
for meth in method_codes:
methstring=methstring+ ":" +meth
PmagSpecRec["magic_method_codes"]=methstring[1:]
PmagSpecRec["specimen_description"]="NRM data"
PmagSpecRecs.append(PmagSpecRec)
pmag.magic_write(pmag_file,PmagSpecRecs,'pmag_specimens')
print("Data saved in ",pmag_file)
if __name__ == "__main__":
main()
| bsd-3-clause |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/python/training/basic_loops.py | 95 | 2251 | # 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.
# ==============================================================================
"""Basic loop for training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import errors
def basic_train_loop(supervisor, train_step_fn, args=None,
kwargs=None, master=""):
"""Basic loop to train a model.
Calls `train_step_fn` in a loop to train a model. The function is called as:
```python
train_step_fn(session, *args, **kwargs)
```
It is passed a `tf.Session` in addition to `args` and `kwargs`. The function
typically runs one training step in the session.
Args:
supervisor: `tf.train.Supervisor` to run the training services.
train_step_fn: Callable to execute one training step. Called
repeatedly as `train_step_fn(session, *args **kwargs)`.
args: Optional positional arguments passed to `train_step_fn`.
kwargs: Optional keyword arguments passed to `train_step_fn`.
master: Master to use to create the training session. Defaults to
`""` which causes the session to be created in the local process.
"""
if args is None:
args = []
if kwargs is None:
kwargs = {}
should_retry = True
while should_retry:
try:
should_retry = False
with supervisor.managed_session(master) as sess:
while not supervisor.should_stop():
train_step_fn(sess, *args, **kwargs)
except errors.AbortedError:
# Always re-run on AbortedError as it indicates a restart of one of the
# distributed tensorflow servers.
should_retry = True
| apache-2.0 |
BRD-CD/superset | superset/views/base.py | 2 | 11040 | import functools
import json
import logging
import traceback
from flask import g, redirect, Response, flash, abort
from flask_babel import gettext as __
from flask_appbuilder import BaseView
from flask_appbuilder import ModelView
from flask_appbuilder.widgets import ListWidget
from flask_appbuilder.actions import action
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_appbuilder.security.sqla import models as ab_models
from superset import appbuilder, conf, db, utils, sm, sql_parse
from superset.connectors.connector_registry import ConnectorRegistry
from superset.connectors.sqla.models import SqlaTable
def get_error_msg():
if conf.get("SHOW_STACKTRACE"):
error_msg = traceback.format_exc()
else:
error_msg = "FATAL ERROR \n"
error_msg += (
"Stacktrace is hidden. Change the SHOW_STACKTRACE "
"configuration setting to enable it")
return error_msg
def json_error_response(msg, status=None, stacktrace=None):
data = {'error': str(msg)}
if stacktrace:
data['stacktrace'] = stacktrace
status = status if status else 500
return Response(
json.dumps(data),
status=status, mimetype="application/json")
def api(f):
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
logging.exception(e)
return json_error_response(get_error_msg())
return functools.update_wrapper(wraps, f)
def get_datasource_exist_error_mgs(full_name):
return __("Datasource %(name)s already exists", name=full_name)
def get_user_roles():
if g.user.is_anonymous():
public_role = conf.get('AUTH_ROLE_PUBLIC')
return [appbuilder.sm.find_role(public_role)] if public_role else []
return g.user.roles
class BaseSupersetView(BaseView):
def can_access(self, permission_name, view_name, user=None):
if not user:
user = g.user
return utils.can_access(
appbuilder.sm, permission_name, view_name, user)
def all_datasource_access(self, user=None):
return self.can_access(
"all_datasource_access", "all_datasource_access", user=user)
def database_access(self, database, user=None):
return (
self.can_access(
"all_database_access", "all_database_access", user=user) or
self.can_access("database_access", database.perm, user=user)
)
def schema_access(self, datasource, user=None):
return (
self.database_access(datasource.database, user=user) or
self.all_datasource_access(user=user) or
self.can_access("schema_access", datasource.schema_perm, user=user)
)
def datasource_access(self, datasource, user=None):
return (
self.schema_access(datasource, user=user) or
self.can_access("datasource_access", datasource.perm, user=user)
)
def datasource_access_by_name(
self, database, datasource_name, schema=None):
if self.database_access(database) or self.all_datasource_access():
return True
schema_perm = utils.get_schema_perm(database, schema)
if schema and self.can_access('schema_access', schema_perm):
return True
datasources = ConnectorRegistry.query_datasources_by_name(
db.session, database, datasource_name, schema=schema)
for datasource in datasources:
if self.can_access("datasource_access", datasource.perm):
return True
return False
def datasource_access_by_fullname(
self, database, full_table_name, schema):
table_name_pieces = full_table_name.split(".")
if len(table_name_pieces) == 2:
table_schema = table_name_pieces[0]
table_name = table_name_pieces[1]
else:
table_schema = schema
table_name = table_name_pieces[0]
return self.datasource_access_by_name(
database, table_name, schema=table_schema)
def rejected_datasources(self, sql, database, schema):
superset_query = sql_parse.SupersetQuery(sql)
return [
t for t in superset_query.tables if not
self.datasource_access_by_fullname(database, t, schema)]
def user_datasource_perms(self):
datasource_perms = set()
for r in g.user.roles:
for perm in r.permissions:
if (
perm.permission and
'datasource_access' == perm.permission.name):
datasource_perms.add(perm.view_menu.name)
return datasource_perms
def schemas_accessible_by_user(self, database, schemas):
if self.database_access(database) or self.all_datasource_access():
return schemas
subset = set()
for schema in schemas:
schema_perm = utils.get_schema_perm(database, schema)
if self.can_access('schema_access', schema_perm):
subset.add(schema)
perms = self.user_datasource_perms()
if perms:
tables = (
db.session.query(SqlaTable)
.filter(
SqlaTable.perm.in_(perms),
SqlaTable.database_id == database.id,
)
.all()
)
for t in tables:
if t.schema:
subset.add(t.schema)
return sorted(list(subset))
def accessible_by_user(self, database, datasource_names, schema=None):
if self.database_access(database) or self.all_datasource_access():
return datasource_names
if schema:
schema_perm = utils.get_schema_perm(database, schema)
if self.can_access('schema_access', schema_perm):
return datasource_names
user_perms = self.user_datasource_perms()
user_datasources = ConnectorRegistry.query_datasources_by_permissions(
db.session, database, user_perms)
if schema:
names = {
d.table_name
for d in user_datasources if d.schema == schema}
return [d for d in datasource_names if d in names]
else:
full_names = {d.full_name for d in user_datasources}
return [d for d in datasource_names if d in full_names]
class SupersetModelView(ModelView):
page_size = 100
class ListWidgetWithCheckboxes(ListWidget):
"""An alternative to list view that renders Boolean fields as checkboxes
Works in conjunction with the `checkbox` view."""
template = 'superset/fab_overrides/list_with_checkboxes.html'
def validate_json(form, field): # noqa
try:
json.loads(field.data)
except Exception as e:
logging.exception(e)
raise Exception("json isn't valid")
class DeleteMixin(object):
def _delete(self, pk):
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete
"""
item = self.datamodel.get(pk, self._base_filters)
if not item:
abort(404)
try:
self.pre_delete(item)
except Exception as e:
flash(str(e), "danger")
else:
view_menu = sm.find_view_menu(item.get_perm())
pvs = sm.get_session.query(sm.permissionview_model).filter_by(
view_menu=view_menu).all()
schema_view_menu = None
if hasattr(item, 'schema_perm'):
schema_view_menu = sm.find_view_menu(item.schema_perm)
pvs.extend(sm.get_session.query(
sm.permissionview_model).filter_by(
view_menu=schema_view_menu).all())
if self.datamodel.delete(item):
self.post_delete(item)
for pv in pvs:
sm.get_session.delete(pv)
if view_menu:
sm.get_session.delete(view_menu)
if schema_view_menu:
sm.get_session.delete(schema_view_menu)
sm.get_session.commit()
flash(*self.datamodel.message)
self.update_redirect()
@action(
"muldelete",
__("Delete"),
__("Delete all Really?"),
"fa-trash",
single=False
)
def muldelete(self, items):
if not items:
abort(404)
for item in items:
try:
self.pre_delete(item)
except Exception as e:
flash(str(e), "danger")
else:
self._delete(item.id)
self.update_redirect()
return redirect(self.get_redirect())
class SupersetFilter(BaseFilter):
"""Add utility function to make BaseFilter easy and fast
These utility function exist in the SecurityManager, but would do
a database round trip at every check. Here we cache the role objects
to be able to make multiple checks but query the db only once
"""
def get_user_roles(self):
return get_user_roles()
def get_all_permissions(self):
"""Returns a set of tuples with the perm name and view menu name"""
perms = set()
for role in self.get_user_roles():
for perm_view in role.permissions:
t = (perm_view.permission.name, perm_view.view_menu.name)
perms.add(t)
return perms
def has_role(self, role_name_or_list):
"""Whether the user has this role name"""
if not isinstance(role_name_or_list, list):
role_name_or_list = [role_name_or_list]
return any(
[r.name in role_name_or_list for r in self.get_user_roles()])
def has_perm(self, permission_name, view_menu_name):
"""Whether the user has this perm"""
return (permission_name, view_menu_name) in self.get_all_permissions()
def get_view_menus(self, permission_name):
"""Returns the details of view_menus for a perm name"""
vm = set()
for perm_name, vm_name in self.get_all_permissions():
if perm_name == permission_name:
vm.add(vm_name)
return vm
def has_all_datasource_access(self):
return (
self.has_role(['Admin', 'Alpha']) or
self.has_perm('all_datasource_access', 'all_datasource_access'))
class DatasourceFilter(SupersetFilter):
def apply(self, query, func): # noqa
if self.has_all_datasource_access():
return query
perms = self.get_view_menus('datasource_access')
# TODO(bogdan): add `schema_access` support here
return query.filter(self.model.perm.in_(perms))
| apache-2.0 |
ioam/svn-history | topo/tkgui/topoconsole.py | 1 | 29735 | """
TopoConsole class file.
$Id$
"""
__version__='$Revision$'
# CB: does the status bar need to keep saying 'ok'? Sometimes
# positive feedback is useful, but 'ok' doesn't seem too helpful.
import os
import copy
import sys
import __main__
import webbrowser
import string
from Tkinter import Frame, Button, \
LEFT, YES, Label, DISABLED, \
NORMAL, DoubleVar
from tkFileDialog import asksaveasfilename,askopenfilename
import param
from param import normalize_path,resolve_path
import paramtk as tk
import topo
from topo.plotting.plotgroup import plotgroups, FeatureCurvePlotGroup
from topo.misc.keyedlist import KeyedList
from topo.misc.commandline import sim_name_from_filename
import topo.misc.genexamples
import topo.command
import topo.tkgui
from templateplotgrouppanel import TemplatePlotGroupPanel
from featurecurvepanel import FeatureCurvePanel
from projectionpanel import CFProjectionPanel,ProjectionActivityPanel,ConnectionFieldsPanel,RFProjectionPanel
from testpattern import TestPattern
from editor import ModelEditor
tk.AppWindow.window_icon_path = resolve_path('tkgui/icons/topo.xbm')
SCRIPT_FILETYPES = [('Topographica scripts','*.ty'),
('Python scripts','*.py'),
('All files','*')]
SAVED_FILE_EXTENSION = '.typ'
SAVED_FILETYPES = [('Topographica saved networks',
'*'+SAVED_FILE_EXTENSION),
('All files','*')]
turl = "http://topographica.org/"
userman = "User_Manual/index.html"
tuts = "Tutorials/index.html"
refman = "Reference_Manual/index.html"
plotman = "User_Manual/plotting.html"
# for deb on ubuntu; will need to check others
pkgdoc = "/usr/share/doc/topographica/doc/"
# Documentation locations: locally built and web urls.
user_manual_locations = ('doc/'+userman,
pkgdoc+userman,
turl+userman)
tutorials_locations = ('doc/'+tuts,
pkgdoc+tuts,
turl+tuts)
reference_manual_locations = ('doc/'+refman,
pkgdoc+refman,
turl+refman)
python_doc_locations = ('http://www.python.org/doc/',)
topo_www_locations = (turl,)
plotting_help_locations = ('doc/'+plotman,
pkgdoc+plotman,
turl+plotman)
# If a particular plotgroup_template needs (or works better with) a
# specific subclass of PlotPanel, the writer of the new subclass
# or the plotgroup_template can declare here that that template
# should use a specific PlotPanel subclass. For example:
# plotpanel_classes['Hue Pref Map'] = HuePreferencePanel
plotpanel_classes = {}
# CEBALERT: why are the other plotpanel_classes updates at the end of this file?
def open_plotgroup_panel(class_,plotgroup=None,**kw):
if class_.valid_context():
win = topo.guimain.some_area.new_window()
panel = class_(win,plotgroup=plotgroup,**kw)
if not panel.dock:
topo.guimain.some_area.eject(win)
else:
topo.guimain.some_area.consume(win)
panel.refresh_title()
panel.pack(expand='yes',fill='both')
win.sizeright()
#frame.sizeright()
#topo.guimain.messageBar.message('state', 'OK')
return panel
else:
topo.guimain.messageBar.response(
'No suitable objects in this simulation for this operation.')
class PlotsMenuEntry(param.Parameterized):
"""
Stores information about a Plots menu command
(including the command itself, and the plotgroup template).
"""
def __init__(self,plotgroup,class_=TemplatePlotGroupPanel,**params):
"""
Store the template, and set the class that will be created by this menu entry
If users want to extend the Plot Panel classes, then they
should add entries to the plotpanel_classes dictionary.
If no entry is defined there, then the default class is used.
The class_ is overridden for any special cases listed in this method.
"""
super(PlotsMenuEntry,self).__init__(**params)
self.plotgroup = plotgroup
# Special cases. These classes are specific to the topo/tkgui
# directory and therefore this link must be made within the tkgui
# files.
if isinstance(self.plotgroup,FeatureCurvePlotGroup):
class_ = plotpanel_classes.get(self.plotgroup.name,FeatureCurvePanel)
self.class_ = plotpanel_classes.get(self.plotgroup.name,class_)
def __call__(self,event=None,**kw):
"""
Instantiate the class_ (used as menu commands' 'command' attribute).
Keyword args are passed to the class_.
"""
new_plotgroup = copy.deepcopy(self.plotgroup)
# CB: hack to share plot_templates with the current
# plotgroup in plotgroups
new_plotgroup.plot_templates = topo.plotting.plotgroup.plotgroups[self.plotgroup.name].plot_templates
return open_plotgroup_panel(self.class_,new_plotgroup,**kw)
# Notebook only available for Tkinter>=8.5
try:
from paramtk.tilewrapper import Notebook
class DockManager(Notebook):
"""Manages windows that can be tabs in a notebook, or toplevels."""
def __init__(self, master=None, cnf={}, **kw):
Notebook.__init__(self, master, cnf=cnf, **kw)
self._tab_ids = {}
def _set_tab_title(self,win,title):
self.tab(self._tab_ids[win],text=title)
def _set_toplevel_title(self,win,title):
prefix = topo.sim.name+": "
if not title.startswith(prefix):
title=prefix+title
self.tk.call("wm","title",win._w,title)
def add(self, child, cnf={}, **kw):
self._tab_ids[child]=len(self.tabs())
Notebook.add(self,child,cnf=cnf,**kw)
## def unhide(self,win):
## if win in self._tab_ids:
## self.tab(self._tab_ids[win],state='normal')
def new_window(self):
win = tk.AppWindow(self,status=True)
#self.consume(win)
return win
def consume(self,win):
if win not in self._tab_ids:
self.tk.call('wm','forget',win._w)
win.title = lambda x: self._set_tab_title(win,x)
self.add(win)
def eject(self,win):
if win in self._tab_ids:
self.forget(self._tab_ids[win])
# manage my tab ids (HACK)
del self._tab_ids[win]
for w in self._tab_ids:
self._tab_ids[w]-=1
self._tab_ids[w]=max(self._tab_ids[w],0)
self.tk.call('wm','manage',win._w)
win.renew()
win.title = lambda x: self._set_toplevel_title(win,x)
return win
except ImportError:
class FakeDockManager(Frame):
def _set_tab_title(self,*args):
pass
def _set_toplevel_title(self,win,title):
prefix = topo.sim.name+": "
if not title.startswith(prefix):
title=prefix+title
self.tk.call("wm","title",win._w,title)
def add(self,*args):
pass
def new_window(self):
win = tk.AppWindow(self,status=True)
return win
def consume(self,win):
pass
def eject(self,win):
win.renew()
win.title = lambda x: self._set_toplevel_title(win,x)
return win
DockManager = FakeDockManager
# This is really a hack. There doesn't seem to be any easy way to tie
# an exception to the window from which it originated. (I couldn't
# find an example of tkinter software displaying a gui exception on
# the originating window.)
def _tkinter_report_exception(widget):
exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
msg = "(%s) %s"%(exc.__name__,val)
# If the supplied widget has no master, it's probably the Tk
# instance. In that case, resort to the 'last-one-set' hack (see
# CEBALERT "provide a way of allowing other gui components" in
# topo/param/tk.py).
if not widget.master:
widget = tk._last_one_set
stat = None
while (widget is not None and widget.master):
# CEBALERT: should rename all status bars to the same thing
# (status_bar)
if hasattr(widget,'status'):
stat = widget.status
break
elif hasattr(widget,'messageBar'):
stat = widget.messageBar
break
widget = widget.master
if stat is not None:
stat.error('%s'%msg)
else:
topo.guimain.messageBar.error('%s'%msg)
# BK-NOTE: Default is now to display full trace always. Any user
# errors should be caught as special exception cases
# BK-ALERT: Want to raise errors vs print, however this currently crashes ipython.
#raise
param.Parameterized().warning(msg)
import traceback
traceback.print_exc()
import Tkinter
class TopoConsole(tk.AppWindow,tk.TkParameterized):
"""
Main window for the Tk-based GUI.
"""
def _getmenubar(self):
return self.master.menubar
menubar = property(_getmenubar)
def __getitem__(self,menu_name):
"""Allow dictionary-style access to the menu bar."""
return self.menubar[menu_name]
def __init__(self,root,**params):
tk.AppWindow.__init__(self,root,status=True)
tk.TkParameterized.__init__(self,root,**params)
# Instead of displaying tracebacks on the commandline, try to display
# them on the originating window.
# CEBALERT: on destroy(), ought to revert this
Tkinter.Misc._report_exception=_tkinter_report_exception
self.auto_refresh_panels = []
self._init_widgets()
self.title(topo.sim.name) # If -g passed *before* scripts on commandline, this is useless.
# So topo.misc.commandline sets the title as its last action (if -g)
# catch click on the 'x': offers choice to quit or not
self.protocol("WM_DELETE_WINDOW",self.quit_topographica)
##########
### Make cascade menus open automatically on linux when the mouse
### is over the menu title.
### [Tkinter-discuss] Cascade menu issue
### http://mail.python.org/pipermail/tkinter-discuss/2006-August/000864.html
if topo.tkgui.system_platform is 'linux':
activate_cascade = """\
if {[%W cget -type] != {menubar} && [%W type active] == {cascade}} {
%W postcascade active
}
"""
self.bind_class("Menu", "<<MenuSelect>>", activate_cascade)
##########
# Install warning and message handling
from param.parameterized import Parameterized
self.__orig_P_warning = Parameterized.warning
self.__orig_P_message = Parameterized.message
type.__setattr__(Parameterized,'warning',self.gui_warning)
type.__setattr__(Parameterized,'message',self.gui_message)
def gui_warning(self,*args):
stat = self.__get_status_bar()
s = string.join(args,' ')
stat.warn(s)
self.__orig_P_warning(self,*args)
def gui_message(self,*args):
stat = self.__get_status_bar()
s = string.join(args,' ')
stat.message(s)
self.__orig_P_message(self,*args)
def title(self,t=None):
newtitle = "Topographica"
if t: newtitle+=": %s" % t
tk.AppWindow.title(self,newtitle)
def _init_widgets(self):
## CEBALERT: now we can have multiple operations at the same time,
## status bar could be improved to show all tasks?
# CEBALERT
self.messageBar = self.status
self.some_area = DockManager(self)
self.some_area.pack(fill="both", expand=1)
### Balloon, for pop-up help
self.balloon = tk.Balloon(self.content)
### Top-level (native) menu bar
#self.menubar = tk.ControllableMenu(self.content)
self.configure(menu=self.menubar)
#self.menu_balloon = Balloon(topo.tkgui.root)
# no menubar in tile yet
# http://news.hping.org/comp.lang.tcl.archive/4679.html
self.__simulation_menu()
self.__create_plots_menu()
self.refresh_plots_menu()
self.__help_menu()
### Running the simulation
run_frame = Frame(self.content)
run_frame.pack(side='top',fill='x',padx=4,pady=8)
self.run_frame = run_frame
Label(run_frame,text='Run for: ').pack(side=LEFT)
self.run_for_var=DoubleVar()
self.run_for_var.set(1.0)
run_for = tk.TaggedSlider(run_frame,
variable=self.run_for_var,
tag_width=11,
slider_length=150,
bounds=(0,20000))
self.balloon.bind(run_for,"Duration to run the simulation, e.g. 0.0500, 1.0, or 20000.")
run_for.pack(side=LEFT,fill='x',expand=YES)
run_for.tag.bind("<Return>",self.run_simulation)
# When return is pressed, the TaggedSlider updates itself...but we also want to run
# the simulation in this case.
run_frame.optional_action=self.run_simulation
go_button = Button(run_frame,text="Go",
command=self.run_simulation)
go_button.pack(side=LEFT)
self.balloon.bind(go_button,"Run the simulation for the specified duration.")
self.step_button = Button(run_frame,text="Step",command=self.run_step)
self.balloon.bind(self.step_button,"Run the simulation through the time at which the next events are processed.")
self.step_button.pack(side=LEFT)
self.sizeright()
def __simulation_menu(self):
"""Add the simulation menu options to the menubar."""
simulation_menu = ControllableMenu(self.menubar,tearoff=0)
self.menubar.add_cascade(label='Simulation',menu=simulation_menu)
simulation_menu.add_command(label='Run script',command=self.run_script)
simulation_menu.add_command(label='Save script',command=self.save_script_repr)
simulation_menu.add_command(label='Load snapshot',command=self.load_snapshot)
simulation_menu.add_command(label='Save snapshot',command=self.save_snapshot)
#simulation_menu.add_command(label='Reset',command=self.reset_network)
simulation_menu.add_command(label='Test Pattern',command=self.open_test_pattern)
simulation_menu.add_command(label='Model Editor',command=self.open_model_editor)
simulation_menu.add_command(label='Quit',command=self.quit_topographica)
def open_test_pattern(self):
return open_plotgroup_panel(TestPattern)
def __create_plots_menu(self):
"""
Add the plot menu to the menubar, with Basic plots on the menu itself and
others in cascades by category (the plots come from plotgroup_templates).
"""
plots_menu = ControllableMenu(self.menubar,tearoff=0)
self.menubar.add_cascade(label='Plots',menu=plots_menu)
# CEBALERT: should split other menus in same way as plots (create/refresh)
def refresh_plots_menu(self):
plots_menu = self['Plots']
plots_menu.delete(0,'end')
# create menu entries, and get list of categories
entries=KeyedList() # keep the order of plotgroup_templates (which is also KL)
categories = []
for label,plotgroup in plotgroups.items():
entries[label] = PlotsMenuEntry(plotgroup)
categories.append(plotgroup.category)
categories = sorted(set(categories))
# The Basic category items appear on the menu itself.
assert 'Basic' in categories, "'Basic' is the category for the standard Plots menu entries."
for label,entry in entries:
if entry.plotgroup.category=='Basic':
plots_menu.add_command(label=label,command=entry.__call__)
categories.remove('Basic')
plots_menu.add_separator()
# Add the other categories to the menu as cascades, and the plots of each category to
# their cascades.
for category in categories:
category_menu = ControllableMenu(plots_menu,tearoff=0)
plots_menu.add_cascade(label=category,menu=category_menu)
# could probably search more efficiently than this
for label,entry in sorted(entries):
if entry.plotgroup.category==category:
category_menu.add_command(label=label,command=entry.__call__)
plots_menu.add_separator()
plots_menu.add_command(label="Help",command=(lambda x=plotting_help_locations: self.open_location(x)))
def __help_menu(self):
"""Add the help menu options."""
help_menu = ControllableMenu(self.menubar,tearoff=0,name='help')
self.menubar.add_cascade(label='Help',menu=help_menu)
help_menu.add_command(label='About',command=self.new_about_window)
help_menu.add_command(label="User Manual",
command=(lambda x=user_manual_locations: self.open_location(x)))
help_menu.add_command(label="Tutorials",
command=(lambda x=tutorials_locations: self.open_location(x)))
help_menu.add_command(label="Examples",
command=self.run_example_script)
help_menu.add_command(label="Reference Manual",
command=(lambda x=reference_manual_locations: self.open_location(x)))
help_menu.add_command(label="Topographica.org",
command=(lambda x=topo_www_locations: self.open_location(x)))
help_menu.add_command(label="Python documentation",
command=(lambda x=python_doc_locations: self.open_location(x)))
def quit_topographica(self,check=True,exit_status=0):
"""Quit topographica."""
if not check or (check and tk.askyesno("Quit Topographica","Really quit?")):
self.destroy()
# matplotlib's tk backend starts its own Tk instances; we
# need to close these ourselves (at least to avoid error
# message about 'unusual termination' in Windows).
try: # not that there should be an error, but just in case...
import matplotlib._pylab_helpers
for figman in matplotlib._pylab_helpers.Gcf.get_all_fig_managers():
figman.destroy()
except:
pass
print "Quit selected; exiting"
# Workaround for obscure problem on some UNIX systems
# as of 4/2007, probably including Fedora Core 5.
# On these systems, if Topographica is started from a
# bash prompt and then quit from the Tkinter GUI (as
# opposed to using Ctrl-D in the terminal), the
# terminal would suppress echoing of all future user
# input. stty sane restores the terminal to sanity,
# but it is not clear why this is necessary.
# For more info:
# http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d0f33c8eb2e02d
if topo.tkgui.system_platform=="linux" and os.getenv('EMACS')!='t':
try: os.system("stty sane")
except: pass
# CEBALERT: re. above. Shouldn't we be able to store the
# output of "stty --save" before starting the gui, then
# ensure that when the gui exits (however badly it
# happens) run "stty saved_settings"?
# CEBALERT: there was no call to self.master.destroy()
sys.exit(exit_status)
def run_script(self):
"""
Dialog to run a user-selected script
The script is exec'd in __main__.__dict__ (i.e. as if it were specified on the commandline.)
"""
script = askopenfilename(initialdir=normalize_path(),filetypes=SCRIPT_FILETYPES)
if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
self.messageBar.response('Run canceled')
else:
execfile(script,__main__.__dict__)
self.messageBar.response('Ran ' + script)
sim_name_from_filename(script)
self.title(topo.sim.name)
# CEBALERT: duplicates most of run_script()
def run_example_script(self):
script = askopenfilename(initialdir=topo.misc.genexamples.find_examples(),
filetypes=SCRIPT_FILETYPES)
if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
self.messageBar.response('No example opened')
else:
execfile(script,__main__.__dict__)
self.messageBar.response('Ran ' + script)
sim_name_from_filename(script)
self.title(topo.sim.name)
def save_script_repr(self):
script_name = asksaveasfilename(filetypes=SCRIPT_FILETYPES,
initialdir=normalize_path(),
initialfile=topo.sim.basename()+"_script_repr.ty")
if script_name:
topo.command.save_script_repr(script_name)
self.messageBar.response('Script saved to ' + script_name)
def load_snapshot(self):
"""
Dialog to load a user-selected snapshot (see topo.command.load_snapshot() ).
"""
snapshot_name = askopenfilename(initialdir=normalize_path(),filetypes=SAVED_FILETYPES)
if snapshot_name in ('',(),None):
self.messageBar.response('No snapshot loaded.')
else:
self.messageBar.dynamicinfo('Loading snapshot (may take some time)...')
self.update_idletasks()
topo.command.load_snapshot(snapshot_name)
self.messageBar.response('Loaded snapshot ' + snapshot_name)
self.title(topo.sim.name)
self.auto_refresh()
def save_snapshot(self):
"""
Dialog to save a snapshot (see topo.command.save_snapshot() ).
Adds the file extension .typ if not already present.
"""
snapshot_name = asksaveasfilename(filetypes=SAVED_FILETYPES,
initialdir=normalize_path(),
initialfile=topo.sim.basename()+".typ")
if snapshot_name in ('',(),None):
self.messageBar.response('No snapshot saved.')
else:
if not snapshot_name.endswith('.typ'):
snapshot_name = snapshot_name + SAVED_FILE_EXTENSION
self.messageBar.dynamicinfo('Saving snapshot (may take some time)...')
self.update_idletasks()
topo.command.save_snapshot(snapshot_name)
self.messageBar.response('Snapshot saved to ' + snapshot_name)
def auto_refresh(self):
"""
Refresh all windows in auto_refresh_panels.
Panels can add and remove themselves to the list; those in the list
will have their refresh() method called whenever this console's
autorefresh() is called.
"""
for win in self.auto_refresh_panels:
win.refresh()
self.set_step_button_state()
self.update_idletasks()
### CEBERRORALERT: why doesn't updatecommand("display=True") for an
### orientation preference map measurement work with the
### hierarchical example? I guess this is the reason I thought the
### updating never worked properly (or I really did break it
### recently - or I'm confused)...
def refresh_activity_windows(self):
"""
Update any windows with a plotgroup_key of 'Activity'.
Used primarily for debugging long scripts that present a lot of activity patterns.
"""
for win in self.auto_refresh_panels:
if win.plotgroup.name=='Activity' or win.plotgroup.name=='ProjectionActivity' :
win.refresh()
self.update_idletasks()
def open_model_editor(self):
"""Start the Model editor."""
return ModelEditor(self)
def new_about_window(self):
win = tk.AppWindow(self)
win.withdraw()
win.title("About Topographica")
text = Label(win,text=topo.about(display=False),justify=LEFT)
text.pack(side=LEFT)
win.deiconify()
#self.messageBar.message('state', 'OK')
def open_location(self, locations):
"""
Try to open one of the specified locations in a new window of the default
browser. See webbrowser module for more information.
locations should be a tuple.
"""
# CB: could have been a list. This is only here because if locations is set
# to a string, it will loop over the characters of the string.
assert isinstance(locations,tuple),"locations must be a tuple."
for location in locations:
try:
existing_location = resolve_path(location)
webbrowser.open(existing_location,new=2,autoraise=True)
self.messageBar.response('Opened local file '+existing_location+' in browser.')
return ###
except:
pass
for location in locations:
if location.startswith('http'):
try:
webbrowser.open(location,new=2,autoraise=True)
self.messageBar.response('Opened remote location '+location+' in browser.')
return ###
except:
pass
self.messageBar.response("Could not open any of %s in a browser."%locations)
# CEBALERT: need to take care of removing old messages automatically?
# (Otherwise callers might always have to pass 'ok'.)
def status_message(self,m):
self.messageBar.response(m)
def run_simulation(self,event=None): # event=None allows use as callback
"""
Run the simulation for the duration specified in the
'run for' taggedslider.
"""
fduration = self.run_for_var.get()
self.open_progress_window(timer=topo.sim.timer)
topo.sim.run_and_time(fduration)
self.auto_refresh()
# CEBERRORALERT: Step button does strange things at time==0.
# E.g. for lissom_oo_or, nothing appears to happen. For
# hierarchical, runs to time==10.
def run_step(self):
if not topo.sim.events:
# JP: step button should be disabled if there are no events,
# but just in case...
return
# JPALERT: This should really use .run_and_time() but it doesn't support
# run(until=...)
topo.sim.run(until=topo.sim.events[0].time)
self.auto_refresh()
def set_step_button_state(self):
if topo.sim.events:
self.step_button.config(state=NORMAL)
else:
self.step_button.config(state=DISABLED)
def __get_status_bar(self,i=2):
# Hack to find appropriate status bar: Go back through frames
# until a widget with a status bar is found, and return it.
try:
while True:
f = sys._getframe(i)
if hasattr(f,'f_locals'):
if 'self' in f.f_locals:
o = f.f_locals['self']
# (temporary hack til ScrolledFrame cleaned up)
if o.__class__.__name__!='ScrolledFrame':
if hasattr(o,'messageBar'):
return o.messageBar
elif hasattr(o,'status'):
return o.status
i+=1
except:
pass
#print "GUI INTERNAL WARNING: failed to determine window on which to display message."
return self.messageBar
def open_progress_window(self,timer,title=None):
"""
Provide a convenient link to progress bars.
"""
stat = self.__get_status_bar()
return stat.open_progress_window(timer=timer,sim=topo.sim)
# CEBALERT: of course dictionary access is used as an alternative to
# the config method or whatever it's called! So this could cause
# serious confusion to someone trying to set config options using the
# dictionary style access rather than .config()! Either document
# clearly or abandon, and get() and set() to access menu entries by
# name.
class ControllableMenu(tk.Menu):
"""
A Menu, but where entries are accessible by name (using
dictionary-style access).
** Not truly compatible with Tkinter; work in progress **
"""
def __getitem__(self,name):
return self.named_commands[name]
if __name__ != '__main__':
plotpanel_classes['Connection Fields'] = ConnectionFieldsPanel
plotpanel_classes['RF Projection'] = RFProjectionPanel
plotpanel_classes['Projection'] = CFProjectionPanel
plotpanel_classes['Projection Activity'] = ProjectionActivityPanel
| bsd-3-clause |
0Steve0/Kaggle | Leaf Classfication/Leaf Classfication in Random Forest/Random Forest Benchmark.py | 1 | 1123 | #import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
# load training data
traindata = pd.read_csv('C:/Users/sound/Desktop/Kaggle/Leaf Classfication/data/train.csv')
x_train = traindata.values[:, 2:]
y_train = traindata.values[:, 1]
#set the number of trees in random forest
num_trees = [10, 50, 100, 200, 300, 400, 500]
#calculate the cross validation scores and std
cr_val_scores = list()
cr_val_scores_std = list()
for n_tree in num_trees:
recognizer = RandomForestClassifier(n_tree)
cr_val_score = cross_val_score(recognizer, x_train, y_train)
cr_val_scores.append(np.mean(cr_val_score))
cr_val_scores_std.append(np.std(cr_val_score))
#plot cross_val_score and std
sc_array = np.array(cr_val_scores)
std_array = np.array(cr_val_scores_std)
plt.plot(num_trees, cr_val_scores)
plt.plot(num_trees, sc_array + std_array, 'b--')
plt.plot(num_trees, sc_array - std_array, 'b--')
plt.ylabel('cross_val_scores')
plt.xlabel('num_of_trees')
plt.savefig('random_forest_benchmark.png')
| apache-2.0 |
vidyacraghav/cplusdratchio | deps/boost_1_55_0/tools/build/v2/build/targets.py | 18 | 56567 | # Status: ported.
# Base revision: 64488
# Copyright Vladimir Prus 2002-2007.
# Copyright Rene Rivera 2006.
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Supports 'abstract' targets, which are targets explicitly defined in Jamfile.
#
# Abstract targets are represented by classes derived from 'AbstractTarget' class.
# The first abstract target is 'project_target', which is created for each
# Jamfile, and can be obtained by the 'target' rule in the Jamfile's module.
# (see project.jam).
#
# Project targets keep a list of 'MainTarget' instances.
# A main target is what the user explicitly defines in a Jamfile. It is
# possible to have several definitions for a main target, for example to have
# different lists of sources for different platforms. So, main targets
# keep a list of alternatives.
#
# Each alternative is an instance of 'AbstractTarget'. When a main target
# subvariant is defined by some rule, that rule will decide what class to
# use, create an instance of that class and add it to the list of alternatives
# for the main target.
#
# Rules supplied by the build system will use only targets derived
# from 'BasicTarget' class, which will provide some default behaviour.
# There will be two classes derived from it, 'make-target', created by the
# 'make' rule, and 'TypedTarget', created by rules such as 'exe' and 'dll'.
#
# +------------------------+
# |AbstractTarget |
# +========================+
# |name |
# |project |
# | |
# |generate(properties) = 0|
# +-----------+------------+
# |
# ^
# / \
# +-+-+
# |
# |
# +------------------------+------+------------------------------+
# | | |
# | | |
# +----------+-----------+ +------+------+ +------+-------+
# | project_target | | MainTarget | | BasicTarget |
# +======================+ 1 * +=============+ alternatives +==============+
# | generate(properties) |o-----------+ generate |<>------------->| generate |
# | main-target | +-------------+ | construct = 0|
# +----------------------+ +--------------+
# |
# ^
# / \
# +-+-+
# |
# |
# ...--+----------------+------------------+----------------+---+
# | | | |
# | | | |
# ... ---+-----+ +------+-------+ +------+------+ +--------+-----+
# | | TypedTarget | | make-target | | stage-target |
# . +==============+ +=============+ +==============+
# . | construct | | construct | | construct |
# +--------------+ +-------------+ +--------------+
import re
import os.path
import sys
from b2.manager import get_manager
from b2.util.utility import *
import property, project, virtual_target, property_set, feature, generators, toolset
from virtual_target import Subvariant
from b2.exceptions import *
from b2.util.sequence import unique
from b2.util import path, bjam_signature
from b2.build.errors import user_error_checkpoint
import b2.build.build_request as build_request
import b2.util.set
_re_separate_target_from_properties = re.compile (r'^([^<]*)(/(<.*))?$')
class TargetRegistry:
def __init__ (self):
# All targets that are currently being built.
# Only the key is id (target), the value is the actual object.
self.targets_being_built_ = {}
# Current indent for debugging messages
self.indent_ = ""
self.debug_building_ = "--debug-building" in bjam.variable("ARGV")
self.targets_ = []
def main_target_alternative (self, target):
""" Registers the specified target as a main target alternatives.
Returns 'target'.
"""
target.project ().add_alternative (target)
return target
def main_target_sources (self, sources, main_target_name, no_renaming=0):
"""Return the list of sources to use, if main target rule is invoked
with 'sources'. If there are any objects in 'sources', they are treated
as main target instances, and the name of such targets are adjusted to
be '<name_of_this_target>__<name_of_source_target>'. Such renaming
is disabled is non-empty value is passed for 'no-renaming' parameter."""
result = []
for t in sources:
t = b2.util.jam_to_value_maybe(t)
if isinstance (t, AbstractTarget):
name = t.name ()
if not no_renaming:
name = main_target_name + '__' + name
t.rename (name)
# Inline targets are not built by default.
p = t.project()
p.mark_targets_as_explicit([name])
result.append(name)
else:
result.append (t)
return result
def main_target_requirements(self, specification, project):
"""Returns the requirement to use when declaring a main target,
which are obtained by
- translating all specified property paths, and
- refining project requirements with the one specified for the target
'specification' are the properties xplicitly specified for a
main target
'project' is the project where the main taret is to be declared."""
specification.extend(toolset.requirements())
requirements = property_set.refine_from_user_input(
project.get("requirements"), specification,
project.project_module(), project.get("location"))
return requirements
def main_target_usage_requirements (self, specification, project):
""" Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use-properties explicitly specified for a main target
project: Project where the main target is to be declared
"""
project_usage_requirements = project.get ('usage-requirements')
# We don't use 'refine-from-user-input' because I'm not sure if:
# - removing of parent's usage requirements makes sense
# - refining of usage requirements is not needed, since usage requirements
# are always free.
usage_requirements = property_set.create_from_user_input(
specification, project.project_module(), project.get("location"))
return project_usage_requirements.add (usage_requirements)
def main_target_default_build (self, specification, project):
""" Return the default build value to use when declaring a main target,
which is obtained by using specified value if not empty and parent's
default build attribute otherwise.
specification: Default build explicitly specified for a main target
project: Project where the main target is to be declared
"""
if specification:
return property_set.create_with_validation(specification)
else:
return project.get ('default-build')
def start_building (self, main_target_instance):
""" Helper rules to detect cycles in main target references.
"""
if self.targets_being_built_.has_key(id(main_target_instance)):
names = []
for t in self.targets_being_built_.values() + [main_target_instance]:
names.append (t.full_name())
get_manager().errors()("Recursion in main target references\n")
self.targets_being_built_[id(main_target_instance)] = main_target_instance
def end_building (self, main_target_instance):
assert (self.targets_being_built_.has_key (id (main_target_instance)))
del self.targets_being_built_ [id (main_target_instance)]
def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'.
"""
return self.main_target_alternative (TypedTarget (name, project, type,
self.main_target_sources (sources, name),
self.main_target_requirements (requirements, project),
self.main_target_default_build (default_build, project),
self.main_target_usage_requirements (usage_requirements, project)))
def increase_indent(self):
self.indent_ += " "
def decrease_indent(self):
self.indent_ = self.indent_[0:-4]
def logging(self):
return self.debug_building_
def log(self, message):
if self.debug_building_:
print self.indent_ + message
def push_target(self, target):
self.targets_.append(target)
def pop_target(self):
self.targets_ = self.targets_[:-1]
def current(self):
return self.targets_[0]
class GenerateResult:
def __init__ (self, ur=None, targets=None):
if not targets:
targets = []
self.__usage_requirements = ur
self.__targets = targets
assert all(isinstance(t, virtual_target.VirtualTarget) for t in targets)
if not self.__usage_requirements:
self.__usage_requirements = property_set.empty ()
def usage_requirements (self):
return self.__usage_requirements
def targets (self):
return self.__targets
def extend (self, other):
assert (isinstance (other, GenerateResult))
self.__usage_requirements = self.__usage_requirements.add (other.usage_requirements ())
self.__targets.extend (other.targets ())
class AbstractTarget:
""" Base class for all abstract targets.
"""
def __init__ (self, name, project, manager = None):
""" manager: the Manager object
name: name of the target
project: the project target to which this one belongs
manager:the manager object. If none, uses project.manager ()
"""
assert (isinstance (project, ProjectTarget))
# Note: it might seem that we don't need either name or project at all.
# However, there are places where we really need it. One example is error
# messages which should name problematic targets. Another is setting correct
# paths for sources and generated files.
# Why allow manager to be specified? Because otherwise project target could not derive
# from this class.
if manager:
self.manager_ = manager
else:
self.manager_ = project.manager ()
self.name_ = name
self.project_ = project
def manager (self):
return self.manager_
def name (self):
""" Returns the name of this target.
"""
return self.name_
def project (self):
""" Returns the project for this target.
"""
return self.project_
def location (self):
""" Return the location where the target was declared.
"""
return self.location_
def full_name (self):
""" Returns a user-readable name for this target.
"""
location = self.project ().get ('location')
return location + '/' + self.name_
def generate (self, property_set):
""" Takes a property set. Generates virtual targets for this abstract
target, using the specified properties, unless a different value of some
feature is required by the target.
On success, returns a GenerateResult instance with:
- a property_set with the usage requirements to be
applied to dependents
- a list of produced virtual targets, which may be
empty.
If 'property_set' is empty, performs default build of this
target, in a way specific to derived class.
"""
raise BaseException ("method should be defined in derived classes")
def rename (self, new_name):
self.name_ = new_name
class ProjectTarget (AbstractTarget):
""" Project target class (derived from 'AbstractTarget')
This class these responsibilities:
- maintaining a list of main target in this project and
building it
Main targets are constructed in two stages:
- When Jamfile is read, a number of calls to 'add_alternative' is made.
At that time, alternatives can also be renamed to account for inline
targets.
- The first time 'main-target' or 'has-main-target' rule is called,
all alternatives are enumerated an main targets are created.
"""
def __init__ (self, manager, name, project_module, parent_project, requirements, default_build):
AbstractTarget.__init__ (self, name, self, manager)
self.project_module_ = project_module
self.location_ = manager.projects().attribute (project_module, 'location')
self.requirements_ = requirements
self.default_build_ = default_build
self.build_dir_ = None
# A cache of IDs
self.ids_cache_ = {}
# True is main targets have already been built.
self.built_main_targets_ = False
# A list of the registered alternatives for this project.
self.alternatives_ = []
# A map from main target name to the target corresponding
# to it.
self.main_target_ = {}
# Targets marked as explicit.
self.explicit_targets_ = set()
# Targets marked as always
self.always_targets_ = set()
# The constants defined for this project.
self.constants_ = {}
# Whether targets for all main target are already created.
self.built_main_targets_ = 0
if parent_project:
self.inherit (parent_project)
# TODO: This is needed only by the 'make' rule. Need to find the
# way to make 'make' work without this method.
def project_module (self):
return self.project_module_
def get (self, attribute):
return self.manager().projects().attribute(
self.project_module_, attribute)
def build_dir (self):
if not self.build_dir_:
self.build_dir_ = self.get ('build-dir')
if not self.build_dir_:
self.build_dir_ = os.path.join(self.project_.get ('location'), 'bin')
return self.build_dir_
def generate (self, ps):
""" Generates all possible targets contained in this project.
"""
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent ()
result = GenerateResult ()
for t in self.targets_to_build ():
g = t.generate (ps)
result.extend (g)
self.manager_.targets().decrease_indent ()
return result
def targets_to_build (self):
""" Computes and returns a list of AbstractTarget instances which
must be built when this project is built.
"""
result = []
if not self.built_main_targets_:
self.build_main_targets ()
# Collect all main targets here, except for "explicit" ones.
for n, t in self.main_target_.iteritems ():
if not t.name () in self.explicit_targets_:
result.append (t)
# Collect all projects referenced via "projects-to-build" attribute.
self_location = self.get ('location')
for pn in self.get ('projects-to-build'):
result.append (self.find(pn + "/"))
return result
def mark_targets_as_explicit (self, target_names):
"""Add 'target' to the list of targets in this project
that should be build only by explicit request."""
# Record the name of the target, not instance, since this
# rule is called before main target instaces are created.
self.explicit_targets_.update(target_names)
def mark_targets_as_always(self, target_names):
self.always_targets_.update(target_names)
def add_alternative (self, target_instance):
""" Add new target alternative.
"""
if self.built_main_targets_:
raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.full_name ())
self.alternatives_.append (target_instance)
def main_target (self, name):
if not self.built_main_targets_:
self.build_main_targets()
return self.main_target_[name]
def has_main_target (self, name):
"""Tells if a main target with the specified name exists."""
if not self.built_main_targets_:
self.build_main_targets()
return self.main_target_.has_key(name)
def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'.
"""
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, None)
def find_really(self, id):
""" Find and return the target with the specified id, treated
relative to self.
"""
result = None
current_location = self.get ('location')
__re_split_project_target = re.compile (r'(.*)//(.*)')
split = __re_split_project_target.match (id)
project_part = None
target_part = None
if split:
project_part = split.group (1)
target_part = split.group (2)
project_registry = self.project_.manager ().projects ()
extra_error_message = ''
if project_part:
# There's explicit project part in id. Looks up the
# project and pass the request to it.
pm = project_registry.find (project_part, current_location)
if pm:
project_target = project_registry.target (pm)
result = project_target.find (target_part, no_error=1)
else:
extra_error_message = "error: could not find project '$(project_part)'"
else:
# Interpret target-name as name of main target
# Need to do this before checking for file. Consider this:
#
# exe test : test.cpp ;
# install s : test : <location>. ;
#
# After first build we'll have target 'test' in Jamfile and file
# 'test' on the disk. We need target to override the file.
result = None
if self.has_main_target(id):
result = self.main_target(id)
if not result:
result = FileReference (self.manager_, id, self.project_)
if not result.exists ():
# File actually does not exist.
# Reset 'target' so that an error is issued.
result = None
if not result:
# Interpret id as project-id
project_module = project_registry.find (id, current_location)
if project_module:
result = project_registry.target (project_module)
return result
def find (self, id, no_error = False):
v = self.ids_cache_.get (id, None)
if not v:
v = self.find_really (id)
self.ids_cache_ [id] = v
if v or no_error:
return v
raise BaseException ("Unable to find file or target named '%s'\nreferred from project at '%s'" % (id, self.get ('location')))
def build_main_targets (self):
self.built_main_targets_ = True
for a in self.alternatives_:
name = a.name ()
if not self.main_target_.has_key (name):
t = MainTarget (name, self.project_)
self.main_target_ [name] = t
if name in self.always_targets_:
a.always()
self.main_target_ [name].add_alternative (a)
def add_constant(self, name, value, path=0):
"""Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project.
"""
if path:
l = self.location_
if not l:
# Project corresponding to config files do not have
# 'location' attribute, but do have source location.
# It might be more reasonable to make every project have
# a location and use some other approach to prevent buildable
# targets in config files, but that's for later.
l = get('source-location')
value = os.path.join(l, value)
# Now make the value absolute path
value = os.path.join(os.getcwd(), value)
self.constants_[name] = value
bjam.call("set-variable", self.project_module(), name, value)
def inherit(self, parent_project):
for c in parent_project.constants_:
# No need to pass the type. Path constants were converted to
# absolute paths already by parent.
self.add_constant(c, parent_project.constants_[c])
# Import rules from parent
this_module = self.project_module()
parent_module = parent_project.project_module()
rules = bjam.call("RULENAMES", parent_module)
if not rules:
rules = []
user_rules = [x for x in rules
if x not in self.manager().projects().project_rules().all_names()]
if user_rules:
bjam.call("import-rules-from-parent", parent_module, this_module, user_rules)
class MainTarget (AbstractTarget):
""" A named top-level target in Jamfile.
"""
def __init__ (self, name, project):
AbstractTarget.__init__ (self, name, project)
self.alternatives_ = []
self.default_build_ = property_set.empty ()
def add_alternative (self, target):
""" Add a new alternative for this target.
"""
d = target.default_build ()
if self.alternatives_ and self.default_build_ != d:
get_manager().errors()("default build must be identical in all alternatives\n"
"main target is '%s'\n"
"with '%s'\n"
"differing from previous default build: '%s'" % (self.full_name (), d.raw (), self.default_build_.raw ()))
else:
self.default_build_ = d
self.alternatives_.append (target)
def __select_alternatives (self, property_set, debug):
""" Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)?
"""
# When selecting alternatives we have to consider defaults,
# for example:
# lib l : l.cpp : <variant>debug ;
# lib l : l_opt.cpp : <variant>release ;
# won't work unless we add default value <variant>debug.
property_set = property_set.add_defaults ()
# The algorithm: we keep the current best viable alternative.
# When we've got new best viable alternative, we compare it
# with the current one.
best = None
best_properties = None
if len (self.alternatives_) == 0:
return None
if len (self.alternatives_) == 1:
return self.alternatives_ [0]
if debug:
print "Property set for selection:", property_set
for v in self.alternatives_:
properties = v.match (property_set, debug)
if properties is not None:
if not best:
best = v
best_properties = properties
else:
if b2.util.set.equal (properties, best_properties):
return None
elif b2.util.set.contains (properties, best_properties):
# Do nothing, this alternative is worse
pass
elif b2.util.set.contains (best_properties, properties):
best = v
best_properties = properties
else:
return None
return best
def apply_default_build (self, property_set):
return apply_default_build(property_set, self.default_build_)
def generate (self, ps):
""" Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative.
"""
self.manager_.targets ().start_building (self)
# We want composite properties in build request act as if
# all the properties it expands too are explicitly specified.
ps = ps.expand ()
all_property_sets = self.apply_default_build (ps)
result = GenerateResult ()
for p in all_property_sets:
result.extend (self.__generate_really (p))
self.manager_.targets ().end_building (self)
return result
def __generate_really (self, prop_set):
""" Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated.
"""
best_alternative = self.__select_alternatives (prop_set, debug=0)
if not best_alternative:
# FIXME: revive.
# self.__select_alternatives(prop_set, debug=1)
self.manager_.errors()(
"No best alternative for '%s'.\n"
% (self.full_name(),))
result = best_alternative.generate (prop_set)
# Now return virtual targets for the only alternative
return result
def rename(self, new_name):
AbstractTarget.rename(self, new_name)
for a in self.alternatives_:
a.rename(new_name)
class FileReference (AbstractTarget):
""" Abstract target which refers to a source file.
This is artificial creature; it's usefull so that sources to
a target can be represented as list of abstract target instances.
"""
def __init__ (self, manager, file, project):
AbstractTarget.__init__ (self, file, project)
self.file_location_ = None
def generate (self, properties):
return GenerateResult (None, [
self.manager_.virtual_targets ().from_file (
self.name_, self.location(), self.project_) ])
def exists (self):
""" Returns true if the referred file really exists.
"""
if self.location ():
return True
else:
return False
def location (self):
# Returns the location of target. Needed by 'testing.jam'
if not self.file_location_:
source_location = self.project_.get('source-location')
for src_dir in source_location:
location = os.path.join(src_dir, self.name())
if os.path.isfile(location):
self.file_location_ = src_dir
self.file_path = location
break
return self.file_location_
def resolve_reference(target_reference, project):
""" Given a target_reference, made in context of 'project',
returns the AbstractTarget instance that is referred to, as well
as properties explicitly specified for this reference.
"""
# Separate target name from properties override
split = _re_separate_target_from_properties.match (target_reference)
if not split:
raise BaseException ("Invalid reference: '%s'" % target_reference)
id = split.group (1)
sproperties = []
if split.group (3):
sproperties = property.create_from_strings(feature.split(split.group(3)))
sproperties = feature.expand_composites(sproperties)
# Find the target
target = project.find (id)
return (target, property_set.create(sproperties))
def generate_from_reference(target_reference, project, property_set):
""" Attempts to generate the target given by target reference, which
can refer both to a main target or to a file.
Returns a list consisting of
- usage requirements
- generated virtual targets, if any
target_reference: Target reference
project: Project where the reference is made
property_set: Properties of the main target that makes the reference
"""
target, sproperties = resolve_reference(target_reference, project)
# Take properties which should be propagated and refine them
# with source-specific requirements.
propagated = property_set.propagated()
rproperties = propagated.refine(sproperties)
return target.generate(rproperties)
class BasicTarget (AbstractTarget):
""" Implements the most standard way of constructing main target
alternative from sources. Allows sources to be either file or
other main target and handles generation of those dependency
targets.
"""
def __init__ (self, name, project, sources, requirements = None, default_build = None, usage_requirements = None):
AbstractTarget.__init__ (self, name, project)
for s in sources:
if get_grist (s):
raise InvalidSource ("property '%s' found in the 'sources' parameter for '%s'" % (s, name))
self.sources_ = sources
if not requirements: requirements = property_set.empty ()
self.requirements_ = requirements
if not default_build: default_build = property_set.empty ()
self.default_build_ = default_build
if not usage_requirements: usage_requirements = property_set.empty ()
self.usage_requirements_ = usage_requirements
# A cache for resolved references
self.source_targets_ = None
# A cache for generated targets
self.generated_ = {}
# A cache for build requests
self.request_cache = {}
# Result of 'capture_user_context' has everything. For example, if this
# target is declare as result of loading Jamfile which was loaded when
# building target B which was requested from A, then we'll have A, B and
# Jamroot location in context. We only care about Jamroot location, most
# of the times.
self.user_context_ = self.manager_.errors().capture_user_context()[-1:]
self.always_ = False
def always(self):
self.always_ = True
def sources (self):
""" Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system.
"""
if self.source_targets_ == None:
self.source_targets_ = []
for s in self.sources_:
self.source_targets_.append(resolve_reference(s, self.project_)[0])
return self.source_targets_
def requirements (self):
return self.requirements_
def default_build (self):
return self.default_build_
def common_properties (self, build_request, requirements):
""" Given build request and requirements, return properties
common to dependency build request and target build
properties.
"""
# For optimization, we add free unconditional requirements directly,
# without using complex algorithsm.
# This gives the complex algorithm better chance of caching results.
# The exact effect of this "optimization" is no longer clear
free_unconditional = []
other = []
for p in requirements.all():
if p.feature().free() and not p.condition() and p.feature().name() != 'conditional':
free_unconditional.append(p)
else:
other.append(p)
other = property_set.create(other)
key = (build_request, other)
if not self.request_cache.has_key(key):
self.request_cache[key] = self.__common_properties2 (build_request, other)
return self.request_cache[key].add_raw(free_unconditional)
# Given 'context' -- a set of already present properties, and 'requirements',
# decide which extra properties should be applied to 'context'.
# For conditional requirements, this means evaluating condition. For
# indirect conditional requirements, this means calling a rule. Ordinary
# requirements are always applied.
#
# Handles situation where evaluating one conditional requirements affects
# condition of another conditional requirements, for example:
#
# <toolset>gcc:<variant>release <variant>release:<define>RELEASE
#
# If 'what' is 'refined' returns context refined with new requirements.
# If 'what' is 'added' returns just the requirements that must be applied.
def evaluate_requirements(self, requirements, context, what):
# Apply non-conditional requirements.
# It's possible that that further conditional requirement change
# a value set by non-conditional requirements. For example:
#
# exe a : a.cpp : <threading>single <toolset>foo:<threading>multi ;
#
# I'm not sure if this should be an error, or not, especially given that
#
# <threading>single
#
# might come from project's requirements.
unconditional = feature.expand(requirements.non_conditional())
context = context.refine(property_set.create(unconditional))
# We've collected properties that surely must be present in common
# properties. We now try to figure out what other properties
# should be added in order to satisfy rules (4)-(6) from the docs.
conditionals = property_set.create(requirements.conditional())
# It's supposed that #conditionals iterations
# should be enough for properties to propagate along conditions in any
# direction.
max_iterations = len(conditionals.all()) +\
len(requirements.get("<conditional>")) + 1
added_requirements = []
current = context
# It's assumed that ordinary conditional requirements can't add
# <indirect-conditional> properties, and that rules referred
# by <indirect-conditional> properties can't add new
# <indirect-conditional> properties. So the list of indirect conditionals
# does not change.
indirect = requirements.get("<conditional>")
ok = 0
for i in range(0, max_iterations):
e = conditionals.evaluate_conditionals(current).all()[:]
# Evaluate indirect conditionals.
for i in indirect:
i = b2.util.jam_to_value_maybe(i)
if callable(i):
# This is Python callable, yeah.
e.extend(i(current))
else:
# Name of bjam function. Because bjam is unable to handle
# list of Property, pass list of strings.
br = b2.util.call_jam_function(i[1:], [str(p) for p in current.all()])
if br:
e.extend(property.create_from_strings(br))
if e == added_requirements:
# If we got the same result, we've found final properties.
ok = 1
break
else:
# Oops, results of evaluation of conditionals has changed.
# Also 'current' contains leftover from previous evaluation.
# Recompute 'current' using initial properties and conditional
# requirements.
added_requirements = e
current = context.refine(property_set.create(feature.expand(e)))
if not ok:
self.manager().errors()("Can't evaluate conditional properties "
+ str(conditionals))
if what == "added":
return property_set.create(unconditional + added_requirements)
elif what == "refined":
return current
else:
self.manager().errors("Invalid value of the 'what' parameter")
def __common_properties2(self, build_request, requirements):
# This guarantees that default properties are present
# in result, unless they are overrided by some requirement.
# TODO: There is possibility that we've added <foo>bar, which is composite
# and expands to <foo2>bar2, but default value of <foo2> is not bar2,
# in which case it's not clear what to do.
#
build_request = build_request.add_defaults()
# Featured added by 'add-default' can be composite and expand
# to features without default values -- so they are not added yet.
# It could be clearer/faster to expand only newly added properties
# but that's not critical.
build_request = build_request.expand()
return self.evaluate_requirements(requirements, build_request,
"refined")
def match (self, property_set, debug):
""" Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'.
"""
# The condition is composed of all base non-conditional properties.
# It's not clear if we should expand 'self.requirements_' or not.
# For one thing, it would be nice to be able to put
# <toolset>msvc-6.0
# in requirements.
# On the other hand, if we have <variant>release in condition it
# does not make sense to require <optimization>full to be in
# build request just to select this variant.
bcondition = self.requirements_.base ()
ccondition = self.requirements_.conditional ()
condition = b2.util.set.difference (bcondition, ccondition)
if debug:
print " next alternative: required properties:", [str(p) for p in condition]
if b2.util.set.contains (condition, property_set.all()):
if debug:
print " matched"
return condition
else:
return None
def generate_dependency_targets (self, target_ids, property_set):
targets = []
usage_requirements = []
for id in target_ids:
result = generate_from_reference(id, self.project_, property_set)
targets += result.targets()
usage_requirements += result.usage_requirements().all()
return (targets, usage_requirements)
def generate_dependency_properties(self, properties, ps):
""" Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements).
"""
result_properties = []
usage_requirements = []
for p in properties:
result = generate_from_reference(p.value(), self.project_, ps)
for t in result.targets():
result_properties.append(property.Property(p.feature(), t))
usage_requirements += result.usage_requirements().all()
return (result_properties, usage_requirements)
@user_error_checkpoint
def generate (self, ps):
""" Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden.
"""
self.manager_.errors().push_user_context(
"Generating target " + self.full_name(), self.user_context_)
if self.manager().targets().logging():
self.manager().targets().log(
"Building target '%s'" % self.name_)
self.manager().targets().increase_indent ()
self.manager().targets().log(
"Build request: '%s'" % str (ps.raw ()))
cf = self.manager().command_line_free_features()
self.manager().targets().log(
"Command line free features: '%s'" % str (cf.raw ()))
self.manager().targets().log(
"Target requirements: %s'" % str (self.requirements().raw ()))
self.manager().targets().push_target(self)
if not self.generated_.has_key(ps):
# Apply free features form the command line. If user
# said
# define=FOO
# he most likely want this define to be set for all compiles.
ps = ps.refine(self.manager().command_line_free_features())
rproperties = self.common_properties (ps, self.requirements_)
self.manager().targets().log(
"Common properties are '%s'" % str (rproperties))
if rproperties.get("<build>") != ["no"]:
result = GenerateResult ()
properties = rproperties.non_dependency ()
(p, u) = self.generate_dependency_properties (rproperties.dependency (), rproperties)
properties += p
assert all(isinstance(p, property.Property) for p in properties)
usage_requirements = u
(source_targets, u) = self.generate_dependency_targets (self.sources_, rproperties)
usage_requirements += u
self.manager_.targets().log(
"Usage requirements for '%s' are '%s'" % (self.name_, usage_requirements))
# FIXME:
rproperties = property_set.create(properties + usage_requirements)
usage_requirements = property_set.create (usage_requirements)
self.manager_.targets().log(
"Build properties: '%s'" % str(rproperties))
source_targets += rproperties.get('<source>')
# We might get duplicate sources, for example if
# we link to two library which have the same <library> in
# usage requirements.
# Use stable sort, since for some targets the order is
# important. E.g. RUN_PY target need python source to come
# first.
source_targets = unique(source_targets, stable=True)
# FIXME: figure why this call messes up source_targets in-place
result = self.construct (self.name_, source_targets[:], rproperties)
if result:
assert len(result) == 2
gur = result [0]
result = result [1]
if self.always_:
for t in result:
t.always()
s = self.create_subvariant (
result,
self.manager().virtual_targets().recent_targets(), ps,
source_targets, rproperties, usage_requirements)
self.manager().virtual_targets().clear_recent_targets()
ur = self.compute_usage_requirements (s)
ur = ur.add (gur)
s.set_usage_requirements (ur)
self.manager_.targets().log (
"Usage requirements from '%s' are '%s'" %
(self.name(), str(rproperties)))
self.generated_[ps] = GenerateResult (ur, result)
else:
self.generated_[ps] = GenerateResult (property_set.empty(), [])
else:
# If we just see <build>no, we cannot produce any reasonable
# diagnostics. The code that adds this property is expected
# to explain why a target is not built, for example using
# the configure.log-component-configuration function.
# If this target fails to build, add <build>no to properties
# to cause any parent target to fail to build. Except that it
# - does not work now, since we check for <build>no only in
# common properties, but not in properties that came from
# dependencies
# - it's not clear if that's a good idea anyway. The alias
# target, for example, should not fail to build if a dependency
# fails.
self.generated_[ps] = GenerateResult(
property_set.create(["<build>no"]), [])
else:
self.manager().targets().log ("Already built")
self.manager().targets().pop_target()
self.manager().targets().decrease_indent()
return self.generated_[ps]
def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets.
"""
rproperties = subvariant.build_properties ()
xusage_requirements =self.evaluate_requirements(
self.usage_requirements_, rproperties, "added")
# We generate all dependency properties and add them,
# as well as their usage requirements, to result.
(r1, r2) = self.generate_dependency_properties(xusage_requirements.dependency (), rproperties)
extra = r1 + r2
result = property_set.create (xusage_requirements.non_dependency () + extra)
# Propagate usage requirements we've got from sources, except
# for the <pch-header> and <pch-file> features.
#
# That feature specifies which pch file to use, and should apply
# only to direct dependents. Consider:
#
# pch pch1 : ...
# lib lib1 : ..... pch1 ;
# pch pch2 :
# lib lib2 : pch2 lib1 ;
#
# Here, lib2 should not get <pch-header> property from pch1.
#
# Essentially, when those two features are in usage requirements,
# they are propagated only to direct dependents. We might need
# a more general mechanism, but for now, only those two
# features are special.
raw = subvariant.sources_usage_requirements().raw()
raw = property.change(raw, "<pch-header>", None);
raw = property.change(raw, "<pch-file>", None);
result = result.add(property_set.create(raw))
return result
def create_subvariant (self, root_targets, all_targets,
build_request, sources,
rproperties, usage_requirements):
"""Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- 'all-targets' all virtual
targets created while building this main target
- 'build-request' is property-set instance with
requested build properties"""
for e in root_targets:
e.root (True)
s = Subvariant (self, build_request, sources,
rproperties, usage_requirements, all_targets)
for v in all_targets:
if not v.creating_subvariant():
v.creating_subvariant(s)
return s
def construct (self, name, source_targets, properties):
""" Constructs the virtual targets for this abstract targets and
the dependecy graph. Returns a tuple consisting of the properties and the list of virtual targets.
Should be overrided in derived classes.
"""
raise BaseException ("method should be defined in derived classes")
class TypedTarget (BasicTarget):
import generators
def __init__ (self, name, project, type, sources, requirements, default_build, usage_requirements):
BasicTarget.__init__ (self, name, project, sources, requirements, default_build, usage_requirements)
self.type_ = type
def __jam_repr__(self):
return b2.util.value_to_jam(self)
def type (self):
return self.type_
def construct (self, name, source_targets, prop_set):
r = generators.construct (self.project_, os.path.splitext(name)[0],
self.type_,
prop_set.add_raw(['<main-target-type>' + self.type_]),
source_targets, True)
if not r:
print "warning: Unable to construct '%s'" % self.full_name ()
# Are there any top-level generators for this type/property set.
if not generators.find_viable_generators (self.type_, prop_set):
print "error: no generators were found for type '" + self.type_ + "'"
print "error: and the requested properties"
print "error: make sure you've configured the needed tools"
print "See http://boost.org/boost-build2/doc/html/bbv2/advanced/configuration.html"
print "To debug this problem, try the --debug-generators option."
sys.exit(1)
return r
def apply_default_build(property_set, default_build):
# 1. First, see what properties from default_build
# are already present in property_set.
specified_features = set(p.feature() for p in property_set.all())
defaults_to_apply = []
for d in default_build.all():
if not d.feature() in specified_features:
defaults_to_apply.append(d)
# 2. If there's any defaults to be applied, form the new
# build request. Pass it throw 'expand-no-defaults', since
# default_build might contain "release debug", which will
# result in two property_sets.
result = []
if defaults_to_apply:
# We have to compress subproperties here to prevent
# property lists like:
#
# <toolset>msvc <toolset-msvc:version>7.1 <threading>multi
#
# from being expanded into:
#
# <toolset-msvc:version>7.1/<threading>multi
# <toolset>msvc/<toolset-msvc:version>7.1/<threading>multi
#
# due to cross-product property combination. That may
# be an indication that
# build_request.expand-no-defaults is the wrong rule
# to use here.
compressed = feature.compress_subproperties(property_set.all())
result = build_request.expand_no_defaults(
b2.build.property_set.create([p]) for p in (compressed + defaults_to_apply))
else:
result.append (property_set)
return result
def create_typed_metatarget(name, type, sources, requirements, default_build, usage_requirements):
from b2.manager import get_manager
t = get_manager().targets()
project = get_manager().projects().current()
return t.main_target_alternative(
TypedTarget(name, project, type,
t.main_target_sources(sources, name),
t.main_target_requirements(requirements, project),
t.main_target_default_build(default_build, project),
t.main_target_usage_requirements(usage_requirements, project)))
def create_metatarget(klass, name, sources, requirements=[], default_build=[], usage_requirements=[]):
from b2.manager import get_manager
t = get_manager().targets()
project = get_manager().projects().current()
return t.main_target_alternative(
klass(name, project,
t.main_target_sources(sources, name),
t.main_target_requirements(requirements, project),
t.main_target_default_build(default_build, project),
t.main_target_usage_requirements(usage_requirements, project)))
def metatarget_function_for_class(class_):
@bjam_signature((["name"], ["sources", "*"], ["requirements", "*"],
["default_build", "*"], ["usage_requirements", "*"]))
def create_metatarget(name, sources, requirements = [], default_build = None, usage_requirements = []):
from b2.manager import get_manager
t = get_manager().targets()
project = get_manager().projects().current()
return t.main_target_alternative(
class_(name, project,
t.main_target_sources(sources, name),
t.main_target_requirements(requirements, project),
t.main_target_default_build(default_build, project),
t.main_target_usage_requirements(usage_requirements, project)))
return create_metatarget
| gpl-3.0 |
prashanthr/wakatime | wakatime/packages/pygments_py3/pygments/util.py | 29 | 11592 | # -*- coding: utf-8 -*-
"""
pygments.util
~~~~~~~~~~~~~
Utility functions.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import sys
split_path_re = re.compile(r'[/\\ ]')
doctype_lookup_re = re.compile(r'''(?smx)
(<\?.*?\?>)?\s*
<!DOCTYPE\s+(
[a-zA-Z_][a-zA-Z0-9]*
(?: \s+ # optional in HTML5
[a-zA-Z_][a-zA-Z0-9]*\s+
"[^"]*")?
)
[^>]*>
''')
tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?</.+?>(?uism)')
xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
class ClassNotFound(ValueError):
"""Raised if one of the lookup functions didn't find a matching class."""
class OptionError(Exception):
pass
def get_choice_opt(options, optname, allowed, default=None, normcase=False):
string = options.get(optname, default)
if normcase:
string = string.lower()
if string not in allowed:
raise OptionError('Value for option %s must be one of %s' %
(optname, ', '.join(map(str, allowed))))
return string
def get_bool_opt(options, optname, default=None):
string = options.get(optname, default)
if isinstance(string, bool):
return string
elif isinstance(string, int):
return bool(string)
elif not isinstance(string, string_types):
raise OptionError('Invalid type %r for option %s; use '
'1/0, yes/no, true/false, on/off' % (
string, optname))
elif string.lower() in ('1', 'yes', 'true', 'on'):
return True
elif string.lower() in ('0', 'no', 'false', 'off'):
return False
else:
raise OptionError('Invalid value %r for option %s; use '
'1/0, yes/no, true/false, on/off' % (
string, optname))
def get_int_opt(options, optname, default=None):
string = options.get(optname, default)
try:
return int(string)
except TypeError:
raise OptionError('Invalid type %r for option %s; you '
'must give an integer value' % (
string, optname))
except ValueError:
raise OptionError('Invalid value %r for option %s; you '
'must give an integer value' % (
string, optname))
def get_list_opt(options, optname, default=None):
val = options.get(optname, default)
if isinstance(val, string_types):
return val.split()
elif isinstance(val, (list, tuple)):
return list(val)
else:
raise OptionError('Invalid type %r for option %s; you '
'must give a list value' % (
val, optname))
def docstring_headline(obj):
if not obj.__doc__:
return ''
res = []
for line in obj.__doc__.strip().splitlines():
if line.strip():
res.append(" " + line.strip())
else:
break
return ''.join(res).lstrip()
def make_analysator(f):
"""Return a static text analyser function that returns float values."""
def text_analyse(text):
try:
rv = f(text)
except Exception:
return 0.0
if not rv:
return 0.0
try:
return min(1.0, max(0.0, float(rv)))
except (ValueError, TypeError):
return 0.0
text_analyse.__doc__ = f.__doc__
return staticmethod(text_analyse)
def shebang_matches(text, regex):
"""Check if the given regular expression matches the last part of the
shebang if one exists.
>>> from pygments.util import shebang_matches
>>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
True
>>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
True
>>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
False
>>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
False
>>> shebang_matches('#!/usr/bin/startsomethingwith python',
... r'python(2\.\d)?')
True
It also checks for common windows executable file extensions::
>>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
True
Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
the same as ``'perl -e'``)
Note that this method automatically searches the whole string (eg:
the regular expression is wrapped in ``'^$'``)
"""
index = text.find('\n')
if index >= 0:
first_line = text[:index].lower()
else:
first_line = text.lower()
if first_line.startswith('#!'):
try:
found = [x for x in split_path_re.split(first_line[2:].strip())
if x and not x.startswith('-')][-1]
except IndexError:
return False
regex = re.compile('^%s(\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE)
if regex.search(found) is not None:
return True
return False
def doctype_matches(text, regex):
"""Check if the doctype matches a regular expression (if present).
Note that this method only checks the first part of a DOCTYPE.
eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
"""
m = doctype_lookup_re.match(text)
if m is None:
return False
doctype = m.group(2)
return re.compile(regex, re.I).match(doctype.strip()) is not None
def html_doctype_matches(text):
"""Check if the file looks like it has a html doctype."""
return doctype_matches(text, r'html')
_looks_like_xml_cache = {}
def looks_like_xml(text):
"""Check if a doctype exists or if we have some tags."""
if xml_decl_re.match(text):
return True
key = hash(text)
try:
return _looks_like_xml_cache[key]
except KeyError:
m = doctype_lookup_re.match(text)
if m is not None:
return True
rv = tag_re.search(text[:1000]) is not None
_looks_like_xml_cache[key] = rv
return rv
# Python narrow build compatibility
def _surrogatepair(c):
# Given a unicode character code
# with length greater than 16 bits,
# return the two 16 bit surrogate pair.
# From example D28 of:
# http://www.unicode.org/book/ch03.pdf
return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
def unirange(a, b):
"""Returns a regular expression string to match the given non-BMP range."""
if b < a:
raise ValueError("Bad character range")
if a < 0x10000 or b < 0x10000:
raise ValueError("unirange is only defined for non-BMP ranges")
if sys.maxunicode > 0xffff:
# wide build
return u'[%s-%s]' % (unichr(a), unichr(b))
else:
# narrow build stores surrogates, and the 're' module handles them
# (incorrectly) as characters. Since there is still ordering among
# these characters, expand the range to one that it understands. Some
# background in http://bugs.python.org/issue3665 and
# http://bugs.python.org/issue12749
#
# Additionally, the lower constants are using unichr rather than
# literals because jython [which uses the wide path] can't load this
# file if they are literals.
ah, al = _surrogatepair(a)
bh, bl = _surrogatepair(b)
if ah == bh:
return u'(?:%s[%s-%s])' % (unichr(ah), unichr(al), unichr(bl))
else:
buf = []
buf.append(u'%s[%s-%s]' %
(unichr(ah), unichr(al),
ah == bh and unichr(bl) or unichr(0xdfff)))
if ah - bh > 1:
buf.append(u'[%s-%s][%s-%s]' %
unichr(ah+1), unichr(bh-1), unichr(0xdc00), unichr(0xdfff))
if ah != bh:
buf.append(u'%s[%s-%s]' %
(unichr(bh), unichr(0xdc00), unichr(bl)))
return u'(?:' + u'|'.join(buf) + u')'
def format_lines(var_name, seq, raw=False, indent_level=0):
"""Formats a sequence of strings for output."""
lines = []
base_indent = ' ' * indent_level * 4
inner_indent = ' ' * (indent_level + 1) * 4
lines.append(base_indent + var_name + ' = (')
if raw:
# These should be preformatted reprs of, say, tuples.
for i in seq:
lines.append(inner_indent + i + ',')
else:
for i in seq:
# Force use of single quotes
r = repr(i + '"')
lines.append(inner_indent + r[:-2] + r[-1] + ',')
lines.append(base_indent + ')')
return '\n'.join(lines)
def duplicates_removed(it, already_seen=()):
"""
Returns a list with duplicates removed from the iterable `it`.
Order is preserved.
"""
lst = []
seen = set()
for i in it:
if i in seen or i in already_seen:
continue
lst.append(i)
seen.add(i)
return lst
class Future(object):
"""Generic class to defer some work.
Handled specially in RegexLexerMeta, to support regex string construction at
first use.
"""
def get(self):
raise NotImplementedError
def guess_decode(text):
"""Decode *text* with guessed encoding.
First try UTF-8; this should fail for non-UTF-8 encodings.
Then try the preferred locale encoding.
Fall back to latin-1, which always works.
"""
try:
text = text.decode('utf-8')
return text, 'utf-8'
except UnicodeDecodeError:
try:
import locale
prefencoding = locale.getpreferredencoding()
text = text.decode()
return text, prefencoding
except (UnicodeDecodeError, LookupError):
text = text.decode('latin1')
return text, 'latin1'
def guess_decode_from_terminal(text, term):
"""Decode *text* coming from terminal *term*.
First try the terminal encoding, if given.
Then try UTF-8. Then try the preferred locale encoding.
Fall back to latin-1, which always works.
"""
if getattr(term, 'encoding', None):
try:
text = text.decode(term.encoding)
except UnicodeDecodeError:
pass
else:
return text, term.encoding
return guess_decode(text)
def terminal_encoding(term):
"""Return our best guess of encoding for the given *term*."""
if getattr(term, 'encoding', None):
return term.encoding
import locale
return locale.getpreferredencoding()
# Python 2/3 compatibility
if sys.version_info < (3, 0):
unichr = unichr
xrange = xrange
string_types = (str, unicode)
text_type = unicode
u_prefix = 'u'
iteritems = dict.iteritems
itervalues = dict.itervalues
import StringIO, cStringIO
# unfortunately, io.StringIO in Python 2 doesn't accept str at all
StringIO = StringIO.StringIO
BytesIO = cStringIO.StringIO
else:
unichr = chr
xrange = range
string_types = (str,)
text_type = str
u_prefix = ''
iteritems = dict.items
itervalues = dict.values
from io import StringIO, BytesIO
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
| bsd-3-clause |
mamachanko/2048 | setup.py | 1 | 1146 | from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
setup(name='python-2048a',
description='A game engine for 2048',
author='Max Brauer',
author_email='max@rootswiseyouths.com',
url='http://github.com/mamachanko/2048',
packages=find_packages(),
tests_require=['pytest'],
cmdclass={'test': PyTest},
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Games/Entertainment :: Board Games",
"Intended Audience :: Developers",
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"])
| mit |
karllessard/tensorflow | tensorflow/python/data/experimental/service/__init__.py | 7 | 7017 | # Copyright 2020 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.
# ==============================================================================
"""API for using the tf.data service.
This module contains:
1. tf.data server implementations for running the tf.data service.
2. A `distribute` dataset transformation that moves a dataset's preprocessing
to happen in the tf.data service.
The tf.data service offers a way to improve training speed when the host
attached to a training device can't keep up with the data consumption of the
model. For example, suppose a host can generate 100 examples/second, but the
model can process 200 examples/second. Training speed could be doubled by using
the tf.data service to generate 200 examples/second.
## Before using the tf.data service
There are a few things to do before using the tf.data service to speed up
training.
### Understand processing_mode
The tf.data service uses a cluster of workers to prepare data for training your
model. The `processing_mode` argument to
`tf.data.experimental.service.distribute` describes how to leverage multiple
workers to process the input dataset. Currently, there are two processing modes
to choose from: "distributed_epoch" and "parallel_epochs".
"distributed_epoch" means that the dataset will be split across all tf.data
service workers. The dispatcher produces "splits" for the dataset and sends them
to workers for further processing. For example, if a dataset begins with a list
of filenames, the dispatcher will iterate through the filenames and send the
filenames to tf.data workers, which will perform the rest of the dataset
transformations on those files. "distributed_epoch" is useful when your model
needs to see each element of the dataset exactly once, or if it needs to see the
data in a generally-sequential order. "distributed_epoch" only works for
datasets with splittable sources, such as `Dataset.from_tensor_slices`,
`Dataset.list_files`, or `Dataset.range`.
"parallel_epochs" means that the entire input dataset will be processed
independently by each of the tf.data service workers. For this
reason, it is important to shuffle data (e.g. filenames) non-deterministically,
so that each worker will process the elements of the dataset in a different
order. "parallel_epochs" can be used to distribute datasets that aren't
splittable.
### Measure potential impact
Before using the tf.data service, it is useful to first measure the potential
performance improvement. To do this, add
```
dataset = dataset.take(1).cache().repeat()
```
at the end of your dataset, and see how it affects your model's step time.
`take(1).cache().repeat()` will cache the first element of your dataset and
produce it repeatedly. This should make the dataset very fast, so that the model
becomes the bottleneck and you can identify the ideal model speed. With enough
workers, the tf.data service should be able to achieve similar speed.
## Running the tf.data service
tf.data servers should be brought up alongside your training jobs, and brought
down when the jobs are finished. The tf.data service uses one `DispatchServer`
and any number of `WorkerServers`. See
https://github.com/tensorflow/ecosystem/tree/master/data_service for an example
of using Google Kubernetes Engine (GKE) to manage the tf.data service. The
server implementation in
[tf_std_data_server.py](https://github.com/tensorflow/ecosystem/blob/master/data_service/tf_std_data_server.py)
is not GKE-specific, and can be used to run the tf.data service in other
contexts.
### Fault tolerance
By default, the tf.data dispatch server stores its state in-memory, making it a
single point of failure during training. To avoid this, pass
`fault_tolerant_mode=True` when creating your `DispatchServer`. Dispatcher
fault tolerance requires `work_dir` to be configured and accessible from the
dispatcher both before and after restart (e.g. a GCS path). With fault tolerant
mode enabled, the dispatcher will journal its state to the work directory so
that no state is lost when the dispatcher is restarted.
WorkerServers may be freely restarted, added, or removed during training. At
startup, workers will register with the dispatcher and begin processing all
outstanding jobs from the beginning.
## Using the tf.data service from your training job
Once you have a tf.data service cluster running, take note of the dispatcher IP
address and port. To connect to the service, you will use a string in the format
"grpc://<dispatcher_address>:<dispatcher_port>".
```
# Create the dataset however you were before using the tf.data service.
dataset = your_dataset_factory()
service = "grpc://{}:{}".format(dispatcher_address, dispatcher_port)
# This will register the dataset with the tf.data service cluster so that
# tf.data workers can run the dataset to produce elements. The dataset returned
# from applying `distribute` will fetch elements produced by tf.data workers.
dataset = dataset.apply(tf.data.experimental.service.distribute(
processing_mode="parallel_epochs", service=service))
```
Below is a toy example that you can run yourself.
>>> dispatcher = tf.data.experimental.service.DispatchServer()
>>> dispatcher_address = dispatcher.target.split("://")[1]
>>> worker = tf.data.experimental.service.WorkerServer(
... tf.data.experimental.service.WorkerConfig(
... dispatcher_address=dispatcher_address))
>>> dataset = tf.data.Dataset.range(10)
>>> dataset = dataset.apply(tf.data.experimental.service.distribute(
... processing_mode="parallel_epochs", service=dispatcher.target))
>>> print(list(dataset.as_numpy_iterator()))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
See the documentation of `tf.data.experimental.service.distribute` for more
details about using the `distribute` transformation.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops.data_service_ops import distribute
from tensorflow.python.data.experimental.ops.data_service_ops import from_dataset_id
from tensorflow.python.data.experimental.ops.data_service_ops import register_dataset
from tensorflow.python.data.experimental.service.server_lib import DispatcherConfig
from tensorflow.python.data.experimental.service.server_lib import DispatchServer
from tensorflow.python.data.experimental.service.server_lib import WorkerConfig
from tensorflow.python.data.experimental.service.server_lib import WorkerServer
| apache-2.0 |
buchwj/xvector | server/setup.py | 1 | 2321 | #!/usr/bin/env python
# xVector Engine Server
# Copyright (c) 2011 James Buchwald
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from distutils.core import setup
long_description = "The xVector Engine is an open source 2D MMORPG engine "
long_description += "programmed in Python. xVector makes it easy to create "
long_description += "and distribute your own MMORPG with no programming "
long_description += "experience while also providing developers with a "
long_description += "powerful plugin and scripting API. This package provides"
long_description += " the server application for the engine."
setup(name='xVServer',
author='James R. Buchwald',
author_email='buchwj@rpi.edu',
version='0.0.1',
description='Server for the xVector MMORPG Engine',
long_description=long_description,
url='http://www.xvector.org',
license='GPLv2',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Topic :: Games/Entertainment",
"Topic :: Games/Entertainment :: Multi-User Dungeons (MUD)",
"Topic :: Games/Entertainment :: Role-Playing",
],
packages=['xVServer', 'xVServer.Models'],
data_files=[('', ['LICENSE', 'CREDITS']),
('config', ['config/*.xml'])],
scripts=['bin/xVServer.py', 'bin/xVManageDB.py'],
provides=['xVServer'],
requires=['xVLib (==0.0.1)'],
)
| gpl-3.0 |
cheery/essence | essence2/fields.py | 1 | 3279 | from essence2 import clamp
class ListField(object):
def __init__(self, items, name=''):
self.items = items
self.name = name
self.stamp = 0
def __getitem__(self, key):
return self.items[key]
def __setitem__(self, key, value):
self.items[key] = value
self.stamp += 1
def __iter__(self):
return iter(self.items)
def __len__(self):
return len(self.items)
def rename(self, name):
self.name = name
self.stamp += 1
def resolve(self, field):
if self == field:
return []
for subfield in self:
response = subfield.resolve(field)
if response != None:
return [self] + response
def index(self, field):
return self.items.index(field)
def contextof(self, field):
if self == field:
return ()
for index, subfield in enumerate(self):
if subfield == None:
continue
res = subfield.contextof(field)
if res != None:
return ((self, index),) + res
class TextField(object):
def __init__(self, text, name=''):
self.text = text
self.name = name
self.stamp = 0
def __getitem__(self, key):
return self.text[key]
def __setitem__(self, key, value):
key = key if isinstance(key, slice) else slice(key, key)
prefix = self.text[:key.start]
suffix = self.text[key.stop:]
self.text = prefix + value + suffix
self.stamp += 1
def __iter__(self):
return iter(self.text)
def __len__(self):
return len(self.text)
def rename(self, name):
self.name = name
self.stamp += 1
def resolve(self, field):
if self == field:
return []
def __str__(self):
return self.text
def contextof(self, field):
if self == field:
return ()
else:
return None
class Selection(object):
def __init__(self, field, head, tail):
self.field = field
self.head = head
self.tail = tail
def _get_start(self):
if self.tail < self.head:
return self.tail
else:
return self.head
def _set_start(self, value):
if self.tail < self.head:
self.tail = value
else:
self.head = value
start = property(_get_start, _set_start)
def _get_stop(self):
if self.tail < self.head:
return self.head
else:
return self.tail
def _set_stop(self, value):
if self.tail < self.head:
self.head = value
else:
self.tail = value
stop = property(_get_stop, _set_stop)
def replace(self, data):
if isinstance(self.field, ListField):
if self.head == self.tail and not self.field.name.endswith('*'):
self.move(self.head+1, True)
self.field[self.start:self.stop] = data
self.head = self.tail = self.start + len(data)
def move(self, position, drag):
index = clamp(0, len(self.field), position)
if drag:
self.head = index
else:
self.head = self.tail = index
| gpl-3.0 |
ckjbgames/textventure | bin/textventure.py | 1 | 13576 | #!/usr/bin/env python
# textventure.py
#################
## Textventure ##
## ckjbgames ####
## 2017 #########
#################
## Imports
import random # Map randomization
import pickle # For game saving
import sys # Various uses
import socket # Eventually for connections
import MySQLdb # For connecting to MySQL
import json # Decode JSON in MySQL
import os # Save files, etc.
import tty # "Press any key to continue..."
## Classes
class gameItem(object):
"""
An in-game item that can
be used by the player and will
be placed randomly in the rooms
Instances are stored in the Inventory class
Name is the item's name
Effect should be an instance of the Effect class
If Uses is set to true, an item lasts forever
If Uses is set to one, an item has one use, etc.
Uses should NOT be set to false!
Description is self-explainatory
"""
def __init__(self, name = None, effect = None, uses = None, description = None, movable = True, can_hold = True):
"""
This is just an initialzer with a docstring
"""
self.name = name
self.effect = effect
self.uses = uses
self.description = description
self.movable = movable
self.can_hold = can_hold
def __repr__(self):
"""
Prints out an item's attributes in an actually readable format
See the main docstring for more info on the main attributes
"""
uses = self.uses
if uses == True:
uses = "*lasts forever*"
template = "\n%s" +\
"\nEffect:" +\
"\n%s" +\
"\nUses:" +\
"\n%s" +\
"\nDescription:" +\
"\n%s"
return template%(self.name, self.effect, uses, self.description)
def itemName(self):
"""
Used for returning only the item's name (for room descriptions and
inventory listings)
"""
return self.name
def MySQLformat(self):
return [self.name,
self.effect,
self.uses,
self.description,
self.movable,
self.can_hold]
class Inventory(object):
"""
The player's inventory
Contains instances of the gameItem class
"""
def __init__(self):
"""
Initialize the inventory to an empty dictionary
"""
self.player_inventory = {}
def __repr__(self):
"""
A separate __repr__ method so that all the
full attributes of each item are not shown
in the inventory listing.
Basically a plain old inventory listing
"""
if self.player_inventory == {}:
eggs = "You're not carrying anything."
else:
eggs = ''
for spam in self.player_inventory:
eggs = eggs + '\n' + spam.itemName()
return eggs
def addItem(self, item_to_add):
"""
Adds an item to the inventory
item_to_add should be an instance of
the gameItem class
"""
self.player_inventory[item_to_add.itemName()] = item_to_add
def viewItem(self,item_name):
"""
View an item in the inventory
Should be the name of an item
"""
try:
return self.player_inventory[item_name]
except (NameError, KeyError):
return "You don't have that item!"
def toJSON(self):
return json.dumps(self,default=lambda o: o.__dict__,
sort_keys=True)
class Room(object):
"""
A room with a description, other rooms that it leads to,
and contents
name is self-explainatory
items_room is a dictionary containing instances of the gameItem class that are in a room
If items_room is set to false, the room contains no items.
description is also self-explainatory
in_room is a flag for if you are in the room or not
"""
def __init__(self, name = None, items_room = False, description = None, in_room = False):
"""
Initializes attributes described in the main docstring
"""
self.name = name
self.items_room = items_room
self.description = description
self.in_room = in_room
def changeFlag(self, val):
"""
Change in_room flag
Possible fix for an issue
"""
self.in_room = val
def toJSON(self):
return json.dumps(self,default=lambda o: o.__dict__,
sort_keys=True)
class allRooms(object):
"""
A map-type arrangement of all rooms as a 2-dimensional list/array
More effective than having a really, really complicated
initializer method for the Room class
The player will never actually view this unless they have a map
There is a __repr__ method in case they do
"""
def __init__(self, rooms = [],coords = (0,0)):
"""
Initializer method
rooms should be a list containing other lists, which
should be a combination of instances of Room and
the False value
See the main docstring for more info
"""
self.rooms = rooms
self.coords = coords
def __repr__(self):
"""
Kind of displays a map
# - A room, but you are not in it
Space - There is no room here
@ - You are here
"""
map_of = ''
for row in self.rooms:
for room in row:
if room == False:
map_of += ' '
elif room.in_room == True:
map_of += '@'
else:
map_of += '#'
map_of += '\r\n' # In case of Windows
return map_of
def move(self, direction = 8):
"""
A method for moving to another room
Uses a try-except block for determining
if there is a room that can be entered from
the specified direction
These directions are based on the number pad
So:
7 8 9
\ | /
4 - 5 - 6
/ | \
1 2 3
In other words:
8 - North
2 - South
4 - West
6 - East
A map of the game kind of looks like
corridors in Nethack :)
"""
if direction == 8 or direction == 'n':
try:
if isinstance(self.rooms[self.coords[0] - 1][self.coords[1]],Room):
self.rooms[self.coords[0]][self.coords[1]].changeFlag(False)
self.rooms[self.coords[0] - 1][self.coords[1]].changeFlag(True)
self.coords =(self.coords[0] - 1,self.coords[1])
else:
raise NoRoom
except (IndexError,NoRoom,AttributeError):
return "There is no room to enter in this direction!"
elif direction == 2 or direction == 's':
try:
if isinstance(self.rooms[self.coords[0] + 1][self.coords[1]],Room):
self.rooms[self.coords[0]][self.coords[1]].changeFlag(False)
self.rooms[self.coords[0] + 1][self.coords[1]].changeFlag(True)
self.coords = (self.coords[0] + 1,self.coords[1])
else:
raise NoRoom
except (IndexError,NoRoom,AttributeError):
return "There is no room to enter in this direction!"
elif direction == 4 or direction == 'w':
try:
if isinstance(self.rooms[self.coords[0]][self.coords[1] - 1],Room):
self.rooms[self.coords[0]][self.coords[1]].changeFlag(False)
self.rooms[self.coords[0]][self.coords[1] - 1].changeFlag(True)
self.coords = (self.coords[0],self.coords[1] - 1)
else:
raise NoRoom
except (IndexError,NoRoom,AttributeError):
return "There is no room to enter in this direction!"
elif direction == 6 or direction == 'e':
try:
if isinstance(self.rooms[self.coords[0]][self.coords[1] + 1],Room):
self.rooms[self.coords[0]][self.coords[1]].changeFlag(False)
self.rooms[self.coords[0]][self.coords[1] + 1].changeFlag(True)
self.coords =(self.coords[0], self.coords[1] + 1)
else:
raise NoRoom
except (IndexError,NoRoom,AttributeError):
return "There is no room to enter in this direction!"
else:
return "Sorry, that's not a valid direction."
def randomgen(self):
"""
For random generation of a map
Will eventually use MySQL to find item templates
"""
possible = [False, Room('spam',False,'Too many eggs!',False)] # Possibilities for a room; will be updated soon
size = (random.randint(10,25),random.randint(10,25)) # Make the map size anywhere from 10x10 to 25x25
new_rooms = [] # An empty list that new rooms that will be created
for x in range(size[0]): # Start a for loop
row = [] # Make an empty list that will be appended to
for y in range(size[1]): # Start another for loop
row.append(random.choice(possible)) # Append another room or empty space to the current row
new_rooms.append(row) # Append the row to new_rooms
self.rooms = new_rooms # Assign new_rooms to the attribute self.rooms
class NoRoom(Exception):
"""
An exception for the absence of a room to enter
"""
pass
class Controller(object):
"""
Purposes:
1. Loads and saves games using pickle
Store save files by default in
/var/games/textventure/saves
See "Installation" in the Wiki for more
2. Performs some functions having to do with
interactions between the player and the environment
3. Executes textventure commands the player inputs
"""
def __init__(self,inventory = None,allrooms = None):
self.game = [inventory,allrooms]
self.inv,self.allrooms=self.game
def loadgame(self,username = None):
"""
Loads a game with pickle.load
A save file should be in the /var/games/textventure/saves directory
The extension doesn't matter, but I have decided to use *.pickle
"""
print 'Loading game...'
try:
with open('/var/games/textventure/saves/%s.pickle'%(username),'r') as f:
self.game = pickle.load(f)
self.inv,self.allrooms=self.game
except EnvironmentError:
print 'The game could not be loaded. Sorry about that.'
pressanykey()
sys.exit()
else:
print 'Success!'
return self.game
def savegame(self,username = None):
"""
Save a game with pickle.dump
Save file path is mentioned in the docs of loadgame()
"""
print 'Saving game...'
try:
with open('/var/games/textventure/saves/%s.pickle'%(username),'w') as f:
pickle.dump(self.game,f)
print 'Game saved!'
quitconfirm=raw_input('Do you wish to quit (y/n)? ')
if quitconfirm[0] == 'y' or quitconfirm[0] == 'Y':
pressanykey()
sys.exit()
elif quitconfirm[0] == 'n' or quitconfirm[0] == 'N':
print 'Please do continue, good player!'
else:
print "I don't think that's a yes or a no."
pressanykey()
except EnvironmentError:
print 'The game could not be saved. Sorry about that.'
pressanykey()
sys.exit()
else:
print 'Success!'
def commands(self):
"""
Interpret commands.
It's actually pretty simple.
"""
prompt='textventure$ '
command_list=['l','i','p','d','m','u','h','S']
while True:
typed=raw_input(prompt).split(' ')
command=typed[0]
arg=typed[1:]
if command in command_list:
if command == 'l':
print self.allrooms.rooms[self.allrooms.coords[1]][self.allrooms.coords[0]].
## Functions
def pressanykey():
print 'Press any key to continue...'
tty.setraw(1)
sys.stdin.read(1)
## Main Program
if __name__ == '__main__':
control=Controller('','')
username=sys.argv[1]
savepath="/var/games/textventure/saves/%s.pickle"%(username)
if os.path.exists(savepath):
inv,allrooms=control.loadgame(username)
else:
open(savepath,'a').close() # .close() could be omitted, but only in CPython.
# It was kept so it will work in other implementations.
| mit |
stefanopanella/xapi-storage-plugins | volume/org.xen.xapi.storage.gfs2/fence_tool.py | 1 | 5328 | #!/usr/bin/env python
import os
import sys
import time
from xapi.storage import log
from xapi.storage.libs import util
from xapi.storage.common import call
import xapi.storage.libs.poolhelper
import mmap
import signal
import pickle
import shelve
import fcntl
import struct
BLK_SIZE = 512
MSG_OK = '\x00'
MSG_FENCE = '\x01'
MSG_FENCE_ACK = '\x02'
WD_TIMEOUT = 60
DLMREF = "/var/run/sr-ref/dlmref"
DLMREF_LOCK = "/var/run/sr-ref/dlmref.lock"
IOCWD = 0xc0045706
def demonize():
for fd in [0, 1, 2]:
try:
os.close(fd)
except OSError:
pass
def block_read(bd, offset):
f = os.open(bd, os.O_RDONLY)
os.lseek(f, offset, os.SEEK_SET)
s = os.read(f, BLK_SIZE)
os.close(f)
return s[0]
def block_write(bd, offset, msg):
f = os.open(bd, os.O_RDWR | os.O_DIRECT)
os.lseek(f, offset, os.SEEK_SET)
m = mmap.mmap(-1, BLK_SIZE)
m[0] = msg
os.write(f, m)
os.close(f)
def dlm_fence_daemon(node_id):
n = int(node_id)
log.debug("Starting dlm_fence_daemon on node_id=%d" % n)
wd = os.open("/dev/watchdog", os.O_WRONLY)
def dlm_fence_daemon_signal_handler(sig, frame):
log.debug("dlm_fence_daemon_signal_handler")
os.write(wd, "V")
os.close(wd)
log.debug("dlm_fence_daemon: exiting cleanly")
exit(0)
signal.signal(signal.SIGUSR1, dlm_fence_daemon_signal_handler)
demonize()
while True:
f = util.lock_file("SSSS", DLMREF_LOCK, "r+")
d = shelve.open(DLMREF)
klist = d.keys()
for key in klist:
bd = "/dev/" + key + "/sbd"
ret = block_read(bd, BLK_SIZE * 2 * n)
if ret == MSG_OK:
pass
elif ret == MSG_FENCE:
log.debug("dlm_fence_daemon: MSG_FENCE")
log.debug("dlm_fence_daemon: Setting WD timeout to 1 second")
s = struct.pack ("i", 1)
fcntl.ioctl(wd, 3221509894 , s)
log.debug("dlm_fence_daemon: writing MSG_FENCE_ACK")
ret = block_write(bd, BLK_SIZE * ((2 * n) + 1), MSG_FENCE_ACK)
log.debug("dlm_fence_daemon: MSG_FENCE_ACK sent")
# host will be fenced in 1 second
d.close()
util.unlock_file("SSSS", f)
os.write(wd, "w")
time.sleep(1)
def dlm_fence_node(node_id):
n = int(node_id)
log.debug("dlm_fence_node node_id=%d" % n)
f = util.lock_file("dlm_fence_node", DLMREF_LOCK, "r+")
d = shelve.open(DLMREF)
klist = d.keys()
for key in klist:
bd = "/dev/" + key + "/sbd"
ret = block_write(bd, BLK_SIZE * 2 * n, MSG_FENCE)
d.close()
util.unlock_file("dlm_fence_node", f)
# Wait for an ACK for WD_TIMEOUT + 10 seconds or assume
# node has been fenced
for i in range(1, WD_TIMEOUT + 10):
f = util.lock_file("dlm_fence_node", DLMREF_LOCK, "r+")
d = shelve.open(DLMREF)
klist = d.keys()
for key in klist:
bd = "/dev/" + key + "/sbd"
ret = block_read(bd, BLK_SIZE * ((2 * n) + 1))
if ret == MSG_FENCE_ACK:
log.debug("dlm_fence_node got MSG_FENCE_ACK for node_id=%d" % n)
time.sleep(2)
util.unlock_file("dlm_fence_node", f)
exit(0)
d.close()
util.unlock_file("dlm_fence_node", f)
time.sleep(1)
log.debug("dlm_fence_node ACKING FENCE after TIMEOUT for node_id=%d" % n)
def dlm_fence_clear_by_id(node_id, scsi_id):
n = int(node_id)
bd = "/dev/" + scsi_id + "/sbd"
log.debug("dlm_fence_clear_by_id: clearing node_id=%d, scsi_id=%s" %
(n, scsi_id))
ret = block_write(bd, BLK_SIZE * 2 * n, MSG_OK)
ret = block_write(bd, BLK_SIZE * ((2 * n) + 1), MSG_OK)
def dlm_fence_daemon_stop(node_id):
with open("/var/run/sr-ref/dlm_fence_daemon.pickle") as f:
dlm_fence_daemon = pickle.load(f)
dlm_fence_daemon.send_signal(signal.SIGUSR1)
dlm_fence_daemon.wait()
os.unlink("/var/run/sr-ref/dlm_fence_daemon.pickle")
return
def dlm_fence_daemon_start(node_id):
import subprocess
args = ['/usr/libexec/xapi-storage-script/volume/org.xen.xapi.storage.gfs2/fence_tool.py',
"dlm_fence_daemon", str(node_id)]
dlm_fence_daemon = subprocess.Popen(args)
log.debug("dlm_fence_daemon_start: node_id=%d" % node_id)
with open("/var/run/sr-ref/dlm_fence_daemon.pickle", 'w+') as f:
pickle.dump(dlm_fence_daemon, f)
def dlm_fence_no_args():
log.debug("dlm_fence_no_args")
for line in sys.stdin:
log.debug("dlm_fence_no_args: %s" % line)
if line.startswith("node="):
node_id = int(int(line[5:]) % 4096)
dlm_fence_node(node_id)
if __name__ == "__main__":
if len(sys.argv) == 1:
dlm_fence_no_args()
else:
cmd = sys.argv[1]
if cmd == "dlm_fence_daemon":
dlm_fence_daemon(sys.argv[2])
elif cmd == "dlm_fence_daemon_stop":
dlm_fence_daemon_stop(sys.argv[2])
elif cmd == "dlm_fence_node":
dlm_fence_node(sys.argv[2])
elif cmd == "dlm_fence_clear_by_id":
dlm_fence_clear_by_id(sys.argv[2], sys.argv[3])
elif cmd == "dlm_fence_print":
dlm_fence_print()
| lgpl-2.1 |
lipengyu/django-bootstrap | tests/xtests/view_base/tests.py | 8 | 2169 |
from django.contrib.auth.models import User
from xtests.base import BaseTest
from xadmin.views import BaseAdminView, BaseAdminPlugin, ModelAdminView, ListAdminView
from models import ModelA, ModelB
from adminx import site, ModelAAdmin, TestBaseView, TestCommView, TestAView, OptionA
class BaseAdminTest(BaseTest):
def setUp(self):
super(BaseAdminTest, self).setUp()
self.test_view_class = site.get_view_class(TestBaseView)
self.test_view = self.test_view_class(self._mocked_request('test/'))
def test_get_view(self):
test_a = self.test_view.get_view(TestAView, OptionA, opts={'test_attr': 'test'})
self.assertTrue(isinstance(test_a, TestAView))
self.assertTrue(isinstance(test_a, OptionA))
self.assertEqual(test_a.option_attr, 'option_test')
self.assertEqual(test_a.test_attr, 'test')
def test_model_view(self):
test_model = self.test_view.get_model_view(ListAdminView, ModelA)
self.assertTrue(isinstance(test_model, ModelAAdmin))
self.assertEqual(test_model.model, ModelA)
self.assertEqual(test_model.test_model_attr, 'test_model')
def test_admin_url(self):
test_url = self.test_view.get_admin_url('test')
self.assertEqual(test_url, '/view_base/test/base')
def test_model_url(self):
test_url = self.test_view.get_model_url(ModelA, 'list')
self.assertEqual(test_url, '/view_base/view_base/modela/list')
def test_has_model_perm(self):
test_user = User.objects.create(username='test_user')
self.assertFalse(self.test_view.has_model_perm(ModelA, 'change', test_user))
# Admin User
self.assertTrue(self.test_view.has_model_perm(ModelA, 'change'))
class CommAdminTest(BaseTest):
def setUp(self):
super(CommAdminTest, self).setUp()
self.test_view_class = site.get_view_class(TestCommView)
self.test_view = self.test_view_class(self._mocked_request('test/comm'))
def test_model_icon(self):
self.assertEqual(self.test_view.get_model_icon(ModelA), 'flag')
self.assertEqual(self.test_view.get_model_icon(ModelB), 'test')
| bsd-3-clause |
semonte/intellij-community | python/lib/Lib/site-packages/django/contrib/gis/geos/tests/test_io.py | 321 | 4159 | import binascii, ctypes, unittest
from django.contrib.gis.geos import GEOSGeometry, WKTReader, WKTWriter, WKBReader, WKBWriter, geos_version_info
class GEOSIOTest(unittest.TestCase):
def test01_wktreader(self):
# Creating a WKTReader instance
wkt_r = WKTReader()
wkt = 'POINT (5 23)'
# read() should return a GEOSGeometry
ref = GEOSGeometry(wkt)
g1 = wkt_r.read(wkt)
g2 = wkt_r.read(unicode(wkt))
for geom in (g1, g2):
self.assertEqual(ref, geom)
# Should only accept basestring objects.
self.assertRaises(TypeError, wkt_r.read, 1)
self.assertRaises(TypeError, wkt_r.read, buffer('foo'))
def test02_wktwriter(self):
# Creating a WKTWriter instance, testing its ptr property.
wkt_w = WKTWriter()
self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type())
ref = GEOSGeometry('POINT (5 23)')
ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
self.assertEqual(ref_wkt, wkt_w.write(ref))
def test03_wkbreader(self):
# Creating a WKBReader instance
wkb_r = WKBReader()
hex = '000000000140140000000000004037000000000000'
wkb = buffer(binascii.a2b_hex(hex))
ref = GEOSGeometry(hex)
# read() should return a GEOSGeometry on either a hex string or
# a WKB buffer.
g1 = wkb_r.read(wkb)
g2 = wkb_r.read(hex)
for geom in (g1, g2):
self.assertEqual(ref, geom)
bad_input = (1, 5.23, None, False)
for bad_wkb in bad_input:
self.assertRaises(TypeError, wkb_r.read, bad_wkb)
def test04_wkbwriter(self):
wkb_w = WKBWriter()
# Representations of 'POINT (5 23)' in hex -- one normal and
# the other with the byte order changed.
g = GEOSGeometry('POINT (5 23)')
hex1 = '010100000000000000000014400000000000003740'
wkb1 = buffer(binascii.a2b_hex(hex1))
hex2 = '000000000140140000000000004037000000000000'
wkb2 = buffer(binascii.a2b_hex(hex2))
self.assertEqual(hex1, wkb_w.write_hex(g))
self.assertEqual(wkb1, wkb_w.write(g))
# Ensuring bad byteorders are not accepted.
for bad_byteorder in (-1, 2, 523, 'foo', None):
# Equivalent of `wkb_w.byteorder = bad_byteorder`
self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)
# Setting the byteorder to 0 (for Big Endian)
wkb_w.byteorder = 0
self.assertEqual(hex2, wkb_w.write_hex(g))
self.assertEqual(wkb2, wkb_w.write(g))
# Back to Little Endian
wkb_w.byteorder = 1
# Now, trying out the 3D and SRID flags.
g = GEOSGeometry('POINT (5 23 17)')
g.srid = 4326
hex3d = '0101000080000000000000144000000000000037400000000000003140'
wkb3d = buffer(binascii.a2b_hex(hex3d))
hex3d_srid = '01010000A0E6100000000000000000144000000000000037400000000000003140'
wkb3d_srid = buffer(binascii.a2b_hex(hex3d_srid))
# Ensuring bad output dimensions are not accepted
for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
# Equivalent of `wkb_w.outdim = bad_outdim`
self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)
# These tests will fail on 3.0.0 because of a bug that was fixed in 3.1:
# http://trac.osgeo.org/geos/ticket/216
if not geos_version_info()['version'].startswith('3.0.'):
# Now setting the output dimensions to be 3
wkb_w.outdim = 3
self.assertEqual(hex3d, wkb_w.write_hex(g))
self.assertEqual(wkb3d, wkb_w.write(g))
# Telling the WKBWriter to inlcude the srid in the representation.
wkb_w.srid = True
self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
self.assertEqual(wkb3d_srid, wkb_w.write(g))
def suite():
s = unittest.TestSuite()
s.addTest(unittest.makeSuite(GEOSIOTest))
return s
def run(verbosity=2):
unittest.TextTestRunner(verbosity=verbosity).run(suite())
| apache-2.0 |
klickagent/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitpy/common/net/networktransaction.py | 190 | 2926 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
import time
import urllib2
_log = logging.getLogger(__name__)
class NetworkTimeout(Exception):
def __str__(self):
return 'NetworkTimeout'
class NetworkTransaction(object):
def __init__(self, initial_backoff_seconds=10, grown_factor=1.5, timeout_seconds=(10 * 60), convert_404_to_None=False):
self._initial_backoff_seconds = initial_backoff_seconds
self._grown_factor = grown_factor
self._timeout_seconds = timeout_seconds
self._convert_404_to_None = convert_404_to_None
def run(self, request):
self._total_sleep = 0
self._backoff_seconds = self._initial_backoff_seconds
while True:
try:
return request()
except urllib2.HTTPError, e:
if self._convert_404_to_None and e.code == 404:
return None
self._check_for_timeout()
_log.warn("Received HTTP status %s loading \"%s\". Retrying in %s seconds..." % (e.code, e.filename, self._backoff_seconds))
self._sleep()
def _check_for_timeout(self):
if self._total_sleep + self._backoff_seconds > self._timeout_seconds:
raise NetworkTimeout()
def _sleep(self):
time.sleep(self._backoff_seconds)
self._total_sleep += self._backoff_seconds
self._backoff_seconds *= self._grown_factor
| bsd-3-clause |
wluizguedes/namebench | libnamebench/better_webbrowser.py | 175 | 4191 | #!/usr/bin/env python
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wrapper for webbrowser library, to invoke the http handler on win32."""
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
import os.path
import subprocess
import sys
import traceback
import webbrowser
import util
def output(string):
print string
def create_win32_http_cmd(url):
"""Create a command-line tuple to launch a web browser for a given URL.
Args:
url: string
Returns:
tuple of: (executable, arg1, arg2, ...)
At the moment, this ignores all default arguments to the browser.
TODO(tstromberg): Properly parse the command-line arguments.
"""
browser_type = None
try:
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
'Software\Classes\http\shell\open\command')
browser_type = 'user'
except WindowsError:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
'Software\Classes\http\shell\open\command')
browser_type = 'machine'
except:
return False
cmd = _winreg.EnumValue(key, 0)[1]
# "C:\blah blah\iexplore.exe" -nohome
# "C:\blah blah\firefox.exe" -requestPending -osint -url "%1"
if '"' in cmd:
executable = cmd.split('"')[1]
else:
executable = cmd.split(' ')[0]
if not os.path.exists(executable):
output('$ Default HTTP browser does not exist: %s' % executable)
return False
else:
output('$ %s HTTP handler: %s' % (browser_type, executable))
return (executable, url)
def open(url):
"""Opens a URL, overriding the normal webbrowser.open methods for sanity."""
try:
webbrowser.open(url, new=1, autoraise=True)
# If the user is missing the osascript binary - see
# http://code.google.com/p/namebench/issues/detail?id=88
except:
output('Failed to open: [%s]: %s' % (url, util.GetLastExceptionString()))
if os.path.exists('/usr/bin/open'):
try:
output('trying open: %s' % url)
p = subprocess.Popen(('open', url))
p.wait()
except:
output('open did not seem to work: %s' % util.GetLastExceptionString())
elif sys.platform[:3] == 'win':
try:
output('trying default Windows controller: %s' % url)
controller = webbrowser.get('windows-default')
controller.open_new(url)
except:
output('WindowsController did not work: %s' % util.GetLastExceptionString())
# *NOTE*: EVIL IMPORT SIDE EFFECTS AHEAD!
#
# If we are running on Windows, register the WindowsHttpDefault class.
if sys.platform[:3] == 'win':
import _winreg
# We don't want to load this class by default, because Python 2.4 doesn't have BaseBrowser.
class WindowsHttpDefault(webbrowser.BaseBrowser):
"""Provide an alternate open class for Windows user, using the http handler."""
def open(self, url, new=0, autoraise=1):
command_args = create_win32_http_cmd(url)
if not command_args:
output('$ Could not find HTTP handler')
return False
output('command_args:')
output(command_args)
# Avoid some unicode path issues by moving our current directory
old_pwd = os.getcwd()
os.chdir('C:\\')
try:
_unused = subprocess.Popen(command_args)
os.chdir(old_pwd)
return True
except:
traceback.print_exc()
output('$ Failed to run HTTP handler, trying next browser.')
os.chdir(old_pwd)
return False
webbrowser.register('windows-http', WindowsHttpDefault, update_tryorder=-1)
| apache-2.0 |
vmturbo/nova | nova/api/openstack/compute/instance_actions.py | 7 | 4346 | # Copyright 2013 Rackspace Hosting
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from webob import exc
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
from nova.i18n import _
from nova.policies import instance_actions as ia_policies
from nova import utils
ALIAS = "os-instance-actions"
ACTION_KEYS = ['action', 'instance_uuid', 'request_id', 'user_id',
'project_id', 'start_time', 'message']
EVENT_KEYS = ['event', 'start_time', 'finish_time', 'result', 'traceback']
class InstanceActionsController(wsgi.Controller):
def __init__(self):
super(InstanceActionsController, self).__init__()
self.compute_api = compute.API()
self.action_api = compute.InstanceActionAPI()
def _format_action(self, action_raw):
action = {}
for key in ACTION_KEYS:
action[key] = action_raw.get(key)
return action
def _format_event(self, event_raw):
event = {}
for key in EVENT_KEYS:
event[key] = event_raw.get(key)
return event
@wsgi.Controller.api_version("2.1", "2.20")
def _get_instance(self, req, context, server_id):
return common.get_instance(self.compute_api, context, server_id)
@wsgi.Controller.api_version("2.21") # noqa
def _get_instance(self, req, context, server_id):
with utils.temporary_mutation(context, read_deleted='yes'):
return common.get_instance(self.compute_api, context, server_id)
@extensions.expected_errors(404)
def index(self, req, server_id):
"""Returns the list of actions recorded for a given instance."""
context = req.environ["nova.context"]
instance = self._get_instance(req, context, server_id)
context.can(ia_policies.BASE_POLICY_NAME, instance)
actions_raw = self.action_api.actions_get(context, instance)
actions = [self._format_action(action) for action in actions_raw]
return {'instanceActions': actions}
@extensions.expected_errors(404)
def show(self, req, server_id, id):
"""Return data about the given instance action."""
context = req.environ['nova.context']
instance = self._get_instance(req, context, server_id)
context.can(ia_policies.BASE_POLICY_NAME, instance)
action = self.action_api.action_get_by_request_id(context, instance,
id)
if action is None:
msg = _("Action %s not found") % id
raise exc.HTTPNotFound(explanation=msg)
action_id = action['id']
action = self._format_action(action)
if context.can(ia_policies.POLICY_ROOT % 'events', fatal=False):
events_raw = self.action_api.action_events_get(context, instance,
action_id)
action['events'] = [self._format_event(evt) for evt in events_raw]
return {'instanceAction': action}
class InstanceActions(extensions.V21APIExtensionBase):
"""View a log of actions and events taken on an instance."""
name = "InstanceActions"
alias = ALIAS
version = 1
def get_resources(self):
ext = extensions.ResourceExtension(ALIAS,
InstanceActionsController(),
parent=dict(
member_name='server',
collection_name='servers'))
return [ext]
def get_controller_extensions(self):
"""It's an abstract function V21APIExtensionBase and the extension
will not be loaded without it.
"""
return []
| apache-2.0 |
adamnovak/client | dev/wizards.py | 5 | 2538 | template_main_cpp = r'''/**
* Print a simple "Hello world!"
*
* @file main.cpp
* @section LICENSE
This code is under MIT License, http://opensource.org/licenses/MIT
*/
#include <iostream>
int main() {
std::cout << "Hello world!\n";
}
'''
template_main_c = r'''/**
* Print a simple "Hello world!"
*
* @file main.c
* @section LICENSE
This code is under MIT License, http://opensource.org/licenses/MIT
*/
#include <stdio.h>
int main(void)
{
printf("Hello World!");
}
'''
template_main_arduino = r'''/**
* It blinks an LED. In this case, LED in pin 13 with a time delay of 1 second
*
* @file main.cpp
* @section LICENSE
This code is under MIT License, http://opensource.org/licenses/MIT
*/
#include "Arduino.h"
// Pin 13 has an LED connected on most Arduino boards.
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
pinMode(led, OUTPUT); // initialize the digital pin as an output.
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
'''
template_main_fortran90 = '''program HelloWorld
write (*,*) 'Hello world!'
end program HelloWorld
'''
template_main_nodejs = '''var sys = require("sys");
sys.puts("Hello world!");
'''
template_main_python = '''def main():
print "Hello world!"
if __name__ == "__main__":
main()
'''
mains_templates = {'cpp': ['main.cpp', template_main_cpp],
'c': ['main.c', template_main_c],
'arduino': ['main.cpp', template_main_arduino],
'fortran': ['main.f90', template_main_fortran90],
'node': ['main.js', template_main_nodejs],
'python': ['main.py', template_main_python]}
def get_main_file_template(language='cpp'):
''' Return, if exists, the template file for the specified language '''
if mains_templates.get(language):
file_name, content = mains_templates[language]
return file_name, content
else:
from biicode.client.exception import ClientException
raise ClientException("Bad language introduced (%s)! "
"It should be one of %s" % (language,
mains_templates.keys()))
| mit |
mclevey/PyGithub | scripts/fix_headers.py | 18 | 7051 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# #
# This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ #
# #
# PyGithub 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. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import fnmatch
import os
import subprocess
import itertools
eightySharps = "################################################################################"
def generateLicenseSection(filename):
yield "############################ Copyrights and license ############################"
yield "# #"
for year, name in sorted(listContributors(filename)):
line = "# Copyright " + year + " " + name
line += (79 - len(line)) * " " + "#"
yield line
yield "# #"
yield "# This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ #"
yield "# #"
yield "# PyGithub is free software: you can redistribute it and/or modify it under #"
yield "# the terms of the GNU Lesser General Public License as published by the Free #"
yield "# Software Foundation, either version 3 of the License, or (at your option) #"
yield "# any later version. #"
yield "# #"
yield "# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #"
yield "# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #"
yield "# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #"
yield "# details. #"
yield "# #"
yield "# You should have received a copy of the GNU Lesser General Public License #"
yield "# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #"
yield "# #"
yield "################################################################################"
def listContributors(filename):
contributors = set()
for line in subprocess.check_output(["git", "log", "--format=format:%ad %an <%ae>", "--date=short", "--", filename]).split("\n"):
year = line[0:4]
name = line[11:]
contributors.add((year, name))
return contributors
def extractBodyLines(lines):
bodyLines = []
seenEndOfHeader = False
for line in lines:
if len(line) > 0 and line[0] != "#":
seenEndOfHeader = True
if seenEndOfHeader:
bodyLines.append(line)
# else:
# print "HEAD:", line
if line == eightySharps:
seenEndOfHeader = True
# print "BODY:", "\nBODY: ".join(bodyLines)
return bodyLines
class PythonHeader:
def fix(self, filename, lines):
isExecutable = lines[0].startswith("#!")
newLines = []
if isExecutable:
newLines.append("#!/usr/bin/env python")
newLines.append("# -*- coding: utf-8 -*-")
newLines.append("")
for line in generateLicenseSection(filename):
newLines.append(line)
bodyLines = extractBodyLines(lines)
if len(bodyLines) > 0 and bodyLines[0] != "":
newLines.append("")
if "import " not in bodyLines[0] and bodyLines[0] != '"""' and not bodyLines[0].startswith("##########"):
newLines.append("")
newLines += bodyLines
return newLines
class StandardHeader:
def fix(self, filename, lines):
newLines = []
for line in generateLicenseSection(filename):
newLines.append(line)
bodyLines = extractBodyLines(lines)
if len(bodyLines) and bodyLines[0] != "" > 0:
newLines.append("")
newLines += bodyLines
return newLines
def findHeadersAndFiles():
for root, dirs, files in os.walk('.', topdown=True):
if ".git" in dirs:
dirs.remove(".git")
if "developer.github.com" in dirs:
dirs.remove("developer.github.com")
if "build" in dirs:
dirs.remove("build")
for filename in files:
fullname = os.path.join(root, filename)
if filename.endswith(".py"):
yield (PythonHeader(), fullname)
elif filename in ["COPYING", "COPYING.LESSER"]:
pass
elif filename.endswith(".rst") or filename.endswith(".md"):
pass
elif filename == ".gitignore":
yield (StandardHeader(), fullname)
elif "ReplayData" in fullname:
pass
elif fullname.endswith(".pyc"):
pass
else:
print "Don't know what to do with", filename
def main():
for header, filename in findHeadersAndFiles():
print "Analyzing", filename
with open(filename) as f:
lines = list(line.rstrip() for line in f)
newLines = header.fix(filename, lines)
if newLines != lines:
print " => actually modifying", filename
with open(filename, "w") as f:
for line in newLines:
f.write(line + "\n")
if __name__ == "__main__":
main()
| gpl-3.0 |
omakk/servo | tests/wpt/css-tests/css21_dev/xhtml1print/support/fonts/makegsubfonts.py | 1616 | 14125 |
import os
import textwrap
from xml.etree import ElementTree
from fontTools.ttLib import TTFont, newTable
from fontTools.misc.psCharStrings import T2CharString
from fontTools.ttLib.tables.otTables import GSUB,\
ScriptList, ScriptRecord, Script, DefaultLangSys,\
FeatureList, FeatureRecord, Feature,\
LookupList, Lookup, AlternateSubst, SingleSubst
# paths
directory = os.path.dirname(__file__)
shellSourcePath = os.path.join(directory, "gsubtest-shell.ttx")
shellTempPath = os.path.join(directory, "gsubtest-shell.otf")
featureList = os.path.join(directory, "gsubtest-features.txt")
javascriptData = os.path.join(directory, "gsubtest-features.js")
outputPath = os.path.join(os.path.dirname(directory), "gsubtest-lookup%d")
baseCodepoint = 0xe000
# -------
# Features
# -------
f = open(featureList, "rb")
text = f.read()
f.close()
mapping = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
# parse
values = line.split("\t")
tag = values.pop(0)
mapping.append(tag);
# --------
# Outlines
# --------
def addGlyphToCFF(glyphName=None, program=None, private=None, globalSubrs=None, charStringsIndex=None, topDict=None, charStrings=None):
charString = T2CharString(program=program, private=private, globalSubrs=globalSubrs)
charStringsIndex.append(charString)
glyphID = len(topDict.charset)
charStrings.charStrings[glyphName] = glyphID
topDict.charset.append(glyphName)
def makeLookup1():
# make a variation of the shell TTX data
f = open(shellSourcePath)
ttxData = f.read()
f.close()
ttxData = ttxData.replace("__familyName__", "gsubtest-lookup1")
tempShellSourcePath = shellSourcePath + ".temp"
f = open(tempShellSourcePath, "wb")
f.write(ttxData)
f.close()
# compile the shell
shell = TTFont(sfntVersion="OTTO")
shell.importXML(tempShellSourcePath)
shell.save(shellTempPath)
os.remove(tempShellSourcePath)
# load the shell
shell = TTFont(shellTempPath)
# grab the PASS and FAIL data
hmtx = shell["hmtx"]
glyphSet = shell.getGlyphSet()
failGlyph = glyphSet["F"]
failGlyph.decompile()
failGlyphProgram = list(failGlyph.program)
failGlyphMetrics = hmtx["F"]
passGlyph = glyphSet["P"]
passGlyph.decompile()
passGlyphProgram = list(passGlyph.program)
passGlyphMetrics = hmtx["P"]
# grab some tables
hmtx = shell["hmtx"]
cmap = shell["cmap"]
# start the glyph order
existingGlyphs = [".notdef", "space", "F", "P"]
glyphOrder = list(existingGlyphs)
# start the CFF
cff = shell["CFF "].cff
globalSubrs = cff.GlobalSubrs
topDict = cff.topDictIndex[0]
topDict.charset = existingGlyphs
private = topDict.Private
charStrings = topDict.CharStrings
charStringsIndex = charStrings.charStringsIndex
features = sorted(mapping)
# build the outline, hmtx and cmap data
cp = baseCodepoint
for index, tag in enumerate(features):
# tag.pass
glyphName = "%s.pass" % tag
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=passGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = passGlyphMetrics
for table in cmap.tables:
if table.format == 4:
table.cmap[cp] = glyphName
else:
raise NotImplementedError, "Unsupported cmap table format: %d" % table.format
cp += 1
# tag.fail
glyphName = "%s.fail" % tag
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=failGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = failGlyphMetrics
for table in cmap.tables:
if table.format == 4:
table.cmap[cp] = glyphName
else:
raise NotImplementedError, "Unsupported cmap table format: %d" % table.format
# bump this up so that the sequence is the same as the lookup 3 font
cp += 3
# set the glyph order
shell.setGlyphOrder(glyphOrder)
# start the GSUB
shell["GSUB"] = newTable("GSUB")
gsub = shell["GSUB"].table = GSUB()
gsub.Version = 1.0
# make a list of all the features we will make
featureCount = len(features)
# set up the script list
scriptList = gsub.ScriptList = ScriptList()
scriptList.ScriptCount = 1
scriptList.ScriptRecord = []
scriptRecord = ScriptRecord()
scriptList.ScriptRecord.append(scriptRecord)
scriptRecord.ScriptTag = "DFLT"
script = scriptRecord.Script = Script()
defaultLangSys = script.DefaultLangSys = DefaultLangSys()
defaultLangSys.FeatureCount = featureCount
defaultLangSys.FeatureIndex = range(defaultLangSys.FeatureCount)
defaultLangSys.ReqFeatureIndex = 65535
defaultLangSys.LookupOrder = None
script.LangSysCount = 0
script.LangSysRecord = []
# set up the feature list
featureList = gsub.FeatureList = FeatureList()
featureList.FeatureCount = featureCount
featureList.FeatureRecord = []
for index, tag in enumerate(features):
# feature record
featureRecord = FeatureRecord()
featureRecord.FeatureTag = tag
feature = featureRecord.Feature = Feature()
featureList.FeatureRecord.append(featureRecord)
# feature
feature.FeatureParams = None
feature.LookupCount = 1
feature.LookupListIndex = [index]
# write the lookups
lookupList = gsub.LookupList = LookupList()
lookupList.LookupCount = featureCount
lookupList.Lookup = []
for tag in features:
# lookup
lookup = Lookup()
lookup.LookupType = 1
lookup.LookupFlag = 0
lookup.SubTableCount = 1
lookup.SubTable = []
lookupList.Lookup.append(lookup)
# subtable
subtable = SingleSubst()
subtable.Format = 2
subtable.LookupType = 1
subtable.mapping = {
"%s.pass" % tag : "%s.fail" % tag,
"%s.fail" % tag : "%s.pass" % tag,
}
lookup.SubTable.append(subtable)
path = outputPath % 1 + ".otf"
if os.path.exists(path):
os.remove(path)
shell.save(path)
# get rid of the shell
if os.path.exists(shellTempPath):
os.remove(shellTempPath)
def makeLookup3():
# make a variation of the shell TTX data
f = open(shellSourcePath)
ttxData = f.read()
f.close()
ttxData = ttxData.replace("__familyName__", "gsubtest-lookup3")
tempShellSourcePath = shellSourcePath + ".temp"
f = open(tempShellSourcePath, "wb")
f.write(ttxData)
f.close()
# compile the shell
shell = TTFont(sfntVersion="OTTO")
shell.importXML(tempShellSourcePath)
shell.save(shellTempPath)
os.remove(tempShellSourcePath)
# load the shell
shell = TTFont(shellTempPath)
# grab the PASS and FAIL data
hmtx = shell["hmtx"]
glyphSet = shell.getGlyphSet()
failGlyph = glyphSet["F"]
failGlyph.decompile()
failGlyphProgram = list(failGlyph.program)
failGlyphMetrics = hmtx["F"]
passGlyph = glyphSet["P"]
passGlyph.decompile()
passGlyphProgram = list(passGlyph.program)
passGlyphMetrics = hmtx["P"]
# grab some tables
hmtx = shell["hmtx"]
cmap = shell["cmap"]
# start the glyph order
existingGlyphs = [".notdef", "space", "F", "P"]
glyphOrder = list(existingGlyphs)
# start the CFF
cff = shell["CFF "].cff
globalSubrs = cff.GlobalSubrs
topDict = cff.topDictIndex[0]
topDict.charset = existingGlyphs
private = topDict.Private
charStrings = topDict.CharStrings
charStringsIndex = charStrings.charStringsIndex
features = sorted(mapping)
# build the outline, hmtx and cmap data
cp = baseCodepoint
for index, tag in enumerate(features):
# tag.pass
glyphName = "%s.pass" % tag
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=passGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = passGlyphMetrics
# tag.fail
glyphName = "%s.fail" % tag
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=failGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = failGlyphMetrics
# tag.default
glyphName = "%s.default" % tag
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=passGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = passGlyphMetrics
for table in cmap.tables:
if table.format == 4:
table.cmap[cp] = glyphName
else:
raise NotImplementedError, "Unsupported cmap table format: %d" % table.format
cp += 1
# tag.alt1,2,3
for i in range(1,4):
glyphName = "%s.alt%d" % (tag, i)
glyphOrder.append(glyphName)
addGlyphToCFF(
glyphName=glyphName,
program=failGlyphProgram,
private=private,
globalSubrs=globalSubrs,
charStringsIndex=charStringsIndex,
topDict=topDict,
charStrings=charStrings
)
hmtx[glyphName] = failGlyphMetrics
for table in cmap.tables:
if table.format == 4:
table.cmap[cp] = glyphName
else:
raise NotImplementedError, "Unsupported cmap table format: %d" % table.format
cp += 1
# set the glyph order
shell.setGlyphOrder(glyphOrder)
# start the GSUB
shell["GSUB"] = newTable("GSUB")
gsub = shell["GSUB"].table = GSUB()
gsub.Version = 1.0
# make a list of all the features we will make
featureCount = len(features)
# set up the script list
scriptList = gsub.ScriptList = ScriptList()
scriptList.ScriptCount = 1
scriptList.ScriptRecord = []
scriptRecord = ScriptRecord()
scriptList.ScriptRecord.append(scriptRecord)
scriptRecord.ScriptTag = "DFLT"
script = scriptRecord.Script = Script()
defaultLangSys = script.DefaultLangSys = DefaultLangSys()
defaultLangSys.FeatureCount = featureCount
defaultLangSys.FeatureIndex = range(defaultLangSys.FeatureCount)
defaultLangSys.ReqFeatureIndex = 65535
defaultLangSys.LookupOrder = None
script.LangSysCount = 0
script.LangSysRecord = []
# set up the feature list
featureList = gsub.FeatureList = FeatureList()
featureList.FeatureCount = featureCount
featureList.FeatureRecord = []
for index, tag in enumerate(features):
# feature record
featureRecord = FeatureRecord()
featureRecord.FeatureTag = tag
feature = featureRecord.Feature = Feature()
featureList.FeatureRecord.append(featureRecord)
# feature
feature.FeatureParams = None
feature.LookupCount = 1
feature.LookupListIndex = [index]
# write the lookups
lookupList = gsub.LookupList = LookupList()
lookupList.LookupCount = featureCount
lookupList.Lookup = []
for tag in features:
# lookup
lookup = Lookup()
lookup.LookupType = 3
lookup.LookupFlag = 0
lookup.SubTableCount = 1
lookup.SubTable = []
lookupList.Lookup.append(lookup)
# subtable
subtable = AlternateSubst()
subtable.Format = 1
subtable.LookupType = 3
subtable.alternates = {
"%s.default" % tag : ["%s.fail" % tag, "%s.fail" % tag, "%s.fail" % tag],
"%s.alt1" % tag : ["%s.pass" % tag, "%s.fail" % tag, "%s.fail" % tag],
"%s.alt2" % tag : ["%s.fail" % tag, "%s.pass" % tag, "%s.fail" % tag],
"%s.alt3" % tag : ["%s.fail" % tag, "%s.fail" % tag, "%s.pass" % tag]
}
lookup.SubTable.append(subtable)
path = outputPath % 3 + ".otf"
if os.path.exists(path):
os.remove(path)
shell.save(path)
# get rid of the shell
if os.path.exists(shellTempPath):
os.remove(shellTempPath)
def makeJavascriptData():
features = sorted(mapping)
outStr = []
outStr.append("")
outStr.append("/* This file is autogenerated by makegsubfonts.py */")
outStr.append("")
outStr.append("/* ")
outStr.append(" Features defined in gsubtest fonts with associated base")
outStr.append(" codepoints for each feature:")
outStr.append("")
outStr.append(" cp = codepoint for feature featX")
outStr.append("")
outStr.append(" cp default PASS")
outStr.append(" cp featX=1 FAIL")
outStr.append(" cp featX=2 FAIL")
outStr.append("")
outStr.append(" cp+1 default FAIL")
outStr.append(" cp+1 featX=1 PASS")
outStr.append(" cp+1 featX=2 FAIL")
outStr.append("")
outStr.append(" cp+2 default FAIL")
outStr.append(" cp+2 featX=1 FAIL")
outStr.append(" cp+2 featX=2 PASS")
outStr.append("")
outStr.append("*/")
outStr.append("")
outStr.append("var gFeatures = {");
cp = baseCodepoint
taglist = []
for tag in features:
taglist.append("\"%s\": 0x%x" % (tag, cp))
cp += 4
outStr.append(textwrap.fill(", ".join(taglist), initial_indent=" ", subsequent_indent=" "))
outStr.append("};");
outStr.append("");
if os.path.exists(javascriptData):
os.remove(javascriptData)
f = open(javascriptData, "wb")
f.write("\n".join(outStr))
f.close()
# build fonts
print "Making lookup type 1 font..."
makeLookup1()
print "Making lookup type 3 font..."
makeLookup3()
# output javascript data
print "Making javascript data file..."
makeJavascriptData()
| mpl-2.0 |
tetherless-world/ecoop | pyecoop/docs/sphinxext/apigen.py | 59 | 15659 | """Attempt to generate templates for module reference with Sphinx
XXX - we exclude extension modules
To include extension modules, first identify them as valid in the
``_uri2path`` method, then handle them in the ``_parse_module`` script.
We get functions and classes by parsing the text of .py files.
Alternatively we could import the modules for discovery, and we'd have
to do that for extension modules. This would involve changing the
``_parse_module`` method to work via import and introspection, and
might involve changing ``discover_modules`` (which determines which
files are modules, and therefore which module URIs will be passed to
``_parse_module``).
NOTE: this is a modified version of a script originally shipped with the
PyMVPA project, which we've adapted for NIPY use. PyMVPA is an MIT-licensed
project."""
# Stdlib imports
import os
import re
# Functions and classes
class ApiDocWriter(object):
''' Class for automatic detection and parsing of API docs
to Sphinx-parsable reST format'''
# only separating first two levels
rst_section_levels = ['*', '=', '-', '~', '^']
def __init__(self,
package_name,
rst_extension='.rst',
package_skip_patterns=None,
module_skip_patterns=None,
):
''' Initialize package for parsing
Parameters
----------
package_name : string
Name of the top-level package. *package_name* must be the
name of an importable package
rst_extension : string, optional
Extension for reST files, default '.rst'
package_skip_patterns : None or sequence of {strings, regexps}
Sequence of strings giving URIs of packages to be excluded
Operates on the package path, starting at (including) the
first dot in the package path, after *package_name* - so,
if *package_name* is ``sphinx``, then ``sphinx.util`` will
result in ``.util`` being passed for earching by these
regexps. If is None, gives default. Default is:
['\.tests$']
module_skip_patterns : None or sequence
Sequence of strings giving URIs of modules to be excluded
Operates on the module name including preceding URI path,
back to the first dot after *package_name*. For example
``sphinx.util.console`` results in the string to search of
``.util.console``
If is None, gives default. Default is:
['\.setup$', '\._']
'''
if package_skip_patterns is None:
package_skip_patterns = ['\\.tests$']
if module_skip_patterns is None:
module_skip_patterns = ['\\.setup$', '\\._']
self.package_name = package_name
self.rst_extension = rst_extension
self.package_skip_patterns = package_skip_patterns
self.module_skip_patterns = module_skip_patterns
def get_package_name(self):
return self._package_name
def set_package_name(self, package_name):
''' Set package_name
>>> docwriter = ApiDocWriter('sphinx')
>>> import sphinx
>>> docwriter.root_path == sphinx.__path__[0]
True
>>> docwriter.package_name = 'docutils'
>>> import docutils
>>> docwriter.root_path == docutils.__path__[0]
True
'''
# It's also possible to imagine caching the module parsing here
self._package_name = package_name
self.root_module = __import__(package_name)
self.root_path = self.root_module.__path__[0]
self.written_modules = None
package_name = property(get_package_name, set_package_name, None,
'get/set package_name')
def _get_object_name(self, line):
''' Get second token in line
>>> docwriter = ApiDocWriter('sphinx')
>>> docwriter._get_object_name(" def func(): ")
'func'
>>> docwriter._get_object_name(" class Klass(object): ")
'Klass'
>>> docwriter._get_object_name(" class Klass: ")
'Klass'
'''
name = line.split()[1].split('(')[0].strip()
# in case we have classes which are not derived from object
# ie. old style classes
return name.rstrip(':')
def _uri2path(self, uri):
''' Convert uri to absolute filepath
Parameters
----------
uri : string
URI of python module to return path for
Returns
-------
path : None or string
Returns None if there is no valid path for this URI
Otherwise returns absolute file system path for URI
Examples
--------
>>> docwriter = ApiDocWriter('sphinx')
>>> import sphinx
>>> modpath = sphinx.__path__[0]
>>> res = docwriter._uri2path('sphinx.builder')
>>> res == os.path.join(modpath, 'builder.py')
True
>>> res = docwriter._uri2path('sphinx')
>>> res == os.path.join(modpath, '__init__.py')
True
>>> docwriter._uri2path('sphinx.does_not_exist')
'''
if uri == self.package_name:
return os.path.join(self.root_path, '__init__.py')
path = uri.replace('.', os.path.sep)
path = path.replace(self.package_name + os.path.sep, '')
path = os.path.join(self.root_path, path)
# XXX maybe check for extensions as well?
if os.path.exists(path + '.py'): # file
path += '.py'
elif os.path.exists(os.path.join(path, '__init__.py')):
path = os.path.join(path, '__init__.py')
else:
return None
return path
def _path2uri(self, dirpath):
''' Convert directory path to uri '''
relpath = dirpath.replace(self.root_path, self.package_name)
if relpath.startswith(os.path.sep):
relpath = relpath[1:]
return relpath.replace(os.path.sep, '.')
def _parse_module(self, uri):
''' Parse module defined in *uri* '''
filename = self._uri2path(uri)
if filename is None:
# nothing that we could handle here.
return ([],[])
f = open(filename, 'rt')
functions, classes = self._parse_lines(f)
f.close()
return functions, classes
def _parse_lines(self, linesource):
''' Parse lines of text for functions and classes '''
functions = []
classes = []
for line in linesource:
if line.startswith('def ') and line.count('('):
# exclude private stuff
name = self._get_object_name(line)
if not name.startswith('_'):
functions.append(name)
elif line.startswith('class '):
# exclude private stuff
name = self._get_object_name(line)
if not name.startswith('_'):
classes.append(name)
else:
pass
functions.sort()
classes.sort()
return functions, classes
def generate_api_doc(self, uri):
'''Make autodoc documentation template string for a module
Parameters
----------
uri : string
python location of module - e.g 'sphinx.builder'
Returns
-------
S : string
Contents of API doc
'''
# get the names of all classes and functions
functions, classes = self._parse_module(uri)
if not len(functions) and not len(classes):
print 'WARNING: Empty -',uri # dbg
return ''
# Make a shorter version of the uri that omits the package name for
# titles
uri_short = re.sub(r'^%s\.' % self.package_name,'',uri)
ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n'
chap_title = uri_short
ad += (chap_title+'\n'+ self.rst_section_levels[1] * len(chap_title)
+ '\n\n')
# Set the chapter title to read 'module' for all modules except for the
# main packages
if '.' in uri:
title = 'Module: :mod:`' + uri_short + '`'
else:
title = ':mod:`' + uri_short + '`'
ad += title + '\n' + self.rst_section_levels[2] * len(title)
if len(classes):
ad += '\nInheritance diagram for ``%s``:\n\n' % uri
ad += '.. inheritance-diagram:: %s \n' % uri
ad += ' :parts: 3\n'
ad += '\n.. automodule:: ' + uri + '\n'
ad += '\n.. currentmodule:: ' + uri + '\n'
multi_class = len(classes) > 1
multi_fx = len(functions) > 1
if multi_class:
ad += '\n' + 'Classes' + '\n' + \
self.rst_section_levels[2] * 7 + '\n'
elif len(classes) and multi_fx:
ad += '\n' + 'Class' + '\n' + \
self.rst_section_levels[2] * 5 + '\n'
for c in classes:
ad += '\n:class:`' + c + '`\n' \
+ self.rst_section_levels[multi_class + 2 ] * \
(len(c)+9) + '\n\n'
ad += '\n.. autoclass:: ' + c + '\n'
# must NOT exclude from index to keep cross-refs working
ad += ' :members:\n' \
' :undoc-members:\n' \
' :show-inheritance:\n' \
' :inherited-members:\n' \
'\n' \
' .. automethod:: __init__\n'
if multi_fx:
ad += '\n' + 'Functions' + '\n' + \
self.rst_section_levels[2] * 9 + '\n\n'
elif len(functions) and multi_class:
ad += '\n' + 'Function' + '\n' + \
self.rst_section_levels[2] * 8 + '\n\n'
for f in functions:
# must NOT exclude from index to keep cross-refs working
ad += '\n.. autofunction:: ' + uri + '.' + f + '\n\n'
return ad
def _survives_exclude(self, matchstr, match_type):
''' Returns True if *matchstr* does not match patterns
``self.package_name`` removed from front of string if present
Examples
--------
>>> dw = ApiDocWriter('sphinx')
>>> dw._survives_exclude('sphinx.okpkg', 'package')
True
>>> dw.package_skip_patterns.append('^\\.badpkg$')
>>> dw._survives_exclude('sphinx.badpkg', 'package')
False
>>> dw._survives_exclude('sphinx.badpkg', 'module')
True
>>> dw._survives_exclude('sphinx.badmod', 'module')
True
>>> dw.module_skip_patterns.append('^\\.badmod$')
>>> dw._survives_exclude('sphinx.badmod', 'module')
False
'''
if match_type == 'module':
patterns = self.module_skip_patterns
elif match_type == 'package':
patterns = self.package_skip_patterns
else:
raise ValueError('Cannot interpret match type "%s"'
% match_type)
# Match to URI without package name
L = len(self.package_name)
if matchstr[:L] == self.package_name:
matchstr = matchstr[L:]
for pat in patterns:
try:
pat.search
except AttributeError:
pat = re.compile(pat)
if pat.search(matchstr):
return False
return True
def discover_modules(self):
''' Return module sequence discovered from ``self.package_name``
Parameters
----------
None
Returns
-------
mods : sequence
Sequence of module names within ``self.package_name``
Examples
--------
>>> dw = ApiDocWriter('sphinx')
>>> mods = dw.discover_modules()
>>> 'sphinx.util' in mods
True
>>> dw.package_skip_patterns.append('\.util$')
>>> 'sphinx.util' in dw.discover_modules()
False
>>>
'''
modules = [self.package_name]
# raw directory parsing
for dirpath, dirnames, filenames in os.walk(self.root_path):
# Check directory names for packages
root_uri = self._path2uri(os.path.join(self.root_path,
dirpath))
for dirname in dirnames[:]: # copy list - we modify inplace
package_uri = '.'.join((root_uri, dirname))
if (self._uri2path(package_uri) and
self._survives_exclude(package_uri, 'package')):
modules.append(package_uri)
else:
dirnames.remove(dirname)
# Check filenames for modules
for filename in filenames:
module_name = filename[:-3]
module_uri = '.'.join((root_uri, module_name))
if (self._uri2path(module_uri) and
self._survives_exclude(module_uri, 'module')):
modules.append(module_uri)
return sorted(modules)
def write_modules_api(self, modules,outdir):
# write the list
written_modules = []
for m in modules:
api_str = self.generate_api_doc(m)
if not api_str:
continue
# write out to file
outfile = os.path.join(outdir,
m + self.rst_extension)
fileobj = open(outfile, 'wt')
fileobj.write(api_str)
fileobj.close()
written_modules.append(m)
self.written_modules = written_modules
def write_api_docs(self, outdir):
"""Generate API reST files.
Parameters
----------
outdir : string
Directory name in which to store files
We create automatic filenames for each module
Returns
-------
None
Notes
-----
Sets self.written_modules to list of written modules
"""
if not os.path.exists(outdir):
os.mkdir(outdir)
# compose list of modules
modules = self.discover_modules()
self.write_modules_api(modules,outdir)
def write_index(self, outdir, froot='gen', relative_to=None):
"""Make a reST API index file from written files
Parameters
----------
path : string
Filename to write index to
outdir : string
Directory to which to write generated index file
froot : string, optional
root (filename without extension) of filename to write to
Defaults to 'gen'. We add ``self.rst_extension``.
relative_to : string
path to which written filenames are relative. This
component of the written file path will be removed from
outdir, in the generated index. Default is None, meaning,
leave path as it is.
"""
if self.written_modules is None:
raise ValueError('No modules written')
# Get full filename path
path = os.path.join(outdir, froot+self.rst_extension)
# Path written into index is relative to rootpath
if relative_to is not None:
relpath = outdir.replace(relative_to + os.path.sep, '')
else:
relpath = outdir
idx = open(path,'wt')
w = idx.write
w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
w('.. toctree::\n\n')
for f in self.written_modules:
w(' %s\n' % os.path.join(relpath,f))
idx.close()
| apache-2.0 |
FvD/trytond_account_nl | setup.py | 1 | 3133 | #!/usr/bin/env python
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from setuptools import setup
import re
import os
import ConfigParser
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_require_version(name):
if minor_version % 2:
require = '%s >= %s.%s.dev0, < %s.%s'
else:
require = '%s >= %s.%s, < %s.%s'
require %= (name, major_version, minor_version,
major_version, minor_version + 1)
return require
config = ConfigParser.ConfigParser()
config.readfp(open('tryton.cfg'))
info = dict(config.items('tryton'))
for key in ('depends', 'extras_depend', 'xml'):
if key in info:
info[key] = info[key].strip().splitlines()
version = info.get('version', '0.0.1')
major_version, minor_version, _ = version.split('.', 2)
major_version = int(major_version)
minor_version = int(minor_version)
name = 'trytond_account_nl'
download_url = 'http://downloads.tryton.org/%s.%s/' % (
major_version, minor_version)
if minor_version % 2:
version = '%s.%s.dev0' % (major_version, minor_version)
download_url = (
'hg+http://hg.tryton.org/modules/%s#egg=%s-%s' % (
name[8:], name, version))
requires = []
for dep in info.get('depends', []):
if not re.match(r'(ir|res|webdav)(\W|$)', dep):
requires.append(get_require_version('trytond_%s' % dep))
requires.append(get_require_version('trytond'))
setup(name=name,
version=version,
description='Tryton module with Dutch chart of accounts',
long_description=read('README'),
author='Tryton',
author_email='issue_tracker@tryton.org',
url='http://www.tryton.org/',
download_url=download_url,
keywords='tryton account chart dutch fec',
package_dir={'trytond.modules.account_nl': '.'},
packages=[
'trytond.modules.account_nl',
'trytond.modules.account_nl.tests',
],
package_data={
'trytond.modules.account_nl': (info.get('xml', [])
+ ['tryton.cfg', 'view/*.xml', 'locale/*.po']),
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Framework :: Tryton',
'Intended Audience :: Developers',
'Intended Audience :: Financial and Insurance Industry',
'Intended Audience :: Legal Industry',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: Dutch',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Office/Business',
'Topic :: Office/Business :: Financial :: Accounting',
],
license='GPL-3',
install_requires=requires,
zip_safe=False,
entry_points="""
[trytond.modules]
account_nl = trytond.modules.account_nl
""",
test_suite='tests',
test_loader='trytond.test_loader:Loader',
)
| gpl-3.0 |
mgagne/nova | nova/virt/vmwareapi/imagecache.py | 6 | 8980 | # Copyright (c) 2014 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Image cache class
Images that are stored in the cache folder will be stored in a folder whose
name is the image ID. In the event that an image is discovered to be no longer
used then a timestamp will be added to the image folder.
The timestamp will be a folder - this is due to the fact that we can use the
VMware API's for creating and deleting of folders (it really simplifies
things). The timestamp will contain the time, on the compute node, when the
image was first seen to be unused.
At each aging iteration we check if the image can be aged.
This is done by comparing the current nova compute time to the time embedded
in the timestamp. If the time exceeds the configured aging time then
the parent folder, that is the image ID folder, will be deleted.
That effectively ages the cached image.
If an image is used then the timestamps will be deleted.
When accessing a timestamp we make use of locking. This ensure that aging
will not delete an image during the spawn operation. When spawning
the timestamp folder will be locked and the timestamps will be purged.
This will ensure that a image is not deleted during the spawn.
"""
from oslo.config import cfg
from oslo.utils import timeutils
from oslo.vmware import exceptions as vexc
from oslo_concurrency import lockutils
from nova.i18n import _LI, _LW
from nova.openstack.common import log as logging
from nova.virt import imagecache
from nova.virt.vmwareapi import ds_util
from nova.virt.vmwareapi import vim_util
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.import_opt('remove_unused_original_minimum_age_seconds',
'nova.virt.imagecache')
TIMESTAMP_PREFIX = 'ts-'
TIMESTAMP_FORMAT = '%Y-%m-%d-%H-%M-%S'
class ImageCacheManager(imagecache.ImageCacheManager):
def __init__(self, session, base_folder):
super(ImageCacheManager, self).__init__()
self._session = session
self._base_folder = base_folder
self._ds_browser = {}
def _folder_delete(self, ds_path, dc_ref):
try:
ds_util.file_delete(self._session, ds_path, dc_ref)
except (vexc.CannotDeleteFileException,
vexc.FileFaultException,
vexc.FileLockedException) as e:
# There may be more than one process or thread that tries
# to delete the file.
LOG.warning(_LW("Unable to delete %(file)s. Exception: %(ex)s"),
{'file': ds_path, 'ex': e})
except vexc.FileNotFoundException:
LOG.debug("File not found: %s", ds_path)
def enlist_image(self, image_id, datastore, dc_ref):
ds_browser = self._get_ds_browser(datastore.ref)
cache_root_folder = datastore.build_path(self._base_folder)
# Check if the timestamp file exists - if so then delete it. This
# will ensure that the aging will not delete a cache image if it
# is going to be used now.
path = self.timestamp_folder_get(cache_root_folder, image_id)
# Lock to ensure that the spawn will not try and access a image
# that is currently being deleted on the datastore.
with lockutils.lock(str(path), lock_file_prefix='nova-vmware-ts',
external=True):
self.timestamp_cleanup(dc_ref, ds_browser, path)
def timestamp_folder_get(self, ds_path, image_id):
"""Returns the timestamp folder."""
return ds_path.join(image_id)
def timestamp_cleanup(self, dc_ref, ds_browser, ds_path):
ts = self._get_timestamp(ds_browser, ds_path)
if ts:
ts_path = ds_path.join(ts)
LOG.debug("Timestamp path %s exists. Deleting!", ts_path)
# Image is used - no longer need timestamp folder
self._folder_delete(ts_path, dc_ref)
def _get_timestamp(self, ds_browser, ds_path):
files = ds_util.get_sub_folders(self._session, ds_browser, ds_path)
if files:
for file in files:
if file.startswith(TIMESTAMP_PREFIX):
return file
def _get_timestamp_filename(self):
return '%s%s' % (TIMESTAMP_PREFIX,
timeutils.strtime(fmt=TIMESTAMP_FORMAT))
def _get_datetime_from_filename(self, timestamp_filename):
ts = timestamp_filename.lstrip(TIMESTAMP_PREFIX)
return timeutils.parse_strtime(ts, fmt=TIMESTAMP_FORMAT)
def _get_ds_browser(self, ds_ref):
ds_browser = self._ds_browser.get(ds_ref.value)
if not ds_browser:
ds_browser = vim_util.get_dynamic_property(
self._session.vim, ds_ref,
"Datastore", "browser")
self._ds_browser[ds_ref.value] = ds_browser
return ds_browser
def _list_datastore_images(self, ds_path, datastore):
"""Return a list of the images present in _base.
This method returns a dictionary with the following keys:
- unexplained_images
- originals
"""
ds_browser = self._get_ds_browser(datastore.ref)
originals = ds_util.get_sub_folders(self._session, ds_browser,
ds_path)
return {'unexplained_images': [],
'originals': originals}
def _age_cached_images(self, context, datastore, dc_info,
ds_path):
"""Ages cached images."""
age_seconds = CONF.remove_unused_original_minimum_age_seconds
unused_images = self.originals - self.used_images
ds_browser = self._get_ds_browser(datastore.ref)
for image in unused_images:
path = self.timestamp_folder_get(ds_path, image)
# Lock to ensure that the spawn will not try and access a image
# that is currently being deleted on the datastore.
with lockutils.lock(str(path), lock_file_prefix='nova-vmware-ts',
external=True):
ts = self._get_timestamp(ds_browser, path)
if not ts:
ts_path = path.join(self._get_timestamp_filename())
try:
ds_util.mkdir(self._session, ts_path, dc_info.ref)
except vexc.FileAlreadyExistsException:
LOG.debug("Timestamp already exists.")
LOG.info(_LI("Image %s is no longer used by this node. "
"Pending deletion!"), image)
else:
dt = self._get_datetime_from_filename(str(ts))
if timeutils.is_older_than(dt, age_seconds):
LOG.info(_LI("Image %s is no longer used. "
"Deleting!"), path)
# Image has aged - delete the image ID folder
self._folder_delete(path, dc_info.ref)
# If the image is used and the timestamp file exists then we delete
# the timestamp.
for image in self.used_images:
path = self.timestamp_folder_get(ds_path, image)
with lockutils.lock(str(path), lock_file_prefix='nova-vmware-ts',
external=True):
self.timestamp_cleanup(dc_info.ref, ds_browser,
path)
def update(self, context, instances, datastores_info):
"""The cache manager entry point.
This will invoke the cache manager. This will update the cache
according to the defined cache management scheme. The information
populated in the cached stats will be used for the cache management.
"""
# read running instances data
running = self._list_running_instances(context, instances)
self.used_images = set(running['used_images'].keys())
# perform the aging and image verification per datastore
for (datastore, dc_info) in datastores_info:
ds_path = datastore.build_path(self._base_folder)
images = self._list_datastore_images(ds_path, datastore)
self.originals = images['originals']
self._age_cached_images(context, datastore, dc_info, ds_path)
def get_image_cache_folder(self, datastore, image_id):
"""Returns datastore path of folder containing the image."""
return datastore.build_path(self._base_folder, image_id)
| apache-2.0 |
AlbertoPeon/invenio | modules/webstyle/lib/template.py | 32 | 21084 | ## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio templating framework."""
from __future__ import nested_scopes
import os, sys, inspect, getopt, new, cgi
try:
# This tool can be run before Invenio is installed:
# invenio files might then not exist.
from invenio.config import \
CFG_WEBSTYLE_TEMPLATE_SKIN, \
CFG_PREFIX, \
CFG_WEBSTYLE_INSPECT_TEMPLATES
CFG_WEBSTYLE_PYLIBDIR = CFG_PREFIX + os.sep + 'lib' + os.sep + 'python'
except ImportError:
CFG_WEBSTYLE_PYLIBDIR = None
# List of deprecated functions
# Eg. {'webstyle': {'tmpl_records_format_other':"Replaced by .."}}
CFG_WEBSTYLE_DEPRECATED_FUNCTIONS = {'webstyle': \
{'tmpl_records_format_other': "Replaced by " + \
"websearch_templates.tmpl_detailed_record_metadata(..), " + \
"websearch_templates.tmpl_detailed_record_references(..), " + \
"websearch_templates.tmpl_detailed_record_statistics(..), " + \
"webcomment_templates.tmpl_get_comments(..), " + \
"webcomment_templates.tmpl_mini_review(..)," + \
"websubmit_templates.tmpl_filelist(..) and " + \
"HDFILE + HDACT + HDREF output formats",
'detailed_record_container': "Replaced by " + \
"detailed_record_container_top and " + \
"detailed_record_container_bottom"},
'websearch': \
{'tmpl_detailed_record_citations': "Replaced by " + \
"tmpl_detailed_record_citations_prologue" + \
"tmpl_detailed_record_citations_epilogue" + \
"tmpl_detailed_record_citations_citing_list" + \
"tmpl_detailed_record_citations_citation_history" + \
"tmpl_detailed_record_citations_cociting" + \
"tmpl_detailed_record_citations_self_cited"}
}
# List of deprecated parameter
# Eg. {'webstyle': {'get_page':{'header': "replaced by 'title'"}}}
CFG_WEBSTYLE_DEPRECATED_PARAMETERS = {}
## Thanks to Python CookBook for this!
def enhance_method(module, klass, method_name, replacement):
old_method = getattr(klass, method_name)
try:
if type(old_method) is not new.instancemethod or old_method.__name__ == 'new_method':
## not a method or Already wrapped
return
except AttributeError:
raise '%s %s %s %s' % (module, klass, method_name, old_method)
def new_method(*args, **kwds):
return replacement(module, old_method, method_name, *args, **kwds)
setattr(klass, method_name, new.instancemethod(new_method, None, klass))
def method_wrapper(module, old_method, method_name, self, *args, **kwds):
def shortener(text):
if len(text) > 205:
return text[:100] + ' ... ' + text[-100:]
else:
return text
ret = old_method(self, *args, **kwds)
if ret and type(ret) is str:
params = ', '.join([shortener(repr(arg)) for arg in args] + ['%s=%s' % (item[0], shortener(repr(item[1]))) for item in kwds.items()])
signature = '%s_templates/%s(%s)' % (module, method_name, params)
signature_q = '%s_templates/%s' % (module, method_name)
return '<span title="%(signature)s" style="border: thin solid red;"><!-- BEGIN TEMPLATE %(signature_q)s BEGIN TEMPLATE --><span style="color: red; font-size: xx-small; font-style: normal; font-family: monospace; float: both">*</span>%(result)s<!-- END TEMPLATE %(signature_q)s END TEMPLATE --></span>' % {
'signature_q' : cgi.escape(signature_q),
'signature' : cgi.escape(signature, True),
'result' : ret
}
else:
return ret
def load(module=''):
""" Load and returns a template class, given a module name (like
'websearch', 'webbasket',...). The module corresponding to
the currently selected template model (see invenio.conf,
variable CFG_WEBSTYLE_TEMPLATE_SKIN) is tried first. In case it does
not exist, it returns the default template for that module.
"""
local = {}
# load the right template based on the CFG_WEBSTYLE_TEMPLATE_SKIN and the specified module
if CFG_WEBSTYLE_TEMPLATE_SKIN == "default":
mymodule = __import__("invenio.%s_templates" % (module), local, local,
["invenio.templates.%s" % (module)])
else:
try:
mymodule = __import__("invenio.%s_templates_%s" % (module, CFG_WEBSTYLE_TEMPLATE_SKIN), local, local,
["invenio.templates.%s_%s" % (module, CFG_WEBSTYLE_TEMPLATE_SKIN)])
except ImportError:
mymodule = __import__("invenio.%s_templates" % (module), local, local,
["invenio.templates.%s" % (module)])
if CFG_WEBSTYLE_INSPECT_TEMPLATES:
for method_name in dir(mymodule.Template):
if method_name.startswith('tmpl_'):
enhance_method(module, mymodule.Template, method_name, method_wrapper)
return mymodule.Template()
# Functions to check that customized templates functions conform to
# the default templates functions
##
def check(default_base_dir=None, custom_base_dir=None):
"""
Check that installed customized templates are conform to the
default templates interfaces.
Result of the analysis is reported back in 'messages' object
(see 'messages' structure description in print_messages(..) docstring)
"""
messages = []
if CFG_WEBSTYLE_PYLIBDIR is None:
# Nothing to check, since Invenio has not been installed
messages.append(('C', "Nothing to check. Run 'make install' first.",
'',
None,
0))
return messages
# Iterage over all customized templates
for (default_template_path, custom_template_path) in \
get_custom_templates(get_default_templates(default_base_dir), custom_base_dir):
# Load the custom and default templates
default_tpl_path, default_tpl_name = os.path.split(default_template_path)
if default_tpl_path not in sys.path:
sys.path.append(default_tpl_path)
custom_tpl_path, custom_tpl_name = os.path.split(custom_template_path)
if custom_tpl_path not in sys.path:
sys.path.append(custom_tpl_path)
default_template = __import__(default_tpl_name[:-3],
globals(),
locals(),
[''])
custom_template = __import__(custom_tpl_name[:-3],
globals(),
locals(),
[''])
# Check if Template class is in the file
classes = inspect.getmembers(custom_template, inspect.isclass)
if 'Template' not in [possible_class[0] for possible_class in classes]:
messages.append(('E', "'Template' class missing",
custom_template.__name__,
None,
0))
continue
# Check customized functions parameters
for (default_function_name, default_function) in \
inspect.getmembers(default_template.Template, inspect.isroutine):
if custom_template.Template.__dict__.has_key(default_function_name):
# Customized function exists
custom_function = custom_template.Template.__dict__[default_function_name]
(deft_args, deft_varargs, deft_varkw, deft_defaults) = \
inspect.getargspec(default_function.im_func)
(cust_args, cust_varargs, cust_varkw, cust_defaults) = \
inspect.getargspec(custom_function)
deft_args.reverse()
if deft_defaults is not None:
deft_defaults_list = list(deft_defaults)
deft_defaults_list.reverse()
else:
deft_defaults_list = []
cust_args.reverse()
if cust_defaults is not None:
cust_defaults_list = list(cust_defaults)
cust_defaults_list.reverse()
else:
cust_defaults_list = []
arg_errors = False
# Check for presence of missing parameters in custom template
for deft_arg in deft_args:
if deft_arg not in cust_args:
arg_errors = True
messages.append(('E', "missing '%s' parameter" % \
deft_arg,
custom_tpl_name,
default_function_name,
inspect.getsourcelines(custom_function)[1]))
# Check for presence of additional parameters in custom template
for cust_arg in cust_args:
if cust_arg not in deft_args:
arg_errors = True
messages.append(('E', "unknown parameter '%s'" % \
cust_arg,
custom_tpl_name,
custom_function.__name__,
inspect.getsourcelines(custom_function)[1]))
# If parameter is deprecated, report it
module_name = default_tpl_name.split("_")[0]
if CFG_WEBSTYLE_DEPRECATED_PARAMETERS.has_key(module_name) and \
CFG_WEBSTYLE_DEPRECATED_PARAMETERS[module_name].has_key(default_function_name) and \
CFG_WEBSTYLE_DEPRECATED_PARAMETERS[module_name][default_function_name].has_key(cust_arg):
messages.append(('C', CFG_WEBSTYLE_DEPRECATED_PARAMETERS[module_name][default_function_name][cust_arg],
custom_tpl_name,
custom_function.__name__,
inspect.getsourcelines(custom_function)[1]))
# Check for same ordering of parameters.
# Only raise warning if previous parameter tests did
# not generate errors
if not arg_errors:
for cust_arg, deft_arg in map(None, cust_args, deft_args):
if deft_arg != cust_arg:
arg_errors = True
messages.append(('W', "order of parameters is not respected",
custom_tpl_name,
custom_function.__name__,
inspect.getsourcelines(custom_function)[1]))
break
# Check for equality of default parameters values
# Only raise warning if previous parameter tests did
# not generate errors or warnings
if not arg_errors:
i = 0
for cust_default, deft_default in \
map(None, cust_defaults_list, deft_defaults_list):
if deft_default != cust_default:
messages.append(('W', "default value for parameter '%s' is not respected" % \
cust_args[i],
custom_tpl_name,
default_function_name,
inspect.getsourcelines(custom_function)[1]))
i += 1
else:
# Function is not in custom template. Generate warning?
pass
# Check for presence of additional functions in custom template
for (custom_function_name, custom_function) in \
inspect.getmembers(custom_template.Template, inspect.isroutine):
if not default_template.Template.__dict__.has_key(custom_function_name):
messages.append(('W', "unknown function",
custom_tpl_name,
custom_function_name,
inspect.getsourcelines(custom_function)[1]))
# If the function was deprecated, report it
module_name = default_tpl_name.split("_")[0]
if CFG_WEBSTYLE_DEPRECATED_FUNCTIONS.has_key(module_name) and \
CFG_WEBSTYLE_DEPRECATED_FUNCTIONS[module_name].has_key(custom_function_name):
messages.append(('C', CFG_WEBSTYLE_DEPRECATED_FUNCTIONS[module_name][custom_function_name],
custom_tpl_name,
custom_function_name,
inspect.getsourcelines(custom_function)[1]))
return messages
# Utility functions
##
def get_default_templates(base_dir=None):
"""
Returns the paths to all default Invenio templates.
base_dir - path to where templates should be recursively searched
"""
# If base_dir is not specified we assume that this template.py
# file is located in modules/webstyle/lib, which allows
# us to guess where base Invenio modules dir is.
# Note that by luck it also works if file is installed
# in /lib/python/invenio/
if base_dir is None:
# Retrieve path to Invenio 'modules' dir
this_pathname = os.path.abspath(sys.argv[0])
#this_pathname = inspect.getsourcefile(get_default_templates)
this_dir, this_name = os.path.split(this_pathname)
base_dir = this_dir + os.sep + os.pardir + \
os.sep + os.pardir
else:
base_dir = os.path.abspath(base_dir)
templates_path = []
for (dirpath, dirnames, filenames) in os.walk(base_dir):
for filename in filenames:
if filename.endswith("_templates.py"):
templates_path.append(os.path.join(dirpath, filename))
return templates_path
def get_custom_templates(default_templates_paths, base_dir=None):
"""
Returns the paths to customized templates among the given list of
templates paths.
"""
return [(default, get_custom_template(default, base_dir)) \
for default in default_templates_paths \
if get_custom_template(default, base_dir) is not None]
def get_custom_template(default_template_path, base_dir=None):
"""
Returns the path to the customized template of the default
template given as parameter. Returns None if customized does not
exist.
"""
default_tpl_path, default_tpl_name = os.path.split(default_template_path)
if base_dir is None:
custom_path = CFG_WEBSTYLE_PYLIBDIR + \
os.sep + "invenio" + os.sep + \
default_tpl_name[:-3] + '_' + \
CFG_WEBSTYLE_TEMPLATE_SKIN + '.py'
else:
custom_path = os.path.abspath(base_dir) + os.sep + \
default_tpl_name[:-3] + '_' + \
CFG_WEBSTYLE_TEMPLATE_SKIN + '.py'
if os.path.exists(custom_path):
return custom_path
else:
return None
def print_messages(messages,
verbose=2):
"""
Report errors and warnings to user.
messages - list of tuples (type, message, template, function, line)
where: - type : One of the strings:
- 'E': Error
- 'W': Warning
- 'C': Comment
- message : The string message
- template : template name where message occurred
- function : function name where message occurred
- line : line number where message occurred
verbose - int specifying the verbosity of the output.
0 - summary only
1 - summary + errors
2 - summary + errors + warnings
3 - summary + errors + warnings + comments
"""
last_template = '' # Remember last considered template in order to
# print separator between templates
for message in messages:
if message[0] == 'F' and verbose >= 0 or \
message[0] == 'E' and verbose >= 1 or \
message[0] == 'W' and verbose >= 2 or \
message[0] == 'C' and verbose >= 3:
# Print separator if we have moved to another template
if last_template != message[2]:
print "************* Template %s" % message[2]
last_template = message[2]
print '%s:%s:%s%s' % \
(message[0],
message[4],
# message[2].endswith('.py') and message[2][:-3] or \
# message[2],
message[3] and ("%s(): " % message[3]) or ' ',
message[1])
# Print summary
if verbose >= 0:
nb_errors = len([message for message in messages \
if message[0] == 'E'])
nb_warnings = len([message for message in messages \
if message[0] == 'W'])
nb_comments = len([message for message in messages \
if message[0] == 'C'])
if len(messages) > 0:
print '\nFAILED'
else:
print '\nOK'
print "%i error%s, %i warning%s, %i comment%s." % \
(nb_errors, nb_errors > 1 and 's' or '',
nb_warnings, nb_warnings > 1 and 's' or '',
nb_comments, nb_comments > 1 and 's' or '')
def usage(exitcode=1):
"""
Print usage of the template checking utility
"""
print """Usage: python templates.py --check-custom-templates [options]
Options:
-v, --verbose Verbose level (0=min, 2=default, 3=max).
-d, --default-templates-dir path to a directory with the default
template(s) (default: Invenio install
dir if run from Invenio install dir, or
Invenio source if run from Invenio sources)
-c, --custom-templates-dir path to a directory with your custom
template(s) (default: Invenio install dir)
-h, --help Prints this help
Check that your custom templates are synchronized with default Invenio templates.
Examples: $ python templates.py --check-custom-templates
$ python templates.py --check-custom-templates -c~/webstyle_template_ithaca.py
"""
sys.exit(exitcode)
if __name__ == "__main__" and \
'--check-custom-templates' in sys.argv:
default_base_dir = None
custom_base_dir = None
verbose = 2
try:
opts, args = getopt.getopt(sys.argv[1:], "hv:d:c:",
["help",
"verbose=",
"default-templates-dir=",
"custom-templates-dir=",
"check-custom-templates"])
except getopt.GetoptError, err:
usage(1)
try:
for opt in opts:
if opt[0] in ["-h", "--help"]:
usage()
elif opt[0] in ["-v", "--verbose"]:
verbose = opt[1]
elif opt[0] in ["-d", "--default-templates-dir"]:
default_base_dir = opt[1]
elif opt[0] in ["-c", "--custom-templates-dir"]:
custom_base_dir = opt[1]
except StandardError, e:
usage(1)
messages_ = check(default_base_dir, custom_base_dir)
print_messages(messages_, verbose=verbose)
| gpl-2.0 |
stormi/tsunami | src/secondaires/auberge/editeurs/aubedit/__init__.py | 1 | 3821 | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
"""Package contenant l'éditeur d'auberge 'aubedit'.
Si des redéfinitions de contexte-éditeur standard doivent être faites, elles
seront placées dans ce package
Note importante : ce package contient la définition d'un éditeur, mais
celui-ci peut très bien être étendu par d'autres modules. Au quel cas,
les extensions n'apparaîtront pas ici.
"""
from primaires.interpreteur.editeur.presentation import Presentation
from primaires.interpreteur.editeur.uniligne import Uniligne
from secondaires.auberge.editeurs.aubedit.edt_chambres import EdtChambres
class EdtAubedit(Presentation):
"""Classe définissant l'éditeur d'auberge."""
nom = "aubedit"
def __init__(self, personnage, auberge):
"""Constructeur de l'éditeur"""
if personnage:
instance_connexion = personnage.instance_connexion
else:
instance_connexion = None
Presentation.__init__(self, instance_connexion, auberge)
if personnage and auberge:
self.construire(auberge)
def __getnewargs__(self):
return (None, None)
def construire(self, auberge):
"""Construction de l'éditeur"""
# Titre
titre = self.ajouter_choix("titre", "t", Uniligne, auberge, "titre")
titre.parent = self
titre.prompt = "Titre de l'auberge : "
titre.apercu = "{objet.titre}"
titre.aide_courte = \
"Entrez le |ent|titre|ff| de l'auberge ou |cmd|/|ff| pour " \
"revenir à la fenêtre parente.\n\nTitre actuel : " \
"|bc|{objet.titre}|ff|"
# Clé de l'aubergiste
cle = self.ajouter_choix("clé de l'aubergiste", "a", Uniligne,
auberge, "cle_aubergiste")
cle.parent = self
cle.prompt = "Clé du prototype de l'aubergiste : "
cle.apercu = "{objet.cle_aubergiste}"
cle.aide_courte = \
"Entrez la |ent|clé de l'aubergiste|ff| ou |cmd|/|ff| pour " \
"revenir à la fenêtre parente.\n\nClé actuelle : " \
"|bc|{objet.cle_aubergiste}|ff|"
# Chambres
chambres = self.ajouter_choix("chambres", "c", EdtChambres, auberge)
chambres.parent = self
chambres.apercu = "\n{objet.aff_chambres}"
| bsd-3-clause |
flathat/IS4C | fannie/legacy/it/paydays.py | 12 | 1146 | #!/usr/bin/python
import datetime
import Sybase
paydays = {
'2011-01-07' : 1,
'2011-01-21' : 1,
'2011-02-07' : 1,
'2011-02-23' : 1,
'2011-03-07' : 1,
'2011-03-22' : 1,
'2011-04-07' : 1,
'2011-04-22' : 1,
'2011-05-06' : 1,
'2011-05-23' : 1,
'2011-06-07' : 1,
'2011-06-22' : 1,
'2011-07-07' : 1,
'2011-07-22' : 1,
'2011-08-08' : 1,
'2011-08-22' : 1,
'2011-09-08' : 1,
'2011-09-22' : 1,
'2011-10-07' : 1,
'2011-10-21' : 1,
'2011-11-07' : 1,
'2011-11-22' : 1,
'2011-12-07' : 1,
'2011-12-22' : 1,
'2012-01-06' : 1,
'2010-12-22' : 1
}
today = datetime.date.today()
if paydays.has_key(str(today)):
fp = open('/var/www/html/git/fannie/src/Credentials/GenericDB.python')
line = fp.read().strip()
fp.close()
hostname,username,pw = line.split(",")
conn = Sybase.connect(hostname,username,pw)
db = conn.cursor()
db.execute('use WedgePOS')
db.execute('INSERT INTO dtransactions SELECT * FROM staffaradjview')
db.execute("""UPDATE custdata SET balance=balance-s.total
FROM custdata AS c
INNER JOIN staffArAdjView AS s
ON c.cardno=s.card_no""")
print "Staff IOUs are being cleared"
conn.commit()
conn.close()
| gpl-2.0 |
DucQuang1/BuildingMachineLearningSystemsWithPython | ch10/neighbors.py | 21 | 1787 | # 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
import numpy as np
import mahotas as mh
from glob import glob
from features import texture, color_histogram
from matplotlib import pyplot as plt
from sklearn.preprocessing import StandardScaler
from scipy.spatial import distance
basedir = '../SimpleImageDataset/'
haralicks = []
chists = []
print('Computing features...')
# Use glob to get all the images
images = glob('{}/*.jpg'.format(basedir))
# We sort the images to ensure that they are always processed in the same order
# Otherwise, this would introduce some variation just based on the random
# ordering that the filesystem uses
images.sort()
for fname in images:
imc = mh.imread(fname)
imc = imc[200:-200,200:-200]
haralicks.append(texture(mh.colors.rgb2grey(imc)))
chists.append(color_histogram(imc))
haralicks = np.array(haralicks)
chists = np.array(chists)
features = np.hstack([chists, haralicks])
print('Computing neighbors...')
sc = StandardScaler()
features = sc.fit_transform(features)
dists = distance.squareform(distance.pdist(features))
print('Plotting...')
fig, axes = plt.subplots(2, 9, figsize=(16,8))
# Remove ticks from all subplots
for ax in axes.flat:
ax.set_xticks([])
ax.set_yticks([])
for ci,i in enumerate(range(0,90,10)):
left = images[i]
dists_left = dists[i]
right = dists_left.argsort()
# right[0] is the same as left[i], so pick the next closest element
right = right[1]
right = images[right]
left = mh.imread(left)
right = mh.imread(right)
axes[0, ci].imshow(left)
axes[1, ci].imshow(right)
fig.tight_layout()
fig.savefig('figure_neighbors.png', dpi=300)
| mit |
awalls-cx18/gnuradio | gr-filter/python/filter/rational_resampler.py | 6 | 6238 | #
# Copyright 2005,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from gnuradio import gr, gru
from . import filter_swig as filter
_plot = None
def design_filter(interpolation, decimation, fractional_bw):
"""
Given the interpolation rate, decimation rate and a fractional bandwidth,
design a set of taps.
Args:
interpolation: interpolation factor (integer > 0)
decimation: decimation factor (integer > 0)
fractional_bw: fractional bandwidth in (0, 0.5) 0.4 works well. (float)
Returns:
: sequence of numbers
"""
if fractional_bw >= 0.5 or fractional_bw <= 0:
raise ValueError("Invalid fractional_bandwidth, must be in (0, 0.5)")
beta = 7.0
halfband = 0.5
rate = float(interpolation) / float(decimation)
if(rate >= 1.0):
trans_width = halfband - fractional_bw
mid_transition_band = halfband - trans_width / 2.0
else:
trans_width = rate*(halfband - fractional_bw)
mid_transition_band = rate*halfband - trans_width / 2.0
taps = filter.firdes.low_pass(interpolation, # gain
interpolation, # Fs
mid_transition_band, # trans mid point
trans_width, # transition width
filter.firdes.WIN_KAISER,
beta) # beta
return taps
class _rational_resampler_base(gr.hier_block2):
"""
base class for all rational resampler variants.
"""
def __init__(self, resampler_base,
interpolation, decimation, taps=None, fractional_bw=None):
"""
Rational resampling polyphase FIR filter.
Either taps or fractional_bw may be specified, but not both.
If neither is specified, a reasonable default, 0.4, is used as
the fractional_bw.
Args:
interpolation: interpolation factor (integer > 0)
decimation: decimation factor (integer > 0)
taps: optional filter coefficients (sequence)
fractional_bw: fractional bandwidth in (0, 0.5), measured at final freq (use 0.4) (float)
"""
if not isinstance(interpolation, int) or interpolation < 1:
raise ValueError("interpolation must be an integer >= 1")
if not isinstance(decimation, int) or decimation < 1:
raise ValueError("decimation must be an integer >= 1")
if taps is None and fractional_bw is None:
fractional_bw = 0.4
d = gru.gcd(interpolation, decimation)
# If we have user-provided taps and the interp and decim
# values have a common divisor, we don't reduce these values
# by the GCD but issue a warning to the user that this might
# increase the complexity of the filter.
if taps and (d > 1):
gr.log.info("Rational resampler has user-provided taps but interpolation ({0}) and decimation ({1}) have a GCD of {2}, which increases the complexity of the filterbank. Consider reducing these values by the GCD.".format(interpolation, decimation, d))
# If we don't have user-provided taps, reduce the interp and
# decim values by the GCD (if there is one) and then define
# the taps from these new values.
if taps is None:
interpolation = interpolation // d
decimation = decimation // d
taps = design_filter(interpolation, decimation, fractional_bw)
self.resampler = resampler_base(interpolation, decimation, taps)
gr.hier_block2.__init__(self, "rational_resampler",
gr.io_signature(1, 1, self.resampler.input_signature().sizeof_stream_item(0)),
gr.io_signature(1, 1, self.resampler.output_signature().sizeof_stream_item(0)))
self.connect(self, self.resampler, self)
def taps(self):
return self.resampler.taps()
class rational_resampler_fff(_rational_resampler_base):
def __init__(self, interpolation, decimation, taps=None, fractional_bw=None):
"""
Rational resampling polyphase FIR filter with
float input, float output and float taps.
"""
_rational_resampler_base.__init__(self, filter.rational_resampler_base_fff,
interpolation, decimation, taps, fractional_bw)
class rational_resampler_ccf(_rational_resampler_base):
def __init__(self, interpolation, decimation, taps=None, fractional_bw=None):
"""
Rational resampling polyphase FIR filter with
complex input, complex output and float taps.
"""
_rational_resampler_base.__init__(self, filter.rational_resampler_base_ccf,
interpolation, decimation, taps, fractional_bw)
class rational_resampler_ccc(_rational_resampler_base):
def __init__(self, interpolation, decimation, taps=None, fractional_bw=None):
"""
Rational resampling polyphase FIR filter with
complex input, complex output and complex taps.
"""
_rational_resampler_base.__init__(self, filter.rational_resampler_base_ccc,
interpolation, decimation, taps, fractional_bw)
| gpl-3.0 |
Chilledheart/chromium | build/android/devil/android/perf/perf_control.py | 18 | 6143 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import atexit
import logging
from devil.android import device_errors
class PerfControl(object):
"""Provides methods for setting the performance mode of a device."""
_CPU_PATH = '/sys/devices/system/cpu'
_KERNEL_MAX = '/sys/devices/system/cpu/kernel_max'
def __init__(self, device):
self._device = device
# this will raise an AdbCommandFailedError if no CPU files are found
self._cpu_files = self._device.RunShellCommand(
'ls -d cpu[0-9]*', cwd=self._CPU_PATH, check_return=True, as_root=True)
assert self._cpu_files, 'Failed to detect CPUs.'
self._cpu_file_list = ' '.join(self._cpu_files)
logging.info('CPUs found: %s', self._cpu_file_list)
self._have_mpdecision = self._device.FileExists('/system/bin/mpdecision')
def SetHighPerfMode(self):
"""Sets the highest stable performance mode for the device."""
try:
self._device.EnableRoot()
except device_errors.CommandFailedError:
message = 'Need root for performance mode. Results may be NOISY!!'
logging.warning(message)
# Add an additional warning at exit, such that it's clear that any results
# may be different/noisy (due to the lack of intended performance mode).
atexit.register(logging.warning, message)
return
product_model = self._device.product_model
# TODO(epenner): Enable on all devices (http://crbug.com/383566)
if 'Nexus 4' == product_model:
self._ForceAllCpusOnline(True)
if not self._AllCpusAreOnline():
logging.warning('Failed to force CPUs online. Results may be NOISY!')
self._SetScalingGovernorInternal('performance')
elif 'Nexus 5' == product_model:
self._ForceAllCpusOnline(True)
if not self._AllCpusAreOnline():
logging.warning('Failed to force CPUs online. Results may be NOISY!')
self._SetScalingGovernorInternal('performance')
self._SetScalingMaxFreq(1190400)
self._SetMaxGpuClock(200000000)
else:
self._SetScalingGovernorInternal('performance')
def SetPerfProfilingMode(self):
"""Enables all cores for reliable perf profiling."""
self._ForceAllCpusOnline(True)
self._SetScalingGovernorInternal('performance')
if not self._AllCpusAreOnline():
if not self._device.HasRoot():
raise RuntimeError('Need root to force CPUs online.')
raise RuntimeError('Failed to force CPUs online.')
def SetDefaultPerfMode(self):
"""Sets the performance mode for the device to its default mode."""
if not self._device.HasRoot():
return
product_model = self._device.product_model
if 'Nexus 5' == product_model:
if self._AllCpusAreOnline():
self._SetScalingMaxFreq(2265600)
self._SetMaxGpuClock(450000000)
governor_mode = {
'GT-I9300': 'pegasusq',
'Galaxy Nexus': 'interactive',
'Nexus 4': 'ondemand',
'Nexus 5': 'ondemand',
'Nexus 7': 'interactive',
'Nexus 10': 'interactive'
}.get(product_model, 'ondemand')
self._SetScalingGovernorInternal(governor_mode)
self._ForceAllCpusOnline(False)
def GetCpuInfo(self):
online = (output.rstrip() == '1' and status == 0
for (_, output, status) in self._ForEachCpu('cat "$CPU/online"'))
governor = (output.rstrip() if status == 0 else None
for (_, output, status)
in self._ForEachCpu('cat "$CPU/cpufreq/scaling_governor"'))
return zip(self._cpu_files, online, governor)
def _ForEachCpu(self, cmd):
script = '; '.join([
'for CPU in %s' % self._cpu_file_list,
'do %s' % cmd,
'echo -n "%~%$?%~%"',
'done'
])
output = self._device.RunShellCommand(
script, cwd=self._CPU_PATH, check_return=True, as_root=True)
output = '\n'.join(output).split('%~%')
return zip(self._cpu_files, output[0::2], (int(c) for c in output[1::2]))
def _WriteEachCpuFile(self, path, value):
results = self._ForEachCpu(
'test -e "$CPU/{path}" && echo {value} > "$CPU/{path}"'.format(
path=path, value=value))
cpus = ' '.join(cpu for (cpu, _, status) in results if status == 0)
if cpus:
logging.info('Successfully set %s to %r on: %s', path, value, cpus)
else:
logging.warning('Failed to set %s to %r on any cpus', path, value)
def _SetScalingGovernorInternal(self, value):
self._WriteEachCpuFile('cpufreq/scaling_governor', value)
def _SetScalingMaxFreq(self, value):
self._WriteEachCpuFile('cpufreq/scaling_max_freq', '%d' % value)
def _SetMaxGpuClock(self, value):
self._device.WriteFile('/sys/class/kgsl/kgsl-3d0/max_gpuclk',
str(value),
as_root=True)
def _AllCpusAreOnline(self):
results = self._ForEachCpu('cat "$CPU/online"')
# TODO(epenner): Investigate why file may be missing
# (http://crbug.com/397118)
return all(output.rstrip() == '1' and status == 0
for (cpu, output, status) in results
if cpu != 'cpu0')
def _ForceAllCpusOnline(self, force_online):
"""Enable all CPUs on a device.
Some vendors (or only Qualcomm?) hot-plug their CPUs, which can add noise
to measurements:
- In perf, samples are only taken for the CPUs that are online when the
measurement is started.
- The scaling governor can't be set for an offline CPU and frequency scaling
on newly enabled CPUs adds noise to both perf and tracing measurements.
It appears Qualcomm is the only vendor that hot-plugs CPUs, and on Qualcomm
this is done by "mpdecision".
"""
if self._have_mpdecision:
script = 'stop mpdecision' if force_online else 'start mpdecision'
self._device.RunShellCommand(script, check_return=True, as_root=True)
if not self._have_mpdecision and not self._AllCpusAreOnline():
logging.warning('Unexpected cpu hot plugging detected.')
if force_online:
self._ForEachCpu('echo 1 > "$CPU/online"')
| bsd-3-clause |
argentumproject/argentum | qa/rpc-tests/wallet-accounts.py | 53 | 3154 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
start_nodes,
start_node,
assert_equal,
connect_nodes_bi,
)
class WalletAccountsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
self.node_args = [[]]
def setup_network(self):
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, self.node_args)
self.is_network_split = False
def run_test (self):
node = self.nodes[0]
# Check that there's no UTXO on any of the nodes
assert_equal(len(node.listunspent()), 0)
node.generate(101)
assert_equal(node.getbalance(), 50)
accounts = ["a","b","c","d","e"]
amount_to_send = 1.0
account_addresses = dict()
for account in accounts:
address = node.getaccountaddress(account)
account_addresses[account] = address
node.getnewaddress(account)
assert_equal(node.getaccount(address), account)
assert(address in node.getaddressesbyaccount(account))
node.sendfrom("", address, amount_to_send)
node.generate(1)
for i in range(len(accounts)):
from_account = accounts[i]
to_account = accounts[(i+1)%len(accounts)]
to_address = account_addresses[to_account]
node.sendfrom(from_account, to_address, amount_to_send)
node.generate(1)
for account in accounts:
address = node.getaccountaddress(account)
assert(address != account_addresses[account])
assert_equal(node.getreceivedbyaccount(account), 2)
node.move(account, "", node.getbalance(account))
node.generate(101)
expected_account_balances = {"": 5200}
for account in accounts:
expected_account_balances[account] = 0
assert_equal(node.listaccounts(), expected_account_balances)
assert_equal(node.getbalance(""), 5200)
for account in accounts:
address = node.getaccountaddress("")
node.setaccount(address, account)
assert(address in node.getaddressesbyaccount(account))
assert(address not in node.getaddressesbyaccount(""))
for account in accounts:
addresses = []
for x in range(10):
addresses.append(node.getnewaddress())
multisig_address = node.addmultisigaddress(5, addresses, account)
node.sendfrom("", multisig_address, 50)
node.generate(101)
for account in accounts:
assert_equal(node.getbalance(account), 50)
if __name__ == '__main__':
WalletAccountsTest().main ()
| mit |
JIoJIaJIu/servo | python/servo/devenv_commands.py | 18 | 6111 | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
from __future__ import print_function, unicode_literals
from os import path, getcwd, listdir
import subprocess
import sys
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase, cd, call
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv')
@CommandArgument(
'params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def cargo(self, params):
if not params:
params = []
if self.context.topdir == getcwd():
with cd(path.join('components', 'servo')):
return call(["cargo"] + params, env=self.build_env())
return call(['cargo'] + params, env=self.build_env())
@Command('cargo-update',
description='Same as update-cargo',
category='devenv')
@CommandArgument(
'params', default=None, nargs='...',
help='Command-line arguments to be passed through to cargo update')
@CommandArgument(
'--package', '-p', default=None,
help='Updates selected package')
@CommandArgument(
'--all-packages', '-a', action='store_true',
help='Updates all packages')
def cargo_update(self, params=None, package=None, all_packages=None):
self.update_cargo(params, package, all_packages)
@Command('update-cargo',
description='Update Cargo dependencies',
category='devenv')
@CommandArgument(
'params', default=None, nargs='...',
help='Command-line arguments to be passed through to cargo update')
@CommandArgument(
'--package', '-p', default=None,
help='Updates selected package')
@CommandArgument(
'--all-packages', '-a', action='store_true',
help='Updates all packages')
def update_cargo(self, params=None, package=None, all_packages=None):
if not params:
params = []
if package:
params += ["-p", package]
elif all_packages:
params = []
else:
print("Please choose package to update with the --package (-p) ")
print("flag or update all packages with --all-packages (-a) flag")
sys.exit(1)
cargo_paths = [path.join('components', 'servo'),
path.join('ports', 'cef'),
path.join('ports', 'geckolib'),
path.join('ports', 'gonk')]
for cargo_path in cargo_paths:
with cd(cargo_path):
print(cargo_path)
call(["cargo", "update"] + params,
env=self.build_env())
@Command('clippy',
description='Run Clippy',
category='devenv')
def clippy(self):
features = "--features=script/plugins/clippy"
with cd(path.join(self.context.topdir, "components", "servo")):
return subprocess.call(["cargo", "build", features],
env=self.build_env())
@Command('rustc',
description='Run the Rust compiler',
category='devenv')
@CommandArgument(
'params', default=None, nargs='...',
help="Command-line arguments to be passed through to rustc")
def rustc(self, params):
if params is None:
params = []
return call(["rustc"] + params, env=self.build_env())
@Command('rust-root',
description='Print the path to the root of the Rust compiler',
category='devenv')
def rust_root(self):
print(self.config["tools"]["rust-root"])
@Command('grep',
description='`git grep` for selected directories.',
category='devenv')
@CommandArgument(
'params', default=None, nargs='...',
help="Command-line arguments to be passed through to `git grep`")
def grep(self, params):
if not params:
params = []
# get all directories under tests/
tests_dirs = listdir('tests')
# Directories to be excluded under tests/
excluded_tests_dirs = ['wpt', 'jquery']
tests_dirs = filter(lambda dir: dir not in excluded_tests_dirs, tests_dirs)
# Set of directories in project root
root_dirs = ['components', 'ports', 'python', 'etc', 'resources']
# Generate absolute paths for directories in tests/ and project-root/
tests_dirs_abs = [path.join(self.context.topdir, 'tests', s) for s in tests_dirs]
root_dirs_abs = [path.join(self.context.topdir, s) for s in root_dirs]
# Absolute paths for all directories to be considered
grep_paths = root_dirs_abs + tests_dirs_abs
return call(
["git"] + ["grep"] + params + ['--'] + grep_paths + [':(exclude)*.min.js'],
env=self.build_env())
@Command('wpt-upgrade',
description='upgrade wptrunner.',
category='devenv')
def upgrade_wpt_runner(self):
with cd(path.join(self.context.topdir, 'tests', 'wpt', 'harness')):
code = call(["git", "init"], env=self.build_env())
if code:
return code
call(
["git", "remote", "add", "upstream", "https://github.com/w3c/wptrunner.git"], env=self.build_env())
code = call(["git", "fetch", "upstream"], env=self.build_env())
if code:
return code
code = call(["git", "reset", '--', "hard", "remotes/upstream/master"], env=self.build_env())
if code:
return code
| mpl-2.0 |
maning/inasafe | extras/retired_impact_functions/tsunami_building_impact.py | 9 | 6468 | from safe.impact_functions.core import FunctionProvider
from safe.impact_functions.core import get_hazard_layer, get_exposure_layer
from safe.storage.vector import Vector
from safe.common.utilities import ugettext as tr
# Largely superseded by flood impact functions, but keep as it
# will be needed to test impact on roads from both raster and polygon
# hazard layers
class TsunamiBuildingImpactFunction(FunctionProvider):
"""Risk plugin for tsunami impact on building data
:param requires category=='hazard' and \
subcategory=='tsunami' and \
layertype in ['raster', 'vector']
:param requires category=='exposure' and \
subcategory in ['building', 'road'] and \
layertype=='vector' and \
disabled==True
"""
target_field = 'ICLASS'
plugin_name = tr('Be affected by tsunami')
def run(self, layers):
"""Risk plugin for tsunami population
"""
# Extract data
H = get_hazard_layer(layers) # Depth
E = get_exposure_layer(layers) # Building locations
# Interpolate hazard level to building locations
Hi = H.interpolate(E, attribute_name='depth')
# Extract relevant numerical data
coordinates = Hi.get_geometry()
depth = Hi.get_data()
N = len(depth)
# List attributes to carry forward to result layer
attributes = E.get_attribute_names()
# Calculate building impact according to guidelines
count3 = 0
count1 = 0
count0 = 0
population_impact = []
for i in range(N):
if H.is_raster:
# Get depth
dep = float(depth[i]['depth'])
# Classify buildings according to depth
if dep >= 3:
affected = 3 # FIXME: Colour upper bound is 100 but
count3 += 1 # does not catch affected == 100
elif 1 <= dep < 3:
affected = 2
count1 += 1
else:
affected = 1
count0 += 1
elif H.is_vector:
dep = 0 # Just put something here
cat = depth[i]['Affected']
if cat is True:
affected = 3
count3 += 1
else:
affected = 1
count0 += 1
# Collect depth and calculated damage
result_dict = {self.target_field: affected,
'DEPTH': dep}
# Carry all original attributes forward
# FIXME: This should be done in interpolation. Check.
#for key in attributes:
# result_dict[key] = E.get_data(key, i)
# Record result for this feature
population_impact.append(result_dict)
# Create report
Hname = H.get_name()
Ename = E.get_name()
if H.is_raster:
impact_summary = ('<b>In case of "%s" the estimated impact to '
'"%s" '
'is:</b><br><br><p>' % (Hname, Ename))
impact_summary += ('<table border="0" width="320px">'
' <tr><th><b>%s</b></th><th><b>%s</b></th></tr>'
' <tr></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
'</table>' % (tr('Impact'), tr('Number of buildings'),
tr('Low'), count0,
tr('Medium'), count1,
tr('High'), count3))
else:
impact_summary = ('<table border="0" width="320px">'
' <tr><th><b>%s</b></th><th><b>%s</b></th></tr>'
' <tr></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
' <tr><td>%s:</td><td>%i</td></tr>'
'</table>' % ('Terdampak oleh tsunami',
'Jumlah gedung',
'Terdampak', count3,
'Tidak terdampak', count0,
'Semua', N))
impact_summary += '<br>' # Blank separation row
impact_summary += '<b>' + tr('Assumption') + ':</b><br>'
impact_summary += ('Levels of impact are defined by BNPB\'s '
'<i>Pengkajian Risiko Bencana</i>')
impact_summary += ('<table border="0" width="320px">'
' <tr><th><b>%s</b></th><th><b>%s</b></th></tr>'
' <tr></tr>'
' <tr><td>%s:</td><td>%s:</td></tr>'
' <tr><td>%s:</td><td>%s:</td></tr>'
' <tr><td>%s:</td><td>%s:</td></tr>'
'</table>' % (tr('Impact'), tr('Tsunami height'),
tr('Low'), '<1 m',
tr('Medium'), '1-3 m',
tr('High'), '>3 m'))
# Create style
style_classes = [dict(label='< 1 m', min=0, max=1,
colour='#1EFC7C', transparency=0, size=1),
dict(label='1 - 3 m', min=1, max=2,
colour='#FFA500', transparency=0, size=1),
dict(label='> 3 m', min=2, max=4,
colour='#F31A1C', transparency=0, size=1)]
style_info = dict(target_field=self.target_field,
style_classes=style_classes)
# Create vector layer and return
if Hi.is_line_data:
name = 'Roads flooded'
elif Hi.is_point_data:
name = 'Buildings flooded'
V = Vector(data=population_impact,
projection=E.get_projection(),
geometry=coordinates,
keywords={'impact_summary': impact_summary},
geometry_type=Hi.geometry_type,
name=name,
style_info=style_info)
return V
| gpl-3.0 |
aurelijusb/arangodb | 3rdParty/V8-4.3.61/build/gyp/test/intermediate_dir/gyptest-intermediate-dir.py | 243 | 1398 | #!/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.
"""
Verifies that targets have independent INTERMEDIATE_DIRs.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('test.gyp', chdir='src')
test.build('test.gyp', 'target1', chdir='src')
# Check stuff exists.
intermediate_file1 = test.read('src/outfile.txt')
test.must_contain(intermediate_file1, 'target1')
shared_intermediate_file1 = test.read('src/shared_outfile.txt')
test.must_contain(shared_intermediate_file1, 'shared_target1')
test.run_gyp('test2.gyp', chdir='src')
# Force the shared intermediate to be rebuilt.
test.sleep()
test.touch('src/shared_infile.txt')
test.build('test2.gyp', 'target2', chdir='src')
# Check INTERMEDIATE_DIR file didn't get overwritten but SHARED_INTERMEDIATE_DIR
# file did.
intermediate_file2 = test.read('src/outfile.txt')
test.must_contain(intermediate_file1, 'target1')
test.must_contain(intermediate_file2, 'target2')
shared_intermediate_file2 = test.read('src/shared_outfile.txt')
if shared_intermediate_file1 != shared_intermediate_file2:
test.fail_test(shared_intermediate_file1 + ' != ' + shared_intermediate_file2)
test.must_contain(shared_intermediate_file1, 'shared_target2')
test.must_contain(shared_intermediate_file2, 'shared_target2')
test.pass_test()
| apache-2.0 |
MoritzS/django | tests/select_for_update/tests.py | 15 | 12203 | import threading
import time
from unittest import mock
from multiple_database.routers import TestRouter
from django.db import (
DatabaseError, connection, connections, router, transaction,
)
from django.test import (
TransactionTestCase, override_settings, skipIfDBFeature,
skipUnlessDBFeature,
)
from django.test.utils import CaptureQueriesContext
from .models import Person
class SelectForUpdateTests(TransactionTestCase):
available_apps = ['select_for_update']
def setUp(self):
# This is executed in autocommit mode so that code in
# run_select_for_update can see this data.
self.person = Person.objects.create(name='Reinhardt')
# We need another database connection in transaction to test that one
# connection issuing a SELECT ... FOR UPDATE will block.
self.new_connection = connection.copy()
def tearDown(self):
try:
self.end_blocking_transaction()
except (DatabaseError, AttributeError):
pass
self.new_connection.close()
def start_blocking_transaction(self):
self.new_connection.set_autocommit(False)
# Start a blocking transaction. At some point,
# end_blocking_transaction() should be called.
self.cursor = self.new_connection.cursor()
sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
'db_table': Person._meta.db_table,
'for_update': self.new_connection.ops.for_update_sql(),
}
self.cursor.execute(sql, ())
self.cursor.fetchone()
def end_blocking_transaction(self):
# Roll back the blocking transaction.
self.new_connection.rollback()
self.new_connection.set_autocommit(True)
def has_for_update_sql(self, queries, **kwargs):
# Examine the SQL that was executed to determine whether it
# contains the 'SELECT..FOR UPDATE' stanza.
for_update_sql = connection.ops.for_update_sql(**kwargs)
return any(for_update_sql in query['sql'] for query in queries)
@skipUnlessDBFeature('has_select_for_update')
def test_for_update_sql_generated(self):
"""
The backend's FOR UPDATE variant appears in
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update())
self.assertTrue(self.has_for_update_sql(ctx.captured_queries))
@skipUnlessDBFeature('has_select_for_update_nowait')
def test_for_update_sql_generated_nowait(self):
"""
The backend's FOR UPDATE NOWAIT variant appears in
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update(nowait=True))
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, nowait=True))
@skipUnlessDBFeature('has_select_for_update_skip_locked')
def test_for_update_sql_generated_skip_locked(self):
"""
The backend's FOR UPDATE SKIP LOCKED variant appears in
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update(skip_locked=True))
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, skip_locked=True))
@skipUnlessDBFeature('has_select_for_update_nowait')
def test_nowait_raises_error_on_block(self):
"""
If nowait is specified, we expect an error to be raised rather
than blocking.
"""
self.start_blocking_transaction()
status = []
thread = threading.Thread(
target=self.run_select_for_update,
args=(status,),
kwargs={'nowait': True},
)
thread.start()
time.sleep(1)
thread.join()
self.end_blocking_transaction()
self.assertIsInstance(status[-1], DatabaseError)
@skipUnlessDBFeature('has_select_for_update_skip_locked')
def test_skip_locked_skips_locked_rows(self):
"""
If skip_locked is specified, the locked row is skipped resulting in
Person.DoesNotExist.
"""
self.start_blocking_transaction()
status = []
thread = threading.Thread(
target=self.run_select_for_update,
args=(status,),
kwargs={'skip_locked': True},
)
thread.start()
time.sleep(1)
thread.join()
self.end_blocking_transaction()
self.assertIsInstance(status[-1], Person.DoesNotExist)
@skipIfDBFeature('has_select_for_update_nowait')
@skipUnlessDBFeature('has_select_for_update')
def test_unsupported_nowait_raises_error(self):
"""
DatabaseError is raised if a SELECT...FOR UPDATE NOWAIT is run on
a database backend that supports FOR UPDATE but not NOWAIT.
"""
with self.assertRaisesMessage(DatabaseError, 'NOWAIT is not supported on this database backend.'):
with transaction.atomic():
Person.objects.select_for_update(nowait=True).get()
@skipIfDBFeature('has_select_for_update_skip_locked')
@skipUnlessDBFeature('has_select_for_update')
def test_unsupported_skip_locked_raises_error(self):
"""
DatabaseError is raised if a SELECT...FOR UPDATE SKIP LOCKED is run on
a database backend that supports FOR UPDATE but not SKIP LOCKED.
"""
with self.assertRaisesMessage(DatabaseError, 'SKIP LOCKED is not supported on this database backend.'):
with transaction.atomic():
Person.objects.select_for_update(skip_locked=True).get()
@skipUnlessDBFeature('has_select_for_update')
def test_for_update_after_from(self):
features_class = connections['default'].features.__class__
attribute_to_patch = "%s.%s.for_update_after_from" % (features_class.__module__, features_class.__name__)
with mock.patch(attribute_to_patch, return_value=True):
with transaction.atomic():
self.assertIn('FOR UPDATE WHERE', str(Person.objects.filter(name='foo').select_for_update().query))
@skipUnlessDBFeature('has_select_for_update')
def test_for_update_requires_transaction(self):
"""
A TransactionManagementError is raised
when a select_for_update query is executed outside of a transaction.
"""
with self.assertRaises(transaction.TransactionManagementError):
list(Person.objects.all().select_for_update())
@skipUnlessDBFeature('has_select_for_update')
def test_for_update_requires_transaction_only_in_execution(self):
"""
No TransactionManagementError is raised
when select_for_update is invoked outside of a transaction -
only when the query is executed.
"""
people = Person.objects.all().select_for_update()
with self.assertRaises(transaction.TransactionManagementError):
list(people)
def run_select_for_update(self, status, **kwargs):
"""
Utility method that runs a SELECT FOR UPDATE against all
Person instances. After the select_for_update, it attempts
to update the name of the only record, save, and commit.
This function expects to run in a separate thread.
"""
status.append('started')
try:
# We need to enter transaction management again, as this is done on
# per-thread basis
with transaction.atomic():
person = Person.objects.select_for_update(**kwargs).get()
person.name = 'Fred'
person.save()
except (DatabaseError, Person.DoesNotExist) as e:
status.append(e)
finally:
# This method is run in a separate thread. It uses its own
# database connection. Close it without waiting for the GC.
connection.close()
@skipUnlessDBFeature('has_select_for_update')
@skipUnlessDBFeature('supports_transactions')
def test_block(self):
"""
A thread running a select_for_update that accesses rows being touched
by a similar operation on another connection blocks correctly.
"""
# First, let's start the transaction in our thread.
self.start_blocking_transaction()
# Now, try it again using the ORM's select_for_update
# facility. Do this in a separate thread.
status = []
thread = threading.Thread(
target=self.run_select_for_update, args=(status,)
)
# The thread should immediately block, but we'll sleep
# for a bit to make sure.
thread.start()
sanity_count = 0
while len(status) != 1 and sanity_count < 10:
sanity_count += 1
time.sleep(1)
if sanity_count >= 10:
raise ValueError('Thread did not run and block')
# Check the person hasn't been updated. Since this isn't
# using FOR UPDATE, it won't block.
p = Person.objects.get(pk=self.person.pk)
self.assertEqual('Reinhardt', p.name)
# When we end our blocking transaction, our thread should
# be able to continue.
self.end_blocking_transaction()
thread.join(5.0)
# Check the thread has finished. Assuming it has, we should
# find that it has updated the person's name.
self.assertFalse(thread.isAlive())
# We must commit the transaction to ensure that MySQL gets a fresh read,
# since by default it runs in REPEATABLE READ mode
transaction.commit()
p = Person.objects.get(pk=self.person.pk)
self.assertEqual('Fred', p.name)
@skipUnlessDBFeature('has_select_for_update')
def test_raw_lock_not_available(self):
"""
Running a raw query which can't obtain a FOR UPDATE lock raises
the correct exception
"""
self.start_blocking_transaction()
def raw(status):
try:
list(
Person.objects.raw(
'SELECT * FROM %s %s' % (
Person._meta.db_table,
connection.ops.for_update_sql(nowait=True)
)
)
)
except DatabaseError as e:
status.append(e)
finally:
# This method is run in a separate thread. It uses its own
# database connection. Close it without waiting for the GC.
connection.close()
status = []
thread = threading.Thread(target=raw, kwargs={'status': status})
thread.start()
time.sleep(1)
thread.join()
self.end_blocking_transaction()
self.assertIsInstance(status[-1], DatabaseError)
@skipUnlessDBFeature('has_select_for_update')
@override_settings(DATABASE_ROUTERS=[TestRouter()])
def test_select_for_update_on_multidb(self):
query = Person.objects.select_for_update()
self.assertEqual(router.db_for_write(Person), query.db)
@skipUnlessDBFeature('has_select_for_update')
def test_select_for_update_with_get(self):
with transaction.atomic():
person = Person.objects.select_for_update().get(name='Reinhardt')
self.assertEqual(person.name, 'Reinhardt')
def test_nowait_and_skip_locked(self):
with self.assertRaisesMessage(ValueError, 'The nowait option cannot be used with skip_locked.'):
Person.objects.select_for_update(nowait=True, skip_locked=True)
def test_ordered_select_for_update(self):
"""
Subqueries should respect ordering as an ORDER BY clause may be useful
to specify a row locking order to prevent deadlocks (#27193).
"""
with transaction.atomic():
qs = Person.objects.filter(id__in=Person.objects.order_by('-id').select_for_update())
self.assertIn('ORDER BY', str(qs.query))
| bsd-3-clause |
ratschlab/ASP | applications/edrt/lle_auto_k.py | 1 | 1501 | from modshogun import *
import numpy
numpy.random.seed(40)
N = 2000
tt = numpy.array((numpy.pi)*(3+2*numpy.random.rand(N)))
height = numpy.array(numpy.random.rand(N)-0.5)
X = numpy.array([tt*numpy.cos(tt), 10*height, tt*numpy.sin(tt)])
preprocs = []
lle = LocallyLinearEmbedding()
lle.set_k(9)
preprocs.append((lle, "LLE preset k"))
lle_adaptive_k = LocallyLinearEmbedding()
lle_adaptive_k.set_k(3)
lle_adaptive_k.set_max_k(40)
lle_adaptive_k.parallel.set_num_threads(1)
lle_adaptive_k.set_auto_k(True)
preprocs.append((lle_adaptive_k, "LLE auto k"))
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
new_mpl = False
try:
swiss_roll_fig = fig.add_subplot(1,3,1, projection='3d')
new_mpl = True
except:
figure = plt.figure()
swiss_roll_fig = Axes3D(figure)
swiss_roll_fig.scatter(X[0], X[1], X[2], s=10, c=tt, cmap=plt.cm.Spectral)
plt.subplots_adjust(wspace=0.3)
plt.title('3D data')
from shogun.Features import RealFeatures
for (i, (preproc, label)) in enumerate(preprocs):
features = RealFeatures(X)
preproc.set_target_dim(2)
preproc.io.set_loglevel(MSG_DEBUG)
new_feats = preproc.embed(features).get_feature_matrix()
if not new_mpl:
preproc_subplot = fig.add_subplot(1,3,i+1)
else:
preproc_subplot = fig.add_subplot(1,3,i+2)
preproc_subplot.scatter(new_feats[0],new_feats[1], c=tt, cmap=plt.cm.Spectral)
plt.axis('tight')
plt.xticks([]), plt.yticks([])
plt.title(label + ' (k=%d)' % preproc.get_k())
plt.show()
| gpl-2.0 |
dushu1203/chromium.src | components/policy/resources/PRESUBMIT.py | 51 | 5366 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# If this presubmit check fails or misbehaves, please complain to
# mnissler@chromium.org, bartfab@chromium.org or atwilson@chromium.org.
import itertools
import sys
import xml.dom.minidom
def _GetPolicyTemplates(template_path):
# Read list of policies in the template. eval() is used instead of a JSON
# parser because policy_templates.json is not quite JSON, and uses some
# python features such as #-comments and '''strings'''. policy_templates.json
# is actually maintained as a python dictionary.
with open(template_path) as f:
template_data = eval(f.read(), {})
policies = ( policy
for policy in template_data['policy_definitions']
if policy['type'] != 'group' )
groups = ( policy['policies']
for policy in template_data['policy_definitions']
if policy['type'] == 'group' )
subpolicies = ( policy for group in groups for policy in group )
return list(itertools.chain(policies, subpolicies))
def _CheckPolicyTemplatesSyntax(input_api, output_api):
local_path = input_api.PresubmitLocalPath()
filepath = input_api.os_path.join(local_path, 'policy_templates.json')
if any(f.AbsoluteLocalPath() == filepath
for f in input_api.AffectedFiles()):
old_sys_path = sys.path
try:
tools_path = input_api.os_path.normpath(
input_api.os_path.join(local_path, input_api.os_path.pardir, 'tools'))
sys.path = [ tools_path ] + sys.path
# Optimization: only load this when it's needed.
import syntax_check_policy_template_json
checker = syntax_check_policy_template_json.PolicyTemplateChecker()
if checker.Run([], filepath) > 0:
return [output_api.PresubmitError('Syntax error(s) in file:',
[filepath])]
finally:
sys.path = old_sys_path
return []
def _CheckPolicyTestCases(input_api, output_api, policies):
# Read list of policies in chrome/test/data/policy/policy_test_cases.json.
root = input_api.change.RepositoryRoot()
policy_test_cases_file = input_api.os_path.join(
root, 'chrome', 'test', 'data', 'policy', 'policy_test_cases.json')
test_names = input_api.json.load(open(policy_test_cases_file)).keys()
tested_policies = frozenset(name.partition('.')[0]
for name in test_names
if name[:2] != '--')
policy_names = frozenset(policy['name'] for policy in policies)
# Finally check if any policies are missing.
missing = policy_names - tested_policies
extra = tested_policies - policy_names
error_missing = ('Policy \'%s\' was added to policy_templates.json but not '
'to src/chrome/test/data/policy/policy_test_cases.json. '
'Please update both files.')
error_extra = ('Policy \'%s\' is tested by '
'src/chrome/test/data/policy/policy_test_cases.json but is not'
' defined in policy_templates.json. Please update both files.')
results = []
for policy in missing:
results.append(output_api.PresubmitError(error_missing % policy))
for policy in extra:
results.append(output_api.PresubmitError(error_extra % policy))
return results
def _CheckPolicyHistograms(input_api, output_api, policies):
root = input_api.change.RepositoryRoot()
histograms = input_api.os_path.join(
root, 'tools', 'metrics', 'histograms', 'histograms.xml')
with open(histograms) as f:
tree = xml.dom.minidom.parseString(f.read())
enums = (tree.getElementsByTagName('histogram-configuration')[0]
.getElementsByTagName('enums')[0]
.getElementsByTagName('enum'))
policy_enum = [e for e in enums
if e.getAttribute('name') == 'EnterprisePolicies'][0]
policy_ids = frozenset([int(e.getAttribute('value'))
for e in policy_enum.getElementsByTagName('int')])
error_missing = ('Policy \'%s\' was added to policy_templates.json but not '
'to src/tools/metrics/histograms/histograms.xml. '
'Please update both files.')
results = []
for policy in policies:
if policy['id'] not in policy_ids:
results.append(output_api.PresubmitError(error_missing % policy['name']))
return results
def _CommonChecks(input_api, output_api):
results = []
results.extend(_CheckPolicyTemplatesSyntax(input_api, output_api))
os_path = input_api.os_path
local_path = input_api.PresubmitLocalPath()
template_path = os_path.join(local_path, 'policy_templates.json')
affected_files = input_api.AffectedFiles()
if any(f.AbsoluteLocalPath() == template_path for f in affected_files):
try:
policies = _GetPolicyTemplates(template_path)
except:
results.append(output_api.PresubmitError('Invalid Python/JSON syntax.'))
return results
results.extend(_CheckPolicyTestCases(input_api, output_api, policies))
results.extend(_CheckPolicyHistograms(input_api, output_api, policies))
return results
def CheckChangeOnUpload(input_api, output_api):
return _CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
return _CommonChecks(input_api, output_api)
| bsd-3-clause |
gramps-project/gramps | gramps/gen/utils/alive.py | 5 | 28472 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2009 Gary Burton
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
A utility to make a best guess if a person is alive. This is used to provide
privacy in reports and exports.
"""
#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
import logging
LOG = logging.getLogger(".gen.utils.alive")
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from ..display.name import displayer as name_displayer
from ..lib.date import Date, Today
from ..errors import DatabaseError
from ..const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#-------------------------------------------------------------------------
#
# Constants from config .ini keys
#
#-------------------------------------------------------------------------
# cache values; use refresh_constants() if they change
try:
from ..config import config
_MAX_AGE_PROB_ALIVE = config.get('behavior.max-age-prob-alive')
_MAX_SIB_AGE_DIFF = config.get('behavior.max-sib-age-diff')
_AVG_GENERATION_GAP = config.get('behavior.avg-generation-gap')
except ImportError:
# Utils used as module not part of GRAMPS
_MAX_AGE_PROB_ALIVE = 110
_MAX_SIB_AGE_DIFF = 20
_AVG_GENERATION_GAP = 20
#-------------------------------------------------------------------------
#
# ProbablyAlive class
#
#-------------------------------------------------------------------------
class ProbablyAlive:
"""
An object to hold the parameters for considering someone alive.
"""
def __init__(self,
db,
max_sib_age_diff=None,
max_age_prob_alive=None,
avg_generation_gap=None):
self.db = db
if max_sib_age_diff is None:
max_sib_age_diff = _MAX_SIB_AGE_DIFF
if max_age_prob_alive is None:
max_age_prob_alive = _MAX_AGE_PROB_ALIVE
if avg_generation_gap is None:
avg_generation_gap = _AVG_GENERATION_GAP
self.MAX_SIB_AGE_DIFF = max_sib_age_diff
self.MAX_AGE_PROB_ALIVE = max_age_prob_alive
self.AVG_GENERATION_GAP = avg_generation_gap
self.pset = set()
def probably_alive_range(self, person, is_spouse=False):
# FIXME: some of these computed dates need to be a span. For
# example, if a person could be born +/- 20 yrs around
# a date then it should be a span, and yr_offset should
# deal with it as well ("between 1920 and 1930" + 10 =
# "between 1930 and 1940")
if person is None:
return (None, None, "", None)
self.pset = set()
birth_ref = person.get_birth_ref()
death_ref = person.get_death_ref()
death_date = None
birth_date = None
explain = ""
# If the recorded death year is before current year then
# things are simple.
if death_ref and death_ref.get_role().is_primary():
if death_ref:
death = self.db.get_event_from_handle(death_ref.ref)
if death:
death_date = death.get_date_object()
# Look for Cause Of Death, Burial or Cremation events.
# These are fairly good indications that someone's not alive.
if not death_date:
for ev_ref in person.get_primary_event_ref_list():
if ev_ref:
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_death_fallback():
death_date = ev.get_date_object()
if not death_date.is_valid():
death_date = Today() # before today
death_date.set_modifier(Date.MOD_BEFORE)
# If they were born within X years before current year then
# assume they are alive (we already know they are not dead).
if not birth_date:
if birth_ref and birth_ref.get_role().is_primary():
birth = self.db.get_event_from_handle(birth_ref.ref)
if birth and birth.get_date_object().get_start_date() != Date.EMPTY:
birth_date = birth.get_date_object()
# Look for Baptism, etc events.
# These are fairly good indications that someone's birth.
if not birth_date:
for ev_ref in person.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth_fallback():
birth_date = ev.get_date_object()
if not birth_date and death_date:
# person died more than MAX after current year
if death_date.is_valid():
birth_date = death_date.copy_offset_ymd(year=-self.MAX_AGE_PROB_ALIVE)
explain = _("death date")
if not death_date and birth_date:
# person died more than MAX after current year
death_date = birth_date.copy_offset_ymd(year=self.MAX_AGE_PROB_ALIVE)
explain = _("birth date")
if death_date and birth_date:
return (birth_date, death_date, explain, person) # direct self evidence
# Neither birth nor death events are available. Try looking
# at siblings. If a sibling was born more than X years past,
# or more than Z future, then probably this person is
# not alive. If the sibling died more than X years
# past, or more than X years future, then probably not alive.
family_list = person.get_parent_family_handle_list()
for family_handle in family_list:
family = self.db.get_family_from_handle(family_handle)
if family is None:
continue
for child_ref in family.get_child_ref_list():
child_handle = child_ref.ref
child = self.db.get_person_from_handle(child_handle)
if child is None:
continue
# Go through once looking for direct evidence:
for ev_ref in child.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
# if sibling birth date too far away, then not alive:
year = dobj.get_year()
if year != 0:
# sibling birth date
return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF),
Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF + self.MAX_AGE_PROB_ALIVE),
_("sibling birth date"),
child)
elif ev and ev.type.is_death():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
# if sibling death date too far away, then not alive:
year = dobj.get_year()
if year != 0:
# sibling death date
return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE),
Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE
+ self.MAX_AGE_PROB_ALIVE),
_("sibling death date"),
child)
# Go through again looking for fallback:
for ev_ref in child.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
# if sibling birth date too far away, then not alive:
year = dobj.get_year()
if year != 0:
# sibling birth date
return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF),
Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF + self.MAX_AGE_PROB_ALIVE),
_("sibling birth-related date"),
child)
elif ev and ev.type.is_death_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
# if sibling death date too far away, then not alive:
year = dobj.get_year()
if year != 0:
# sibling death date
return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE),
Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE),
_("sibling death-related date"),
child)
if not is_spouse: # if you are not in recursion, let's recurse:
for family_handle in person.get_family_handle_list():
family = self.db.get_family_from_handle(family_handle)
if family:
mother_handle = family.get_mother_handle()
father_handle = family.get_father_handle()
if mother_handle == person.handle and father_handle:
father = self.db.get_person_from_handle(father_handle)
date1, date2, explain, other = self.probably_alive_range(father, is_spouse=True)
if date1 and date1.get_year() != 0:
return (Date().copy_ymd(date1.get_year() - self.AVG_GENERATION_GAP),
Date().copy_ymd(date1.get_year() - self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE),
_("a spouse's birth-related date, ") + explain, other)
elif date2 and date2.get_year() != 0:
return (Date().copy_ymd(date2.get_year() + self.AVG_GENERATION_GAP - self.MAX_AGE_PROB_ALIVE),
Date().copy_ymd(date2.get_year() + self.AVG_GENERATION_GAP),
_("a spouse's death-related date, ") + explain, other)
elif father_handle == person.handle and mother_handle:
mother = self.db.get_person_from_handle(mother_handle)
date1, date2, explain, other = self.probably_alive_range(mother, is_spouse=True)
if date1 and date1.get_year() != 0:
return (Date().copy_ymd(date1.get_year() - self.AVG_GENERATION_GAP),
Date().copy_ymd(date1.get_year() - self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE),
_("a spouse's birth-related date, ") + explain, other)
elif date2 and date2.get_year() != 0:
return (Date().copy_ymd(date2.get_year() + self.AVG_GENERATION_GAP - self.MAX_AGE_PROB_ALIVE),
Date().copy_ymd(date2.get_year() + self.AVG_GENERATION_GAP),
_("a spouse's death-related date, ") + explain, other)
# Let's check the family events and see if we find something
for ref in family.get_event_ref_list():
if ref:
event = self.db.get_event_from_handle(ref.ref)
if event:
date = event.get_date_object()
year = date.get_year()
if year != 0:
other = None
if person.handle == mother_handle and father_handle:
other = self.db.get_person_from_handle(father_handle)
elif person.handle == father_handle and mother_handle:
other = self.db.get_person_from_handle(mother_handle)
return (Date().copy_ymd(year - self.AVG_GENERATION_GAP),
Date().copy_ymd(year - self.AVG_GENERATION_GAP +
self.MAX_AGE_PROB_ALIVE),
_("event with spouse"), other)
# Try looking for descendants that were born more than a lifespan
# ago.
def descendants_too_old (person, years):
if person.handle in self.pset:
return (None, None, "", None)
self.pset.add(person.handle)
for family_handle in person.get_family_handle_list():
family = self.db.get_family_from_handle(family_handle)
if not family:
# can happen with LivingProxyDb(PrivateProxyDb(db))
continue
for child_ref in family.get_child_ref_list():
child_handle = child_ref.ref
child = self.db.get_person_from_handle(child_handle)
child_birth_ref = child.get_birth_ref()
if child_birth_ref:
child_birth = self.db.get_event_from_handle(child_birth_ref.ref)
dobj = child_birth.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
d = Date(dobj)
val = d.get_start_date()
val = d.get_year() - years
d.set_year(val)
return (d, d.copy_offset_ymd(self.MAX_AGE_PROB_ALIVE),
_("descendant birth date"),
child)
child_death_ref = child.get_death_ref()
if child_death_ref:
child_death = self.db.get_event_from_handle(child_death_ref.ref)
dobj = child_death.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP),
dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE),
_("descendant death date"),
child)
date1, date2, explain, other = descendants_too_old (child, years + self.AVG_GENERATION_GAP)
if date1 and date2:
return date1, date2, explain, other
# Check fallback data:
for ev_ref in child.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
d = Date(dobj)
val = d.get_start_date()
val = d.get_year() - years
d.set_year(val)
return (d, d.copy_offset_ymd(self.MAX_AGE_PROB_ALIVE),
_("descendant birth-related date"),
child)
elif ev and ev.type.is_death_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP),
dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE),
_("descendant death-related date"),
child)
return (None, None, "", None)
# If there are descendants that are too old for the person to have
# been alive in the current year then they must be dead.
date1, date2, explain, other = None, None, "", None
try:
date1, date2, explain, other = descendants_too_old(person, self.AVG_GENERATION_GAP)
except RuntimeError:
raise DatabaseError(
_("Database error: loop in %s's descendants") %
name_displayer.display(person))
if date1 and date2:
return (date1, date2, explain, other)
def ancestors_too_old(person, year):
if person.handle in self.pset:
return (None, None, "", None)
self.pset.add(person.handle)
LOG.debug("ancestors_too_old('%s', %s)".format(
name_displayer.display(person), year) )
family_handle = person.get_main_parents_family_handle()
if family_handle:
family = self.db.get_family_from_handle(family_handle)
if not family:
# can happen with LivingProxyDb(PrivateProxyDb(db))
return (None, None, "", None)
father_handle = family.get_father_handle()
if father_handle:
father = self.db.get_person_from_handle(father_handle)
father_birth_ref = father.get_birth_ref()
if father_birth_ref and father_birth_ref.get_role().is_primary():
father_birth = self.db.get_event_from_handle(
father_birth_ref.ref)
dobj = father_birth.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year),
dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE),
_("ancestor birth date"),
father)
father_death_ref = father.get_death_ref()
if father_death_ref and father_death_ref.get_role().is_primary():
father_death = self.db.get_event_from_handle(
father_death_ref.ref)
dobj = father_death.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE),
dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE),
_("ancestor death date"),
father)
# Check fallback data:
for ev_ref in father.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year),
dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE),
_("ancestor birth-related date"),
father)
elif ev and ev.type.is_death_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE),
dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE),
_("ancestor death-related date"),
father)
date1, date2, explain, other = ancestors_too_old (father, year - self.AVG_GENERATION_GAP)
if date1 and date2:
return date1, date2, explain, other
mother_handle = family.get_mother_handle()
if mother_handle:
mother = self.db.get_person_from_handle(mother_handle)
mother_birth_ref = mother.get_birth_ref()
if mother_birth_ref and mother_birth_ref.get_role().is_primary():
mother_birth = self.db.get_event_from_handle(mother_birth_ref.ref)
dobj = mother_birth.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year),
dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE),
_("ancestor birth date"),
mother)
mother_death_ref = mother.get_death_ref()
if mother_death_ref and mother_death_ref.get_role().is_primary():
mother_death = self.db.get_event_from_handle(
mother_death_ref.ref)
dobj = mother_death.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE),
dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE),
_("ancestor death date"),
mother)
# Check fallback data:
for ev_ref in mother.get_primary_event_ref_list():
ev = self.db.get_event_from_handle(ev_ref.ref)
if ev and ev.type.is_birth_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year),
dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE),
_("ancestor birth-related date"),
mother)
elif ev and ev.type.is_death_fallback():
dobj = ev.get_date_object()
if dobj.get_start_date() != Date.EMPTY:
return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE),
dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE),
_("ancestor death-related date"),
mother)
date1, date2, explain, other = ancestors_too_old (mother, year - self.AVG_GENERATION_GAP)
if date1 and date2:
return (date1, date2, explain, other)
return (None, None, "", None)
try:
# If there are ancestors that would be too old in the current year
# then assume our person must be dead too.
date1, date2, explain, other = ancestors_too_old (person, - self.AVG_GENERATION_GAP)
except RuntimeError:
raise DatabaseError(
_("Database error: loop in %s's ancestors") %
name_displayer.display(person))
if date1 and date2:
return (date1, date2, explain, other)
# If we can't find any reason to believe that they are dead we
# must assume they are alive.
return (None, None, "", None)
#-------------------------------------------------------------------------
#
# probably_alive
#
#-------------------------------------------------------------------------
def probably_alive(person, db,
current_date=None,
limit=0,
max_sib_age_diff=None,
max_age_prob_alive=None,
avg_generation_gap=None,
return_range=False):
"""
Return true if the person may be alive on current_date.
This works by a process of elimination. If we can't find a good
reason to believe that someone is dead then we assume they must
be alive.
:param current_date: a date object that is not estimated or modified
(defaults to today)
:param limit: number of years to check beyond death_date
:param max_sib_age_diff: maximum sibling age difference, in years
:param max_age_prob_alive: maximum age of a person, in years
:param avg_generation_gap: average generation gap, in years
"""
# First, get the real database to use all people
# for determining alive status:
birth, death, explain, relative = probably_alive_range(person, db,
max_sib_age_diff, max_age_prob_alive, avg_generation_gap)
if current_date is None:
current_date = Today()
LOG.debug("%s: b.%s, d.%s - %s".format(
" ".join(person.get_primary_name().get_text_data_list()),
birth, death, explain))
if not birth or not death:
# no evidence, must consider alive
return ((True, None, None, _("no evidence"), None) if return_range
else True)
# must have dates from here:
if limit:
death += limit # add these years to death
# Finally, check to see if current_date is between dates
result = (current_date.match(birth, ">=") and
current_date.match(death, "<="))
if return_range:
return (result, birth, death, explain, relative)
else:
return result
def probably_alive_range(person, db,
max_sib_age_diff=None,
max_age_prob_alive=None,
avg_generation_gap=None):
"""
Computes estimated birth and death dates.
Returns: (birth_date, death_date, explain_text, related_person)
"""
# First, find the real database to use all people
# for determining alive status:
from ..proxy.proxybase import ProxyDbBase
basedb = db
while isinstance(basedb, ProxyDbBase):
basedb = basedb.db
# Now, we create a wrapper for doing work:
pb = ProbablyAlive(basedb, max_sib_age_diff,
max_age_prob_alive, avg_generation_gap)
return pb.probably_alive_range(person)
def update_constants():
"""
Used to update the constants that are cached in this module.
"""
from ..config import config
global _MAX_AGE_PROB_ALIVE, _MAX_SIB_AGE_DIFF, _AVG_GENERATION_GAP
_MAX_AGE_PROB_ALIVE = config.get('behavior.max-age-prob-alive')
_MAX_SIB_AGE_DIFF = config.get('behavior.max-sib-age-diff')
_AVG_GENERATION_GAP = config.get('behavior.avg-generation-gap')
| gpl-2.0 |
adyliu/mysql-connector-python | python23/django/base.py | 1 | 20086 | # MySQL Connector/Python - MySQL driver written in Python.
"""Django database Backend using MySQL Connector/Python
This Django database backend is heavily based on the MySQL backend coming
with Django.
Changes include:
* Support for microseconds (MySQL 5.6.3 and later)
* Using INFORMATION_SCHEMA where possible
* Using new defaults for, for example SQL_AUTO_IS_NULL
Requires and comes with MySQL Connector/Python v1.1 and later:
http://dev.mysql.com/downloads/connector/python/
"""
from __future__ import unicode_literals
import sys
import warnings
try:
import mysql.connector
from mysql.connector.conversion import MySQLConverter
except ImportError as err:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(
"Error loading mysql.connector module: {0}".format(err))
try:
version = mysql.connector.__version_info__[0:3]
except AttributeError:
from mysql.connector.version import VERSION
version = VERSION[0:3]
if version < (1, 1):
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(
"MySQL Connector/Python v1.1.0 or newer "
"is required; you have %s" % mysql.connector.__version__)
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.utils import (six, timezone, dateparse)
from django.conf import settings
from mysql.connector.django.client import DatabaseClient
from mysql.connector.django.creation import DatabaseCreation
from mysql.connector.django.introspection import DatabaseIntrospection
from mysql.connector.django.validation import DatabaseValidation
# Raise exceptions for database warnings if DEBUG is on
# Note: PEP-249 says Warning must be subclass of StandardError
mysql.connector.Warning = Warning
if settings.DEBUG:
warnings.filterwarnings("error", category=mysql.connector.Warning)
DatabaseError = mysql.connector.DatabaseError
IntegrityError = mysql.connector.IntegrityError
class DjangoMySQLConverter(MySQLConverter):
"""Custom converter for Django"""
def _TIME_to_python(self, value, dsc=None):
"""Return MySQL TIME data type as datetime.time()
Returns datetime.time()
"""
return dateparse.parse_time(value)
def _DATETIME_to_python(self, value, dsc=None):
"""Connector/Python always returns naive datetime.datetime
Connector/Python always returns naive timestamps since MySQL has
no time zone support. Since Django needs non-naive, we need to add
the UTC time zone.
Returns datetime.datetime()
"""
if not value:
return None
dt = MySQLConverter._DATETIME_to_python(self, value)
if settings.USE_TZ and timezone.is_naive(dt):
dt = dt.replace(tzinfo=timezone.utc)
return dt
class CursorWrapper(object):
"""Wrapper around MySQL Connector/Python's cursor class.
The cursor class is defined by the options passed to MySQL
Connector/Python. If buffered option is True in those options,
MySQLCursorBuffered will be used.
"""
def __init__(self, cursor):
self.cursor = cursor
def _execute_wrapper(self, method, query, args):
"""Wrapper around execute() and executemany()"""
try:
return method(query, args)
except (mysql.connector.ProgrammingError,
mysql.connector.IntegrityError) as err:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
except mysql.connector.OperationalError as err:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
except mysql.connector.DatabaseError as err:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
def execute(self, query, args=None):
"""Executes the given operation
This wrapper method around the execute()-method of the cursor is
mainly needed to re-raise using different exceptions.
"""
return self._execute_wrapper(self.cursor.execute, query, args)
def executemany(self, query, args):
"""Executes the given operation
This wrapper method around the executemany()-method of the cursor is
mainly needed to re-raise using different exceptions.
"""
return self._execute_wrapper(self.cursor.execute, query, args)
def __getattr__(self, attr):
"""Return attribute of wrapped cursor"""
return getattr(self.cursor, attr)
def __iter__(self):
"""Returns iterator over wrapped cursor"""
return iter(self.cursor)
class DatabaseFeatures(BaseDatabaseFeatures):
"""Features specific to MySQL
Microsecond precision is supported since MySQL 5.6.3 and turned on
by default.
"""
empty_fetchmany_value = []
update_can_self_select = False
allows_group_by_pk = True
related_fields_match_type = True
allow_sliced_subqueries = False
has_bulk_insert = True
has_select_for_update = True
has_select_for_update_nowait = False
supports_forward_references = False
supports_long_model_names = False
supports_microsecond_precision = False # toggled in __init__()
supports_regex_backreferencing = False
supports_date_lookup_using_string = False
supports_timezones = False
requires_explicit_null_ordering_when_grouping = True
allows_primary_key_0 = False
uses_savepoints = True
def __init__(self, connection):
super(DatabaseFeatures, self).__init__(connection)
self.supports_microsecond_precision = self._microseconds_precision()
def _microseconds_precision(self):
if self.connection.get_server_version() >= (5, 6, 3):
return True
return False
def _mysql_storage_engine(self):
"""Get default storage engine of MySQL
This method creates a table without ENGINE table option and inspects
which engine was used.
Used by Django tests.
"""
cursor = self.connection.cursor()
tblname = 'INTROSPECT_TEST'
droptable = 'DROP TABLE IF EXISTS {table}'.format(table=tblname)
cursor.execute(droptable)
cursor.execute('CREATE TABLE {table} (X INT)'.format(table=tblname))
if self.connection.get_server_version() >= (5, 0, 0):
cursor.execute(
"SELECT ENGINE FROM INFORMATION_SCHEMA.TABLES "
"WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
(self.connection.settings_dict['NAME'], tblname))
engine = cursor.fetchone()[0]
else:
# Very old MySQL servers..
cursor.execute("SHOW TABLE STATUS WHERE Name='{table}'".format(
table=tblname))
engine = cursor.fetchone()[1]
cursor.execute(droptable)
return engine
def can_introspect_foreign_keys(self):
"""Confirm support for introspected foreign keys
Only the InnoDB storage engine supports Foreigen Key (not taking
into account MySQL Cluster here).
"""
return self._mysql_storage_engine == 'InnoDB'
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "mysql.connector.django.compiler"
def date_extract_sql(self, lookup_type, field_name):
# http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
if lookup_type == 'week_day':
# DAYOFWEEK() returns an integer, 1-7, Sunday=1.
# Note: WEEKDAY() returns 0-6, Monday=0.
return "DAYOFWEEK({0})".format(field_name)
else:
return "EXTRACT({0} FROM {1})".format(
lookup_type.upper(), field_name)
def date_trunc_sql(self, lookup_type, field_name):
"""Returns SQL simulating DATE_TRUNC
This function uses MySQL functions DATE_FORMAT and CAST to
simulate DATE_TRUNC.
The field_name is returned when lookup_type is not supported.
"""
fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s')
format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
try:
i = fields.index(lookup_type) + 1
except ValueError:
# Wrong lookup type, just return the value from MySQL as-is
sql = field_name
else:
format_str = ''.join([f for f in format[:i]] +
[f for f in format_def[i:]])
sql = "CAST(DATE_FORMAT({0}, '{1}') AS DATETIME)".format(
field_name, format_str)
return sql
def date_interval_sql(self, sql, connector, timedelta):
"""Returns SQL for calculating date/time intervals
"""
fmt = (
"({sql} {connector} INTERVAL '{days} "
"0:0:{secs}:{msecs}' DAY_MICROSECOND)"
)
return fmt.format(
sql=sql,
connector=connector,
days=timedelta.days,
secs=timedelta.seconds,
msecs=timedelta.microseconds
)
def drop_foreignkey_sql(self):
return "DROP FOREIGN KEY"
def force_no_ordering(self):
"""
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don't want any
implicit sorting going on.
"""
return ["NULL"]
def fulltext_search_sql(self, field_name):
return 'MATCH ({0}) AGAINST (%s IN BOOLEAN MODE)'.format(field_name)
def last_executed_query(self, cursor, sql, params):
return cursor.statement
def no_limit_value(self):
# 2**64 - 1, as recommended by the MySQL documentation
return 18446744073709551615
def quote_name(self, name):
if name.startswith("`") and name.endswith("`"):
return name # Quoting once is enough.
return "`{0}`".format(name)
def random_function_sql(self):
return 'RAND()'
def sql_flush(self, style, tables, sequences):
# NB: The generated SQL below is specific to MySQL
# 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
# to clear all tables of all data
if tables:
sql = ['SET FOREIGN_KEY_CHECKS = 0;']
for table in tables:
sql.append('{keyword} {table};'.format(
keyword=style.SQL_KEYWORD('TRUNCATE'),
table=style.SQL_FIELD(self.quote_name(table))))
sql.append('SET FOREIGN_KEY_CHECKS = 1;')
sql.extend(self.sequence_reset_by_name_sql(style, sequences))
return sql
else:
return []
def sequence_reset_by_name_sql(self, style, sequences):
# Truncate already resets the AUTO_INCREMENT field from
# MySQL version 5.0.13 onwards. Refs #16961.
res = []
if self.connection.get_server_version() < (5, 0, 13):
fmt = "{alter} {table} {{tablename}} {auto_inc} {field};".format(
alter=style.SQL_KEYWORD('ALTER'),
table=style.SQL_KEYWORD('TABLE'),
auto_inc=style.SQL_KEYWORD('AUTO_INCREMENT'),
field=style.SQL_FIELD('= 1')
)
for sequence in sequences:
tablename = style.SQL_TABLE(self.quote_name(sequence['table']))
res.append(fmt.format(tablename=tablename))
return res
return res
def validate_autopk_value(self, value):
# MySQLism: zero in AUTO_INCREMENT field does not work. Refs #17653.
if not value:
raise ValueError('The database backend does not accept 0 as a '
'value for AutoField.')
return value
def value_to_db_datetime(self, value):
if not value:
return None
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
if settings.USE_TZ:
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError(
"MySQL backend does not support timezone-aware times."
)
return self.connection.connection.converter._datetime_to_mysql(value)
def value_to_db_time(self, value):
if not value:
return None
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware "
"times.")
return self.connection.connection.converter._time_to_mysql(value)
def year_lookup_bounds(self, value):
# Again, no microseconds
first = '{0}-01-01 00:00:00'
second = '{0}-12-31 23:59:59.999999'
return [first.format(value), second.format(value)]
def max_name_length(self):
return 64
def bulk_insert_sql(self, fields, num_values):
items_sql = "({0})".format(", ".join(["%s"] * len(fields)))
return "VALUES " + ", ".join([items_sql] * num_values)
def savepoint_create_sql(self, sid):
return "SAVEPOINT {0}".format(sid)
def savepoint_commit_sql(self, sid):
return "RELEASE SAVEPOINT {0}".format(sid)
def savepoint_rollback_sql(self, sid):
return "ROLLBACK TO SAVEPOINT {0}".format(sid)
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'mysql'
operators = {
'exact': '= %s',
'iexact': 'LIKE %s',
'contains': 'LIKE BINARY %s',
'icontains': 'LIKE %s',
'regex': 'REGEXP BINARY %s',
'iregex': 'REGEXP %s',
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': 'LIKE BINARY %s',
'endswith': 'LIKE BINARY %s',
'istartswith': 'LIKE %s',
'iendswith': 'LIKE %s',
}
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.server_version = None
# Since some features depend on the MySQL version, we need to connect
self._connect()
self.features = DatabaseFeatures(self)
self.ops = DatabaseOperations(self)
self.client = DatabaseClient(self)
self.creation = DatabaseCreation(self)
self.introspection = DatabaseIntrospection(self)
self.validation = DatabaseValidation(self)
def _valid_connection(self):
if self.connection:
return self.connection.is_connected()
return False
def _connect(self):
"""Setup the connection with MySQL"""
kwargs = {
'charset': 'utf8',
'use_unicode': True,
'sql_mode': 'TRADITIONAL',
'buffered': True,
}
settings_dict = self.settings_dict
if settings_dict['USER']:
kwargs['user'] = settings_dict['USER']
if settings_dict['NAME']:
kwargs['database'] = settings_dict['NAME']
if settings_dict['PASSWORD']:
kwargs['passwd'] = settings_dict['PASSWORD']
if settings_dict['HOST'].startswith('/'):
kwargs['unix_socket'] = settings_dict['HOST']
elif settings_dict['HOST']:
kwargs['host'] = settings_dict['HOST']
if settings_dict['PORT']:
kwargs['port'] = int(settings_dict['PORT'])
kwargs['client_flags'] = [
# Need potentially affected rows on UPDATE
mysql.connector.constants.ClientFlag.FOUND_ROWS,
]
kwargs.update(settings_dict['OPTIONS'])
self.connection = mysql.connector.connect(**kwargs)
self.server_version = self.connection.get_server_version()
self.connection.set_converter_class(DjangoMySQLConverter)
connection_created.send(sender=self.__class__, connection=self)
if self.server_version < (5, 5, 3):
# http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_sql_auto_is_null
self.connection.cmd_query("SET SQL_AUTO_IS_NULL = 0")
def _cursor(self):
"""Return a CursorWrapper object
Returns a CursorWrapper
"""
if not self._valid_connection():
self._connect()
return CursorWrapper(self.connection.cursor())
def get_server_version(self):
"""Returns the MySQL server version of current connection
Returns a tuple
"""
return self.server_version
def disable_constraint_checking(self):
"""Disables foreign key checks
Disables foreign key checks, primarily for use in adding rows with
forward references. Always returns True,
to indicate constraint checks need to be re-enabled.
Returns True
"""
self.cursor().execute('SET @@session.foreign_key_checks = 0')
return True
def enable_constraint_checking(self):
"""Re-enable foreign key checks
Re-enable foreign key checks after they have been disabled.
"""
self.cursor().execute('SET @@session.foreign_key_checks = 1')
def check_constraints(self, table_names=None):
"""Check rows in tables for invalid foreign key references
Checks each table name in `table_names` for rows with invalid foreign
key references. This method is intended to be used in conjunction with
`disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while
constraint checks were off.
Raises an IntegrityError on the first invalid foreign key reference
encountered (if any) and provides detailed information about the
invalid reference in the error message.
Backends can override this method if they can more directly apply
constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
"""
ref_query = """
SELECT REFERRING.`{0}`, REFERRING.`{1}` FROM `{2}` as REFERRING
LEFT JOIN `{3}` as REFERRED
ON (REFERRING.`{4}` = REFERRED.`{5}`)
WHERE REFERRING.`{6}` IS NOT NULL AND REFERRED.`{7}` IS NULL"""
cursor = self.cursor()
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = \
self.introspection.get_primary_key_column(cursor, table_name)
if not primary_key_column_name:
continue
key_columns = self.introspection.get_key_columns(cursor,
table_name)
for column_name, referenced_table_name, referenced_column_name \
in key_columns:
cursor.execute(ref_query.format(primary_key_column_name,
column_name, table_name,
referenced_table_name,
column_name,
referenced_column_name,
column_name,
referenced_column_name))
for bad_row in cursor.fetchall():
msg = ("The row in table '{0}' with primary key '{1}' has "
"an invalid foreign key: {2}.{3} contains a value "
"'{4}' that does not have a corresponding value in "
"{5}.{6}.".format(table_name, bad_row[0],
table_name, column_name,
bad_row[1], referenced_table_name,
referenced_column_name))
raise utils.IntegrityError(msg)
| gpl-2.0 |
AveryPratt/data-structures | src/radix_sort.py | 1 | 2464 | """Implementation of radix sort algorithm."""
def radix_sort(itr, base=10):
"""Sort iterable using radix sort algorithm."""
divisor = base
digit = 0
try:
maximum = max(itr)
except ValueError:
return itr
while maximum > 1:
buckets = []
tmp = [num for num in itr]
for b in range(base):
buckets.append([])
for item in itr:
idx = item % divisor // base ** digit
buckets[idx].append(item)
itr = []
for bucket in buckets:
itr.extend(bucket)
divisor *= base
digit += 1
maximum /= float(base)
return itr
if __name__ == "__main__":
from timeit import Timer
print("sorting...")
cmd1 = (
"from random import Random\n" +
"rand = Random()\n" +
"pile_of_crap = []\n" +
"for i in range(10000):\n" +
" pile_of_crap.append(rand.randint(0, 1000))\n" +
"radix_sort(pile_of_crap, 2)"
)
cmd2 = (
"from random import Random\n" +
"rand = Random()\n" +
"pile_of_crap = []\n" +
"for i in range(10000):\n" +
" pile_of_crap.append(rand.randint(0, 1000))\n" +
"radix_sort(pile_of_crap)"
)
cmd3 = (
"from random import Random\n" +
"rand = Random()\n" +
"pile_of_crap = []\n" +
"for i in range(10000):\n" +
" pile_of_crap.append(rand.randint(0, 1000))\n" +
"radix_sort(pile_of_crap, 16)"
)
cmd4 = (
"from random import Random\n" +
"rand = Random()\n" +
"pile_of_crap = []\n" +
"for i in range(1000000):\n" +
" pile_of_crap.append(rand.randint(0, 1000000))\n" +
"radix_sort(pile_of_crap, 10)"
)
# timer = Timer(stmt=cmd1, setup="from __main__ import radix_sort")
# print("Sort 10,000 random numbers between 0 and 999 in binary (base 2): ", timer.timeit(1))
# timer = Timer(stmt=cmd2, setup="from __main__ import radix_sort")
# print("Sort 10,000 random numbers between 0 and 999 in decimal (base 10): ", timer.timeit(1))
# timer = Timer(stmt=cmd3, setup="from __main__ import radix_sort")
# print("Sort 10,000 random numbers between 0 and 999 in hexadecimal (base 16): ", timer.timeit(1))
timer = Timer(stmt=cmd4, setup="from __main__ import radix_sort")
print("Sort 1,000,000 random numbers between 0 and 999,999 in base 100,000: ", timer.timeit(1))
| mit |
superdesk/web-publisher | docs/conf.py | 4 | 11051 | # -*- coding: utf-8 -*-
#
# Superdesk Web Publisher documentation build configuration file, created by
# sphinx-quickstart on Wed May 27 11:27:06 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import alabaster
html_theme_path = [alabaster.get_path()]
extensions = ['alabaster']
html_theme = 'alabaster'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('_extensions'))
# loading PhpLexer
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sensio.sphinx.refinclude',
'sensio.sphinx.configurationblock',
'sensio.sphinx.phpcode',
'sensio.sphinx.bestpractice',
'sensio.sphinx.codeblock',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Superdesk Publisher'
copyright = u'2018, Sourcefabric z.ú'
author = u'Sourcefabric z.ú.'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.6.x'
# The full version, including alpha/beta/rc tags.
release = '0.5.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '_extensions', '_static', '_templates']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Sensio Extension Options ----------------------------------------------
# enable highlighting for PHP code not between ``<?php ... ?>`` by default
lexers['php'] = PhpLexer(startinline=True)
lexers['php-annotations'] = PhpLexer(startinline=True)
# use PHP as the primary domain
primary_domain = 'php'
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'logo': 'logo.png',
# 'description': "The next generation publishing platform for journalists and newsrooms",
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'SuperdeskWebPublisherdoc'
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# if not on_rtd: # only import and set the theme if we're building docs locally
# import sphinx_rtd_theme
# html_theme = 'sphinx_rtd_theme'
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# otherwise, readthedocs.org uses their theme by default, so no need to specify it
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'SuperdeskWebPublisher.tex', u'Superdesk Web Publisher Documentation',
u'Sourcefabric z.ú.', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'superdeskwebpublisher', u'Superdesk Web Publisher Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'SuperdeskWebPublisher', u'Superdesk Web Publisher Documentation',
author, 'SuperdeskWebPublisher', 'The next generation publishing platform for journalists and newsrooms',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {
# 'templates': ('http://templates-system.readthedocs.org/en/latest', None)
#}
| agpl-3.0 |
vinutah/projects | ml/pde/fd1d_heat_explicit.py | 1 | 1727 | #!/usr/bin/env python
def save_training_data(dep_var, feature_1, feature_2, feature_3, mode):
path = './data/training/'
filename = path + str(mode) + '_train.svm'
with open(filename,'a') as f:
line = str(dep_var)
line += ' 1:' + str(feature_1)
line += ' 2:' + str(feature_2)
line += ' 3:' + str(feature_3)
line += '\n'
f.write(line)
def readweights(weightsFile,w):
with open(weightsFile,'r') as f:
W = f.readlines()
w.append(W[-1].strip())
w.append(W[-2].strip())
w.append(W[-3].strip())
f.close()
return w
def fd1d_heat_explicit ( x_num, x, t, dt, cfl, rhs, bc, h, mode , weightsFile):
import numpy as np
h_new = np.zeros ( x_num )
f = rhs ( x_num, x, t )
for c in range ( 1, x_num - 1 ):
l = c - 1
r = c + 1
exeKey = 'original'
if exeKey in mode:
h_new[c] = h[c] + cfl * ( h[l] - 2.0 * h[c] + h[r] ) + dt * f[c]
save_training_data(h_new[c] , h[l] , h[c] , h[r], mode )
if mode == 'ml_model':
w = list()
w = readweights(weightsFile,w)
#print 'w[0]=%f' % ( float(str(w[0])) )
#print 'w[1]=%f' % ( float(str(w[1])) )
#print 'w[2]=%f' % ( float(str(w[2])) )
#
#print 'h[l]=%f' % ( float(str(h[l])) )
#print 'h[c]=%f' % ( float(str(h[c])) )
#print 'h[r]=%f' % ( float(str(h[r])) )
w1 = float(str(w[0]))
w2 = float(str(w[1]))
w3 = float(str(w[2]))
f1 = float(str(h[l]))
f2 = float(str(h[c]))
f3 = float(str(h[r]))
h_new[c] = w1*f1 + w2*f2 + w3*f3
h_new = bc ( x_num, x, t + dt, h_new, mode )
return h_new
| mit |
jorge2703/scikit-learn | sklearn/ensemble/__init__.py | 217 | 1307 | """
The :mod:`sklearn.ensemble` module includes ensemble-based methods for
classification and regression.
"""
from .base import BaseEnsemble
from .forest import RandomForestClassifier
from .forest import RandomForestRegressor
from .forest import RandomTreesEmbedding
from .forest import ExtraTreesClassifier
from .forest import ExtraTreesRegressor
from .bagging import BaggingClassifier
from .bagging import BaggingRegressor
from .weight_boosting import AdaBoostClassifier
from .weight_boosting import AdaBoostRegressor
from .gradient_boosting import GradientBoostingClassifier
from .gradient_boosting import GradientBoostingRegressor
from .voting_classifier import VotingClassifier
from . import bagging
from . import forest
from . import weight_boosting
from . import gradient_boosting
from . import partial_dependence
__all__ = ["BaseEnsemble",
"RandomForestClassifier", "RandomForestRegressor",
"RandomTreesEmbedding", "ExtraTreesClassifier",
"ExtraTreesRegressor", "BaggingClassifier",
"BaggingRegressor", "GradientBoostingClassifier",
"GradientBoostingRegressor", "AdaBoostClassifier",
"AdaBoostRegressor", "VotingClassifier",
"bagging", "forest", "gradient_boosting",
"partial_dependence", "weight_boosting"]
| bsd-3-clause |
equialgo/scikit-learn | examples/neighbors/plot_digits_kde_sampling.py | 108 | 2026 | """
=========================
Kernel Density Estimation
=========================
This example shows how kernel density estimation (KDE), a powerful
non-parametric density estimation technique, can be used to learn
a generative model for a dataset. With this generative model in place,
new samples can be drawn. These new samples reflect the underlying model
of the data.
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.neighbors import KernelDensity
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
# load the data
digits = load_digits()
data = digits.data
# project the 64-dimensional data to a lower dimension
pca = PCA(n_components=15, whiten=False)
data = pca.fit_transform(digits.data)
# use grid search cross-validation to optimize the bandwidth
params = {'bandwidth': np.logspace(-1, 1, 20)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(data)
print("best bandwidth: {0}".format(grid.best_estimator_.bandwidth))
# use the best estimator to compute the kernel density estimate
kde = grid.best_estimator_
# sample 44 new points from the data
new_data = kde.sample(44, random_state=0)
new_data = pca.inverse_transform(new_data)
# turn data into a 4x11 grid
new_data = new_data.reshape((4, 11, -1))
real_data = digits.data[:44].reshape((4, 11, -1))
# plot real digits and resampled digits
fig, ax = plt.subplots(9, 11, subplot_kw=dict(xticks=[], yticks=[]))
for j in range(11):
ax[4, j].set_visible(False)
for i in range(4):
im = ax[i, j].imshow(real_data[i, j].reshape((8, 8)),
cmap=plt.cm.binary, interpolation='nearest')
im.set_clim(0, 16)
im = ax[i + 5, j].imshow(new_data[i, j].reshape((8, 8)),
cmap=plt.cm.binary, interpolation='nearest')
im.set_clim(0, 16)
ax[0, 5].set_title('Selection from the input data')
ax[5, 5].set_title('"New" digits drawn from the kernel density model')
plt.show()
| bsd-3-clause |
adw0rd/lettuce | lettuce/terminal.py | 23 | 2339 | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import platform
import struct
def get_size():
if platform.system() == "Windows":
size = get_terminal_size_win()
else:
size = get_terminal_size_unix()
if not all(size):
size = (1, 1)
return size
def get_terminal_size_win():
#Windows specific imports
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
(bufx, bufy, curx, cury, wattr, left, top, right, bottom,
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
else: # can't determine actual size - return default values
sizex, sizey = 80, 25
return sizex, sizey
def get_terminal_size_unix():
# Unix/Posix specific imports
import fcntl
import termios
def ioctl_GWINSZ(fd):
try:
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
'1234'))
except:
return None
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
cr = (os.getenv('LINES', 25), os.getenv('COLUMNS', 80))
return int(cr[1]), int(cr[0])
| gpl-3.0 |
vondrejc/FFTHomPy | tutorials/01_trig_pol.py | 1 | 5510 | from __future__ import division, print_function
print("""
This tutorial explains the usage of trigonometric polynomials and relating
operators for the use in FFT-based homogenization.
The basic classes, which are implemented in module "homogenize.matvec",
are listed here along with their important characteristics:
Grid : contains method "Grid.get_grid_coordinates", which returns coordinates
of grid points
Tensor : this class represents a tensor-valued trigonometric polynomial and is
thus the most important part of FFT-based homogenization
DFT : this class represents matrices of Discrete Fourier Transform, which is
implemented via central version of FFT algorithm
----""")
import os
import sys
sys.path.insert(0, os.path.normpath(os.path.join(sys.path[0], '..')))
import numpy as np
from ffthompy.trigpol import Grid
from ffthompy.tensors import Tensor, DFT
print("""
The work with trigonometric polynomials is shown for""")
d = 2
N = 5*np.ones(d, dtype=np.int32)
print('dimension d =', d)
print('number of grid points N =', N)
print('which is implemented as a numpy.ndarray.')
print("""
Particularly, the vector-valued trigonometric polynomial is created as an instance 'xN' of class
'Tensor' and the random values are assigned.
""")
xN = Tensor(name='trigpol_rand', shape=(d,), N=N)
xN.randomize()
print("""
Basic properties of a trigonometric polynomials can be printed with a norm
corresponding to L2 norm of trigonometric polynomial, i.e.
xN =""")
print(xN)
print("""
The values of trigonometric polynomials are stored in atribute val of type
numpy.ndarray with shape = (self.d,) + tuple(self.N), i.e.
xN.val.shape =""")
print(xN.val.shape)
print("xN.val = xN[:] =")
print(xN.val)
print("""
In order to calculate Fourier coefficients of trigonometric polynomial,
we define DFT operators that are provided in class 'DFT'. The operation
is provided by central version of FFT algorithm and is implemented in method
'DFT.__call__' and/or 'DFT.__mul__'.
""")
FN = DFT(name='forward DFT', N=N, inverese=False)
FiN = DFT(name='inverse DFT', N=N, inverse=True)
print("FN = ")
print(FN)
print("FiN = ")
print(FiN)
print("""
The result of DFT is again the same trigonometric polynomial
with representation in Fourier domain (with Fourier coefficients);
FxN = FN*xN = FN(xN) =""")
FxN = FN*xN # Fourier coefficients of xN
print(FxN)
print("""
The forward and inverse DFT are mutually inverse operations that can
be observed by calculation of variable 'xN2':
xN2 = FiN(FxN) = FiN(FN(xN)) =""")
xN2 = FiN(FxN) # values of trigonometric polynomial at grid points
print(xN2)
print("and its comparison with initial trigonometric polynomial 'xN2'")
print("(xN == xN2) = ")
print(xN == xN2)
print("""
The norm of trigonometric polynomial calculated from Fourier
coefficients corresponds to L^2 norm and is the same like for values at grid
points, which is a consequence of Parseval's identity:
xN.norm() = np.linalg.norm(xN.val)/np.prod(xN.N)**0.5 =
= (np.sum(xN.val*xN.val)/np.prod(xN.N))**0.5 = """)
print(xN.norm())
print("""FxN.norm() = np.linalg.norm(FxN.val) =
= np.sum(FxN.val*np.conj(FxN.val)).real**0.5 =""")
print(FxN.norm())
print("""
The trigonometric polynomials can be also multiplied. The standard
multiplication with '*' operations corresponds to scalar product
leading to a square of norm, i.e.
FxN.norm() = xN.norm() = (xN*xN)**0.5 = (FxN*FxN)**0.5 =""")
print((xN*xN)**0.5)
print((FxN*FxN)**0.5)
print("""
The mean value of trigonometric polynomial is calculated independently for
each component of vector-field of trigonometric polynomial. In the real space,
it can be calculated as a mean of trigonometric polynomial at grid points,
while in Fourier space, it corresponds to zero frequency placed in the
center of grid, i.e.
xN.mean()[0] = xN[0].mean() = xN.val[0].mean() = FxN[0, 2, 2].real =""")
print(xN.mean()[0])
print(xN[0].mean())
print(xN.val[0].mean())
print(FxN[0, 2, 2].real)
print("""========================
Finally, we will plot the fundamental trigonometric polynomial, which
satisfies dirac-delta property at grid points and which
plays a major way in a theory of FFT-based homogenization.
phi =""")
phi = Tensor(name='phi_N,k', N=N, shape=())
phi.val[2, 2] = 1
print(phi)
print("phi.val =")
print(phi.val)
print("""
Fourier coefficients of phi
Fphi = FN*phi = FN(phi) =""")
Fphi = FN*phi
print(Fphi)
print("Fphi.val =")
print(Fphi.val)
print("""
In order to create a plot of this polynomial, it is
evaluated on a fine grid sizing
M = 16*N =""")
M = 16*N
print(M)
print("phi_fine = phi.project(M) =")
phi_fine = phi.project(M)
print(phi_fine)
print("""The procedure is provided by VecTri.enlarge(M) function, which consists of
a calculation of Fourier coefficients, putting zeros to Fourier coefficients
with high frequencies, and inverse FFT that evaluates the polynomial on
a fine grid.
""")
print("""In order to plot this polynomial, we also set a size of a cell
Y =""")
Y = np.ones(d) # size of a cell
print(Y)
print(""" and evaluate the coordinates of grid points, which are stored in
numpy.ndarray of following shape:
coord.shape =""")
coord = Grid.get_coordinates(M, Y)
print(coord.shape)
if __name__ == "__main__":
print("""
Now, the plot of fundamental trigonometric polynomial is shown:""")
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(coord[0], coord[1], phi_fine.val)
plt.show()
print('END')
| mit |
mrGeen/eden | modules/savage/graph/canvas.py | 23 | 15960 | from base import BaseGraph
from reg import RegressionLine
from ..graphics import Canvas
from ..graphics.shapes import Circle, Line, Rectangle, Sector, Path, Square
from ..graphics.group import Group, Grouping
from ..graphics.utils import ViewBox
from ..graphics.color import white
from ..utils.struct import Vector as V, Matrix
#from ..utils.dictionary import DefaultDictionary
from re import match
from copy import deepcopy
from math import pi
class GraphCanvas (Canvas):
def __init__ (self, **attr):
Canvas.__init__ (self, **attr)
if attr.has_key ('regLine'):
self.regLine = attr['regLine']
else:
self.regLine = True
def graph (self):
parent = self
while not isinstance (parent, BaseGraph):
parent = parent.parent
return parent
def changeSize (self, dx, dy):
self.width += dx
self.height += dy
def move (self, dx, dy):
self.x += dx
self.y += dy
def makeTransform (self, minX, maxX, minY, maxY):
matrix1 = Matrix (3, 3)
matrix1.set (-minX, 0, 2)
matrix1.set (-minY, 1, 2)
currentRangeX = float (maxX - minX)
currentRangeY = float (maxY - minY)
matrix2 = Matrix (3, 3)
matrix2.set (self.width / currentRangeX, 0, 0)
matrix2.set (self.height / currentRangeY, 1, 1)
matrix3 = Matrix (3, 3)
matrix3.set (self.height, 1, 2)
matrix3.set (-1.0, 1, 1)
return (matrix3 * (matrix2 * matrix1))
def setSVG (self):
attr = Canvas.setSVG (self)
attr['viewBox'] = ViewBox (0, 0, attr['width'], attr['height'])
return attr
class ScatterCanvas (GraphCanvas):
def __init__ (self, **attr):
GraphCanvas.__init__ (self, **attr)
self.data = Grouping ()
self.dataPoints = Group (id = 'data')
def drawPoint (self, name, x, y):
settings = self.graph ().settings
self.drawPointAux (self.dataPoints, name, x, y, settings.markerType, settings.markerSize)
def drawPointAux (self, group, name, x, y, pointType, pointSize):
if pointType == 'circle':
m = Circle (radius = pointSize, x = x, y = y)
elif pointType == 'square':
half = pointSize / 2.0
m = Square (pointSize,
x = x,
y = y,
worldDeltaX = -half,
worldDeltaY = -half,
absoluteSize = True)
if name:
m.xml['has-tooltip'] = True
m.xml['tooltip-text'] = name
m.xml['has-highlight'] = True
m.xml['highlight-fill'] = 'red'
group.draw (m)
def addColor (self):
settings = self.graph ().settings
if settings.colorScheme == 'tripleAxis':
self.setTripleColor (self.dataPoints, settings.color1, settings.color2, settings.color3)
elif settings.colorScheme == 'solid':
self.setSolidColor (self.dataPoints, settings.color1)
def setSolidColor (self, group, color):
for item in group:
item.style.fill = color
item.xml['highlight-fill'] = color.interpolate (white, .35)
def setTripleColor (self, group, color1, color2, color3):
for item in group:
perX = (item.x - self.minX) / (self.maxX - self.minX)
perY = (item.y - self.minY) / (self.maxY - self.minY)
c1 = color2.interpolate (color3, perX)
c2 = color2.interpolate (color1, perY)
per = (perY + (1 - perX)) / 2.0
c = c1.interpolate (c2, per)
item.style.fill = c
item.xml['highlight-fill'] = c.interpolate (white, .35)
def setBounds (self):
self.xlist = []
self.ylist = []
for child in self.dataPoints:
self.xlist.append (child.x)
self.ylist.append (child.y)
minX = min (self.xlist)
maxX = max (self.xlist)
minY = min (self.ylist)
maxY = max (self.ylist)
rangeX = maxX - minX
rangeY = maxY - minY
self.minX = minX - rangeX * .05
self.maxX = maxX + rangeX * .05
self.minY = minY - rangeY * .05
self.maxY = maxY + rangeY * .05
self.xml['minX'] = self.minX
self.xml['maxX'] = self.maxX
self.xml['minY'] = self.minY
self.xml['maxY'] = self.maxY
def setRegLine (self):
settings = self.graph().settings
if self.regLine:
self.regLineAux (self.data, self.xlist, self.ylist,
(self.minX, self.maxX), (self.minY, self.maxY),
settings.regLineColor, settings.regLineWidth)
def regLineAux (self, group, xlist, ylist, xbounds, ybounds, color, width):
r = RegressionLine (xlist, ylist, xbounds, ybounds)
r.style.strokeWidth = width
r.style.strokeColor = color
group.draw (r)
def finalize (self):
self.draw (self.data)
if len (self.dataPoints) > 0:
self.data.draw (self.dataPoints)
self.setRegLine ()
self.addColor ()
self.data.transform = self.makeTransform (self.minX, self.maxX, self.minY, self.maxY)
class DoubleScatterCanvas (ScatterCanvas):
def __init__ (self, **attr):
ScatterCanvas.__init__ (self, **attr)
self.data2 = Grouping ()
self.dataPoints2 = Group (id = 'data2')
def drawPoint (self, name, x, y):
settings = self.graph ().settings
self.drawPointAux (self.dataPoints, name, x, y, settings.g1MarkerType, settings.g1MarkerSize)
def drawPoint2 (self, name, x, y):
settings = self.graph ().settings
self.drawPointAux (self.dataPoints2, name, x, y, settings.g2MarkerType, settings.g2MarkerSize)
def addColor (self):
settings = self.graph ().settings
if settings.g1ColorScheme == 'tripleAxis':
self.setTripleColor (self.dataPoints, settings.g1Color1, settings.g1Color2, settings.g1Color3)
elif settings.g1ColorScheme == 'solid':
self.setSolidColor (self.dataPoints, settings.g1Color1)
if settings.g2ColorScheme == 'tripleAxis':
self.setTripleColor (self.dataPoints2, settings.g2Color1, settings.g2Color2, settings.g2Color3)
elif settings.g2ColorScheme == 'solid':
self.setSolidColor (self.dataPoints2, settings.g2Color1)
#for child in self.data:
# child.style.fill = self.color1
#for child in self.data2:
# child.style.fill = self.color2
def setBounds (self):
self.xlist = []
self.x2list = []
self.ylist = []
self.y2list = []
for child in self.dataPoints:
self.xlist.append (child.x)
self.ylist.append (child.y)
for child in self.dataPoints2:
self.x2list.append (child.x)
self.y2list.append (child.y)
minX = min (self.xlist + self.x2list)
maxX = max (self.xlist + self.x2list)
minY = min (self.ylist)
maxY = max (self.ylist)
minY2 = min (self.y2list)
maxY2 = max (self.y2list)
rangeX = maxX - minX
rangeY = maxY - minY
rangeY2 = maxY2 - minY2
self.minX = minX - rangeX * .05
self.maxX = maxX + rangeX * .05
self.minY= minY - rangeY * .05
self.maxY = maxY + rangeY * .05
self.minY2 = minY2 - rangeY2 * .05
self.maxY2 = maxY2 + rangeY2 * .05
self.xml['minX'] = self.minX
self.xml['maxX'] = self.maxX
self.xml['minY'] = self.minY
self.xml['maxY'] = self.maxY
self.xml['minY2'] = self.minY2
self.xml['maxY2'] = self.maxY2
def setRegLine (self):
settings = self.graph ().settings
if settings.g1RegLine:
self.regLineAux (self.data, self.xlist, self.ylist,
(self.minX, self.maxX), (self.minY, self.maxY),
settings.g1RegLineColor, settings.g1RegLineWidth)
def setRegLine2 (self):
settings = self.graph ().settings
if settings.g2RegLine:
self.regLineAux (self.data2, self.x2list, self.y2list,
(self.minX, self.maxX), (self.minY2, self.maxY2),
settings.g2RegLineColor, settings.g2RegLineWidth)
def finalize (self):
ScatterCanvas.finalize (self)
self.draw (self.data2)
if len (self.dataPoints2) > 0:
self.data2.draw(self.dataPoints2)
self.setRegLine2 ()
self.data2.transform = self.makeTransform (self.minX, self.maxX, self.minY2, self.maxY2)
class LineCanvas (GraphCanvas):
def __init__ (self, **attr):
GraphCanvas.__init__ (self, **attr)
self.data = Grouping ()
self.dataPoints = Group (id = 'data')
self.colors = {}
self.seriesLength = 1
def setBounds (self):
ylist = []
for group in self.data:
points = group.getElementByClassName ('point-group')
for child in points:
ylist.append (child.y)
self.minX = 0
self.maxX = self.seriesLength - 1
self.minY = min (ylist)
self.maxY = max (ylist)
def addColor (self):
for group in self.data:
try:
color = self.colors[group.id]
except KeyError:
color = 'black'
for child in group.getElementByClassName ('point-group'):
child.style.fill = color
group.getElementByName ('path').style.strokeColor = color
def addData (self, name, *data):
group = Group (id = name)
pointGroup = Group (className = 'point-group')
path = None
if len (data) > self.seriesLength:
self.seriesLength = len (data)
for i, val in enumerate (data):
if val is None:
continue
if not path:
path = Path ()
path.move (i, val)
else:
path.line (i, val)
c = Circle (radius = 2, x = i, y = val)
pointGroup.draw (c)
if path:
path.style.fill = 'none'
group.draw (path)
if len (pointGroup) > 0:
group.draw (pointGroup)
self.data.draw (group)
def finalize (self):
self.draw (self.data)
if len (self.dataPoints) > 0:
self.draw (self.dataPoints)
self.addColor ()
self.data.transform = self.makeTransform (self.minX, self.maxX, self.minY, self.maxY)
class BarCanvas (GraphCanvas):
def __init__ (self, **attr):
GraphCanvas.__init__ (self, **attr)
self.data = Group (id = 'data')
self.counter = 0.0
self.lastBar = 0
self.colors = {}
def addBar (self, group, name, val):
settings = self.graph ().settings
rect = Rectangle (x = self.counter, y = 0, height = val, width = 1)
self.data.draw (rect)
rect.xml['has-tooltip'] = True
rect.xml['name'] = name
rect.xml['group'] = group
if group and name:
rect.xml['data'] = str(group) + ': ' + str(name)
elif group:
rect.xml['data'] = str(group)
elif name:
rect.xml['data'] = str(name)
else:
rect.xml['data'] = None
rounded = match ('-?\d*(\.\d{2})?', str (val))
strVal = rounded.group (0);
rect.xml['tooltip-text'] = 'Value: ' + strVal
self.lastBar = self.counter + settings.barWidth
self.counter += (settings.barWidth + settings.barSpacing)
def addSpace (self):
self.counter += self.graph ().settings.blankSpace
def setBounds (self):
ylist = []
for child in self.data:
ylist.append (child.height)
if len (ylist):
minY = min (ylist)
maxY = max (ylist)
rangeY = maxY - minY
if rangeY:
self.minY = minY - rangeY * .05
self.maxY = maxY + rangeY * .05
else:
self.minY = minY - 1.0
self.maxY = maxY + 1.0
if self.lastBar:
self.minX = 0
self.maxX = self.lastBar
else:
self.minX = 0
self.maxX = 1
else:
self.minX = 0.0
self.maxX = 1.0
self.minY = 0.0
self.maxY = 1.0
self.xml['minX'] = self.minX
self.xml['maxX'] = self.maxX
self.xml['minY'] = self.minY
self.xml['maxY'] = self.maxY
self.barHeights ()
def addColor (self):
for child in self.data:
try:
key = child.xml['name']
child.style.fill = self.colors[key]
except KeyError:
child.style.fill = self.graph ().settings.barColor
if child.xml['has-tooltip']:
child.xml['has-highlight'] = True
child.xml['default-fill'] = child.style.fill
child.xml['highlight-fill'] = child.style.fill.interpolate (white, .35)
def barHeights (self):
for child in self.data:
child.y = self.minY
child.height -= self.minY
def finalize (self):
self.addColor ()
if len (self.data) > 0:
self.draw (self.data)
self.data.transform = self.makeTransform (self.minX, self.maxX, self.minY, self.maxY)
class HorizontalBarCanvas (BarCanvas):
def addBar (self, group, name, val):
settings = self.graph ().settings
rect = Rectangle (y = self.counter, x = 0, height = 1, width = val)
self.data.draw (rect)
rect.xml['has-tooltip'] = True
rect.xml['name'] = name
rect.xml['group'] = group
if group and name:
rect.xml['data'] = str(group) + ': ' + str(name)
elif group:
rect.xml['data'] = str(group)
elif name:
rect.xml['data'] = str(name)
else:
rect.xml['data'] = None
rect.xml['tooltip-text'] = 'Value: ' + str (val)
self.lastBar = self.counter + settings.barWidth
self.counter += (settings.barWidth + settings.barSpacing)
def setBounds (self):
xlist = []
for child in self.data:
xlist.append (child.width)
minX = min (xlist)
maxX = max (xlist)
self.minX = 0
self.maxX = maxX + maxX * .05
#self.minY = minY - minY * .05
self.minY = 0
self.maxY = self.lastBar
self.xml['minX'] = self.minX
self.xml['maxX'] = self.maxX
self.xml['minY'] = self.minY
self.xml['maxY'] = self.maxY
self.barHeights ()
def barHeights (self):
for child in self.data:
child.x = self.minX
child.width -= self.minX
class PieCanvas (GraphCanvas):
def __init__ (self, **attr):
GraphCanvas.__init__ (self, **attr)
self.values = []
self.names = []
def addData (self, name, value):
self.values.append (value)
self.names.append (name)
def finalize (self):
radius = min (self.width, self.height) / 2.0 - 10.0
x = self.x + self.width / 2.0
y = self.y + self.height / 2.0
total = sum (self.values)
data = zip (self.values, self.names)
data.sort ()
current = pi / 2.0
for value, name in data:
rad = (value / total) * (2 * pi)
s = Sector (radius, current, rad, x = x, y = y)
s.xml ['name'] = name
s.style.fill = 'red'
s.style.strokeWidth = .5
s.style.strokeColor = 'black'
self.draw (s)
current += rad
| mit |
simonsfoundation/CaImAn | use_cases/eLife_scripts/Figure_7-1p_striatum.py | 2 | 7274 | # -*- coding: utf-8 -*-
"""
This script reproduces the results for Figure 7, analyzing 1p microendoscopic
data using the CaImAn implementation of the CNMF-E algorithm. The algorithm
using both a patch-based and a non patch-based approach and compares them with
the results obtained from the MATLAB implementation.
More info can be found in the companion paper
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from scipy.optimize import minimize
from scipy.sparse import csc_matrix
from scipy.stats import pearsonr
from scipy.ndimage import center_of_mass
from operator import itemgetter
import h5py
import caiman as cm
from caiman.base.rois import register_ROIs
from caiman.source_extraction import cnmf
import cv2
import os
# data from https://www.dropbox.com/sh/6395g5wwlv63f0s/AACTNVivxYs7IIyeS67SdV2Qa?dl=0
base_folder = '/mnt/ceph/neuro/DataForPublications/DATA_PAPER_ELIFE/WEBSITE'
fname = os.path.join(base_folder, 'blood_vessel_10Hz.mat')
Y = h5py.File(fname)['Y'].value.astype(np.float32)
gSig = 3 # gaussian width of a 2D gaussian kernel, which approximates a neuron
gSiz = 13 # average diameter of a neuron
#%% perform memory mapping and loading
fname_new = cm.save_memmap([Y], base_name='Yr', order='C')
Yr, dims, T = cm.load_memmap(fname_new)
Y = Yr.T.reshape((T,) + dims, order='F')
#%% run w/o patches
dview, n_processes = None, 2
cnm = cnmf.CNMF(n_processes=n_processes, method_init='corr_pnr', k=None, dview=dview,
gSig=(gSig, gSig), gSiz=(gSiz, gSiz), merge_thresh=.65, p=1, tsub=1, ssub=1,
only_init_patch=True, gnb=0, min_corr=.7, min_pnr=7, normalize_init=False,
ring_size_factor=1.4, center_psf=True, ssub_B=2, init_iter=1, s_min=-10)
cnm.fit(Y)
#%% run w/ patches
c, dview, n_processes = cm.cluster.setup_cluster(
backend='local', n_processes=None, single_thread=False)
cnmP = cnmf.CNMF(n_processes=n_processes, method_init='corr_pnr', k=None, dview=dview,
gSig=(gSig, gSig), gSiz=(gSiz, gSiz), merge_thresh=.65, p=1, tsub=1, ssub=1,
only_init_patch=True, gnb=0, min_corr=.7, min_pnr=7, normalize_init=False,
ring_size_factor=1.4, center_psf=True, ssub_B=2, init_iter=1, s_min=-10,
nb_patch=0, del_duplicates=True, rf=(64, 64), stride=(32, 32))
cnmP.fit(Y)
#%% DISCARD LOW QUALITY COMPONENT
def discard(cnm, final_frate=10,
r_values_min=0.1, # threshold on space consistency
fitness_min=-20, # threshold on time variability
# threshold on time variability (if nonsparse activity)
fitness_delta_min=-30,
Npeaks=10):
traces = cnm.estimates.C + cnm.estimates.YrA
idx_components, idx_components_bad = cm.components_evaluation.estimate_components_quality(
traces, Yr, cnm.estimates.A, cnm.estimates.C, cnm.estimates.b, cnm.estimates.f, final_frate=final_frate, Npeaks=Npeaks,
r_values_min=r_values_min, fitness_min=fitness_min, fitness_delta_min=fitness_delta_min)
print(('Keeping ' + str(len(idx_components)) +
' and discarding ' + str(len(idx_components_bad))))
A_ = cnm.estimates.A[:, idx_components]
C_ = cnm.estimates.C[idx_components]
return A_, C_, traces[idx_components]
A_, C_, traces = discard(cnm)
A_P, C_P, tracesP = discard(cnmP)
# DISCARD TOO SMALL COMPONENT
notsmall = np.sum(A_.toarray() > 0, 0) >= 125
A_ = A_[:, notsmall]
C_ = C_[notsmall]
notsmall = np.sum(A_P.toarray() > 0, 0) >= 125
A_P = A_P[:, notsmall]
C_P = C_P[notsmall]
# DISCARD TOO ECCENTRIC COMPONENT
def aspect_ratio(img):
M = cv2.moments(img)
cov = np.array([[M['mu20'], M['mu11']], [M['mu11'], M['mu02']]]) / M['m00']
EV = np.sort(np.linalg.eigh(cov)[0])
return np.sqrt(EV[1] / EV[0])
def keep_ecc(A, thresh=3):
ar = np.array([aspect_ratio(a.reshape(dims)) for a in A.T])
notecc = ar < thresh
centers = np.array([center_of_mass(a.reshape(dims)) for a in A.T])
border = np.array([c.min() < 3 or (np.array(dims) - c).min() < 3 for c in centers])
return notecc | border
keep = keep_ecc(A_.toarray())
A_ = A_[:, keep]
C_ = C_[keep]
keep = keep_ecc(A_P.toarray())
A_P = A_P[:, keep]
C_P = C_P[keep]
#%% load matlab results and match ROIs
A, C_raw, C = itemgetter('A', 'C_raw', 'C')(loadmat(
os.path.join(base_folder, 'results_bk.mat')))
A_ = csc_matrix(A_.toarray().reshape(
dims + (-1,), order='C').reshape((-1, A_.shape[-1]), order='F'))
A_P = csc_matrix(A_P.toarray().reshape(
dims + (-1,), order='C').reshape((-1, A_P.shape[-1]), order='F'))
ids = [616, 524, 452, 305, 256, 573, 181, 574, 575, 619]
def match(a, c):
matched_ROIs1, matched_ROIs2, non_matched1, non_matched2, performance, A2 = register_ROIs(
A, a, dims, align_flag=False, thresh_cost=.7)
cor = [pearsonr(c1, c2)[0] for (c1, c2) in
np.transpose([C[matched_ROIs1], c[matched_ROIs2]], (1, 0, 2))]
print(np.mean(cor), np.median(cor))
return matched_ROIs2[[list(matched_ROIs1).index(i) for i in ids]]
ids_ = match(A_, C_)
# {'f1_score': 0.9033778476040848, 'recall': 0.8468335787923417, 'precision': 0.968013468013468, 'accuracy': 0.8237822349570201}
# (0.7831526916134324, 0.8651673117308342)
ids_P = match(A_P, C_P)
# {'f1_score': 0.8979591836734694, 'recall': 0.8424153166421208, 'precision': 0.9613445378151261, 'accuracy': 0.8148148148148148}
# (0.7854095007286398, 0.870879114022712)
#%% plot ROIs and traces
cn_filter, pnr = cm.summary_images.correlation_pnr(
Y, gSig=gSig, center_psf=True, swap_dim=False)
fig = plt.figure(figsize=(30, 10))
fig.add_axes([0, 0, .33, 1])
plt.rc('lines', lw=1.2)
cm.utils.visualization.plot_contours(
A, cn_filter.T, thr=.6, vmax=0.95, colors='w', display_numbers=False)
cm.utils.visualization.plot_contours(
A_P[:, np.array([i not in ids_P for i in range(A_P.shape[1])])], cn_filter,
thr=.6, vmax=0.95, colors='r', display_numbers=False)
plt.rc('lines', lw=3.5)
for k, i in enumerate(ids_P):
cm.utils.visualization.plot_contours(
A_P[:, i], cn_filter.T, thr=.7, vmax=0.95, colors='C%d' % k, display_numbers=False)
plt.rc('lines', lw=1.5)
plt.plot([1, 2], zorder=-100, lw=3, c='w', label='Zhou et al.')
plt.plot([1, 2], zorder=-100, lw=3, c='r', label='patches')
lg = plt.legend(loc=(.44, .9), frameon=False, fontsize=20)
for text in lg.get_texts():
text.set_color('w')
plt.axis('off')
plt.xticks([])
plt.yticks([])
fig.add_axes([.33, 0, .67, 1])
for i, n in enumerate(ids):
plt.plot(.9 * C[n] / C[n].max() + (9 - i), c='k', lw=5.5, label='Zhou et al.')
a, b = minimize(lambda x:
np.sum((x[0] + x[1] * C_[ids_[i]] - C[n] / C[n].max())**2), (0, 1e-3)).x
plt.plot(.9 * (a + b * C_[ids_[i]]) + (9 - i), lw=4, c='cyan', label='no patches')
a, b = minimize(lambda x:
np.sum((x[0] + x[1] * C_P[ids_P[i]] - C[n] / C[n].max())**2), (0, 1e-3)).x
plt.plot(.9 * (a + b * C_P[ids_P[i]]) + (9 - i), lw=2.5, c='r', label='patches')
if i == 0:
plt.legend(ncol=3, loc=(.3, .96), frameon=False, fontsize=20, columnspacing=4)
plt.scatter([-100], [.45 + (9 - i)], c='C%d' % i, s=80)
plt.ylim(0, 10)
plt.axis('off')
plt.xticks([])
plt.yticks([])
plt.xlim(-350, 6050)
plt.ylim(-.1, 10.2)
plt.show() | gpl-2.0 |
iyahman/samsung-kernel-aries | tools/perf/scripts/python/sctop.py | 11180 | 1924 | # system call top
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Periodically displays system-wide system call totals, broken down by
# syscall. If a [comm] arg is specified, only syscalls called by
# [comm] are displayed. If an [interval] arg is specified, the display
# will be refreshed every [interval] seconds. The default interval is
# 3 seconds.
import os, sys, thread, time
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 sctop.py [comm] [interval]\n";
for_comm = None
default_interval = 3
interval = default_interval
if len(sys.argv) > 3:
sys.exit(usage)
if len(sys.argv) > 2:
for_comm = sys.argv[1]
interval = int(sys.argv[2])
elif len(sys.argv) > 1:
try:
interval = int(sys.argv[1])
except ValueError:
for_comm = sys.argv[1]
interval = default_interval
syscalls = autodict()
def trace_begin():
thread.start_new_thread(print_syscall_totals, (interval,))
pass
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if for_comm is not None:
if common_comm != for_comm:
return
try:
syscalls[id] += 1
except TypeError:
syscalls[id] = 1
def print_syscall_totals(interval):
while 1:
clear_term()
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
reverse = True):
try:
print "%-40s %10d\n" % (syscall_name(id), val),
except TypeError:
pass
syscalls.clear()
time.sleep(interval)
| gpl-2.0 |
apanda/phantomjs-intercept | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/closebug.py | 126 | 2748 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
_log = logging.getLogger(__name__)
class CloseBug(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.close_bug,
]
def run(self, state):
if not self._options.close_bug:
return
# Check to make sure there are no r? or r+ patches on the bug before closing.
# Assume that r- patches are just previous patches someone forgot to obsolete.
# FIXME: Should this use self.cached_lookup('bug')? It's unclear if
# state["patch"].bug_id() always equals state['bug_id'].
patches = self._tool.bugs.fetch_bug(state["patch"].bug_id()).patches()
for patch in patches:
if patch.review() == "?" or patch.review() == "+":
_log.info("Not closing bug %s as attachment %s has review=%s. Assuming there are more patches to land from this bug." % (patch.bug_id(), patch.id(), patch.review()))
return
self._tool.bugs.close_bug_as_fixed(state["patch"].bug_id(), "All reviewed patches have been landed. Closing bug.")
| bsd-3-clause |
michaelkirk/QGIS | python/plugins/GdalTools/tools/doNearBlack.py | 10 | 3764 | # -*- coding: utf-8 -*-
"""
***************************************************************************
doNearBlack.py
---------------------
Date : June 2010
Copyright : (C) 2010 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Giuseppe Sucameli'
__date__ = 'June 2010'
__copyright__ = '(C) 2010, Giuseppe Sucameli'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget
from ui_widgetNearBlack import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils
class GdalToolsDialog(QWidget, Ui_Widget, BasePluginWidget):
def __init__(self, iface):
QWidget.__init__(self)
self.iface = iface
self.setupUi(self)
BasePluginWidget.__init__(self, self.iface, "nearblack")
self.outSelector.setType( self.outSelector.FILE )
# set the default QSpinBoxes value
self.nearSpin.setValue(15)
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.nearSpin, SIGNAL("valueChanged(int)"), self.nearCheck),
(self.whiteCheckBox, SIGNAL("stateChanged(int)"))
])
self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
def onLayersChanged(self):
self.inSelector.setLayers( Utils.LayerRegistry.instance().getRasterLayers() )
def fillInputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
inputFile = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file for Near Black" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
if not inputFile:
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)
self.inSelector.setFilename(inputFile)
def fillOutputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select the raster file to save the results to" ), Utils.FileFilter.saveRastersFilter(), lastUsedFilter)
if not outputFile:
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)
self.outSelector.setFilename(outputFile)
def getArguments(self):
arguments = []
if self.whiteCheckBox.isChecked():
arguments.append( "-white")
if self.nearCheck.isChecked():
arguments.append( "-near")
arguments.append( str(self.nearSpin.value()))
arguments.append( "-o")
arguments.append( self.getOutputFileName())
arguments.append( self.getInputFileName())
return arguments
def getOutputFileName(self):
return self.outSelector.filename()
def getInputFileName(self):
return self.inSelector.filename()
def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())
| gpl-2.0 |
mweisman/QGIS | python/pyplugin_installer/unzip.py | 20 | 2023 | # -*- coding:utf-8 -*-
"""
/***************************************************************************
Plugin Installer module
unzip function
-------------------
Date : May 2013
Copyright : (C) 2013 by Borys Jurgiel
Email : info at borysjurgiel dot pl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import zipfile
import os
def unzip(file, targetDir):
""" Creates directory structure and extracts the zip contents to it.
file - the zip file to extract
targetDir - target location
"""
# create destination directory if doesn't exist
if not targetDir.endswith(':') and not os.path.exists(targetDir):
os.makedirs(targetDir)
zf = zipfile.ZipFile(file)
for name in zf.namelist():
# create directory if doesn't exist
localDir = os.path.split(name)[0]
fullDir = os.path.normpath( os.path.join(targetDir, localDir) )
if not os.path.exists(fullDir):
os.makedirs(fullDir)
# extract file
if not name.endswith('/'):
fullPath = os.path.normpath( os.path.join(targetDir, name) )
outfile = open(fullPath, 'wb')
outfile.write(zf.read(name))
outfile.flush()
outfile.close()
| gpl-2.0 |
sephii/django | django/contrib/gis/db/backends/postgis/adapter.py | 143 | 1558 | """
This object provides quoting for GEOS geometries into PostgreSQL/PostGIS.
"""
from __future__ import unicode_literals
from psycopg2 import Binary
from psycopg2.extensions import ISQLQuote
class PostGISAdapter(object):
def __init__(self, geom):
"Initializes on the geometry."
# Getting the WKB (in string form, to allow easy pickling of
# the adaptor) and the SRID from the geometry.
self.ewkb = bytes(geom.ewkb)
self.srid = geom.srid
self._adapter = Binary(self.ewkb)
def __conform__(self, proto):
# Does the given protocol conform to what Psycopg2 expects?
if proto == ISQLQuote:
return self
else:
raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?')
def __eq__(self, other):
if not isinstance(other, PostGISAdapter):
return False
return (self.ewkb == other.ewkb) and (self.srid == other.srid)
def __str__(self):
return self.getquoted()
def prepare(self, conn):
"""
This method allows escaping the binary in the style required by the
server's `standard_conforming_string` setting.
"""
self._adapter.prepare(conn)
def getquoted(self):
"Returns a properly quoted string for use in PostgreSQL/PostGIS."
# psycopg will figure out whether to use E'\\000' or '\000'
return str('ST_GeomFromEWKB(%s)' % self._adapter.getquoted().decode())
def prepare_database_save(self, unused):
return self
| bsd-3-clause |
wang701/nexus_9_flounder_kernel_src | arch/ia64/scripts/unwcheck.py | 13143 | 1714 | #!/usr/bin/python
#
# Usage: unwcheck.py FILE
#
# This script checks the unwind info of each function in file FILE
# and verifies that the sum of the region-lengths matches the total
# length of the function.
#
# Based on a shell/awk script originally written by Harish Patil,
# which was converted to Perl by Matthew Chapman, which was converted
# to Python by David Mosberger.
#
import os
import re
import sys
if len(sys.argv) != 2:
print "Usage: %s FILE" % sys.argv[0]
sys.exit(2)
readelf = os.getenv("READELF", "readelf")
start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]")
rlen_pattern = re.compile(".*rlen=([0-9]+)")
def check_func (func, slots, rlen_sum):
if slots != rlen_sum:
global num_errors
num_errors += 1
if not func: func = "[%#x-%#x]" % (start, end)
print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum)
return
num_funcs = 0
num_errors = 0
func = False
slots = 0
rlen_sum = 0
for line in os.popen("%s -u %s" % (readelf, sys.argv[1])):
m = start_pattern.match(line)
if m:
check_func(func, slots, rlen_sum)
func = m.group(1)
start = long(m.group(2), 16)
end = long(m.group(3), 16)
slots = 3 * (end - start) / 16
rlen_sum = 0L
num_funcs += 1
else:
m = rlen_pattern.match(line)
if m:
rlen_sum += long(m.group(1))
check_func(func, slots, rlen_sum)
if num_errors == 0:
print "No errors detected in %u functions." % num_funcs
else:
if num_errors > 1:
err="errors"
else:
err="error"
print "%u %s detected in %u functions." % (num_errors, err, num_funcs)
sys.exit(1)
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.