prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
<|fim_middle|>
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return np.logical_not(self._mapped_eq(other)) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
<|fim_middle|>
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return super().__ne__(other) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
<|fim_middle|>
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | mapping = getattr(args[0], 'mapping', {}) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
<|fim_middle|>
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return AliasCSRMatrix(result, mapping=self.mapping) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
<|fim_middle|>
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return result |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def <|fim_middle|>(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __new__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def <|fim_middle|>(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __array_finalize__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def <|fim_middle|>(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | _mapped_eq |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def <|fim_middle|>(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __eq__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def <|fim_middle|>(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __ne__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def <|fim_middle|>(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __init__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def <|fim_middle|>(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | format |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def <|fim_middle|>(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | format |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def <|fim_middle|>(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | mapping |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def <|fim_middle|>(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | tocoo |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def <|fim_middle|>(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __getitem__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def <|fim_middle|>(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __init__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def <|fim_middle|>(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __bool__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def <|fim_middle|>(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __array__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def <|fim_middle|>(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __init__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def <|fim_middle|>(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __str__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def <|fim_middle|>(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __eq__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def <|fim_middle|>(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __ne__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def <|fim_middle|>(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __hash__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def <|fim_middle|>(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | eye |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def <|fim_middle|>(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | first |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def <|fim_middle|>(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __eq__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def <|fim_middle|>(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | __ne__ |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def <|fim_middle|>(self):
return super().__hash__()
<|fim▁end|> | __hash__ |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [<|fim▁hole|>
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff<|fim▁end|> | 'This is cell A1 in Sheet 1', 'This is cell G5'] |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
<|fim_middle|>
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5'] |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
<|fim_middle|>
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', ''] |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
<|fim_middle|>
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "] |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
<|fim_middle|>
<|fim▁end|> | from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def <|fim_middle|>(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | test_read_string_table |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def <|fim_middle|>(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | test_empty_string |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def <|fim_middle|>(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | test_formatted_string_table |
<|file_name|>test_strings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def <|fim_middle|>(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
<|fim▁end|> | test_write_string_table |
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>from django.dispatch import Signal
user_email_bounced = Signal() # args: ['bounce', 'should_deactivate']
email_bounced = Signal() # args: ['bounce', 'should_deactivate']<|fim▁hole|><|fim▁end|> |
email_unsubscribed = Signal() # args: ['email', 'reference'] |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database<|fim▁hole|> Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)<|fim▁end|> | |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
<|fim_middle|>
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
<|fim_middle|>
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | """
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users] |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
<|fim_middle|>
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | """
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id)) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
<|fim_middle|>
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | """
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
<|fim_middle|>
<|fim▁end|> | """
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
<|fim_middle|>
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | del u['password'] |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
<|fim_middle|>
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | u = User.objects.get(pk = id) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
<|fim_middle|>
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | u = request.user |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
<|fim_middle|>
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | raise PermissionDenied |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
<|fim_middle|>
u.save()
return get_user_dict(u)
<|fim▁end|> | if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f]) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
<|fim_middle|>
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password']) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
<|fim_middle|>
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | raise PermissionDenied('Old password is required') |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
<|fim_middle|>
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | raise PermissionDenied('Password is incorrect') |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
<|fim_middle|>
u.save()
return get_user_dict(u)
<|fim▁end|> | setattr(u, f, values[f]) |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def <|fim_middle|>(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | get_user_dict |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def <|fim_middle|>(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | filter |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def <|fim_middle|>(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | get |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def <|fim_middle|>(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | get_me |
<|file_name|>user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <[email protected]>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def <|fim_middle|>(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
<|fim▁end|> | update |
<|file_name|>server_web.py<|end_file_name|><|fim▁begin|># A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length: %i" % len(str.encode(web_contents))
clientsocket.send(str.encode(web_headers + "\n\n" + web_contents))
clientsocket.close()
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# Let's use better the local interface name
hostname = "10.10.104.17"
try:<|fim▁hole|>
while True:
# accept connections from outside
print ("Waiting for connections at %s %i" % (hostname, PORT))
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a non threaded server
process_client(clientsocket)
except socket.error:
print("Problemas using port %i. Do you have permission?" % PORT)<|fim▁end|> | serversocket.bind((ip, PORT))
# become a server socket
# MAX_OPEN_REQUESTS connect requests before refusing outside connections
serversocket.listen(MAX_OPEN_REQUESTS) |
<|file_name|>server_web.py<|end_file_name|><|fim▁begin|># A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
<|fim_middle|>
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# Let's use better the local interface name
hostname = "10.10.104.17"
try:
serversocket.bind((ip, PORT))
# become a server socket
# MAX_OPEN_REQUESTS connect requests before refusing outside connections
serversocket.listen(MAX_OPEN_REQUESTS)
while True:
# accept connections from outside
print ("Waiting for connections at %s %i" % (hostname, PORT))
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a non threaded server
process_client(clientsocket)
except socket.error:
print("Problemas using port %i. Do you have permission?" % PORT)
<|fim▁end|> | print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length: %i" % len(str.encode(web_contents))
clientsocket.send(str.encode(web_headers + "\n\n" + web_contents))
clientsocket.close() |
<|file_name|>server_web.py<|end_file_name|><|fim▁begin|># A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def <|fim_middle|>(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length: %i" % len(str.encode(web_contents))
clientsocket.send(str.encode(web_headers + "\n\n" + web_contents))
clientsocket.close()
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# Let's use better the local interface name
hostname = "10.10.104.17"
try:
serversocket.bind((ip, PORT))
# become a server socket
# MAX_OPEN_REQUESTS connect requests before refusing outside connections
serversocket.listen(MAX_OPEN_REQUESTS)
while True:
# accept connections from outside
print ("Waiting for connections at %s %i" % (hostname, PORT))
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a non threaded server
process_client(clientsocket)
except socket.error:
print("Problemas using port %i. Do you have permission?" % PORT)
<|fim▁end|> | process_client |
<|file_name|>win32_aclui.py<|end_file_name|><|fim▁begin|># pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64
from .. import SIM_PROCEDURES as P
from . import SimLibrary
_l = logging.getLogger(name=__name__)
lib = SimLibrary()
lib.set_default_cc('X86', SimCCStdcall)
lib.set_default_cc('AMD64', SimCCMicrosoftAMD64)
lib.set_library_names("aclui.dll")
prototypes = \
{
#
'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="ISecurityInformation")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]),
#
'EditSecurity': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]),
#
'EditSecurityAdvanced': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation"), SimTypeInt(signed=False, label="SI_PAGE_TYPE")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi", "uSIPage"]),
}<|fim▁hole|><|fim▁end|> |
lib.set_prototypes(prototypes) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>__package__ = 'archivebox.core'<|fim▁end|> | |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur<|fim▁hole|> return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')<|fim▁end|> |
if src == CURRENCY_EUR and dst == CURRENCY_USD: |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
<|fim_middle|>
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
<|fim_middle|>
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
<|fim_middle|>
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | price = float(price)
return format_number(round_number(price) if round_price else price) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
<|fim_middle|>
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | return '%s %s' % (format_price(price), dict(CURRENCIES)[currency]) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
<|fim_middle|>
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
<|fim_middle|>
<|fim▁end|> | if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies') |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
<|fim_middle|>
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | return lambda p: p |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
<|fim_middle|>
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | return lambda p: p / getattr(rates, name(dst)) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
<|fim_middle|>
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | return lambda p: p * getattr(rates, name(src)) |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
<|fim_middle|>
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | return lambda p: p * rates.usd_eur |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
<|fim_middle|>
raise ValueError('Unknown currencies')
<|fim▁end|> | return lambda p: p / rates.usd_eur |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def <|fim_middle|>(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | round_number |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def <|fim_middle|>(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | format_number |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def <|fim_middle|>(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | format_price |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def <|fim_middle|>(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | format_printable_price |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def <|fim_middle|>(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | get_currency_from_session |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def <|fim_middle|>(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
<|fim▁end|> | get_price_factory |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception<|fim▁hole|>@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])<|fim▁end|> | from nova.objects import base
from nova.objects import fields
|
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
<|fim_middle|>
<|fim▁end|> | """Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context']) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
<|fim_middle|>
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
<|fim_middle|>
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
<|fim_middle|>
<|fim▁end|> | db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context']) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
<|fim_middle|>
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
<|fim_middle|>
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid) |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
<|fim_middle|>
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | return None |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def <|fim_middle|>(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | obj_make_compatible |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def <|fim_middle|>(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | obj_from_db_obj |
<|file_name|>migration_context.py<|end_file_name|><|fim▁begin|># Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representing additional resources related to a migration.
Some resources cannot be calculated from knowing the flavor alone for the
purpose of resources tracking, but need to be persisted at the time the
claim was made, for subsequent resource tracking runs to be consistent.
MigrationContext objects are created when the claim is done and are there
to facilitate resource tracking and final provisioning of the instance on
the destination host.
"""
# Version 1.0: Initial version
# Version 1.1: Add old/new pci_devices and pci_requests
VERSION = '1.1'
fields = {
'instance_uuid': fields.UUIDField(),
'migration_id': fields.IntegerField(),
'new_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'old_numa_topology': fields.ObjectField('InstanceNUMATopology',
nullable=True),
'new_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'old_pci_devices': fields.ObjectField('PciDeviceList',
nullable=True),
'new_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
'old_pci_requests': fields.ObjectField('InstancePCIRequests',
nullable=True),
}
@classmethod
def obj_make_compatible(cls, primitive, target_version):
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
primitive.pop('old_pci_devices', None)
primitive.pop('new_pci_devices', None)
primitive.pop('old_pci_requests', None)
primitive.pop('new_pci_requests', None)
@classmethod
def obj_from_db_obj(cls, db_obj):
primitive = jsonutils.loads(db_obj)
return cls.obj_from_primitive(primitive)
@base.remotable_classmethod
def <|fim_middle|>(cls, context, instance_uuid):
db_extra = db.instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['migration_context'])
if not db_extra:
raise exception.MigrationContextNotFound(
instance_uuid=instance_uuid)
if db_extra['migration_context'] is None:
return None
return cls.obj_from_db_obj(db_extra['migration_context'])
<|fim▁end|> | get_by_instance_uuid |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<|fim▁hole|># DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)<|fim▁end|> | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
<|fim_middle|>
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp() |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
<|fim_middle|>
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
<|fim_middle|>
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.") |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
<|fim_middle|>
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | raise ArgumentTypeError("Argument is not a valid hex value.") |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
<|fim_middle|>
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | message[param] = value |
<|file_name|>slack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
<|fim_middle|>
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
<|fim▁end|> | attachment[param] = value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.