identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
BitString.asBinary
(self)
Get |ASN.1| value as a text string of bits.
Get |ASN.1| value as a text string of bits.
def asBinary(self): """Get |ASN.1| value as a text string of bits. """ binString = binary.bin(self._value)[2:] return '0' * (len(self._value) - len(binString)) + binString
[ "def", "asBinary", "(", "self", ")", ":", "binString", "=", "binary", ".", "bin", "(", "self", ".", "_value", ")", "[", "2", ":", "]", "return", "'0'", "*", "(", "len", "(", "self", ".", "_value", ")", "-", "len", "(", "binString", ")", ")", "+", "binString" ]
[ 585, 4 ]
[ 589, 68 ]
python
en
['en', 'en', 'en']
True
BitString.fromHexString
(cls, value, internalFormat=False, prepend=None)
Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF'
Create a |ASN.1| object initialized from the hex string.
def fromHexString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ try: value = SizedInteger(value, 16).setBitLength(len(value) * 4) except ValueError: raise error.PyAsn1Error('%s.fromHexString() error: %s' % (cls.__name__, sys.exc_info()[1])) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value
[ "def", "fromHexString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ")", ":", "try", ":", "value", "=", "SizedInteger", "(", "value", ",", "16", ")", ".", "setBitLength", "(", "len", "(", "value", ")", "*", "4", ")", "except", "ValueError", ":", "raise", "error", ".", "PyAsn1Error", "(", "'%s.fromHexString() error: %s'", "%", "(", "cls", ".", "__name__", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", ")", "if", "prepend", "is", "not", "None", ":", "value", "=", "SizedInteger", "(", "(", "SizedInteger", "(", "prepend", ")", "<<", "len", "(", "value", ")", ")", "|", "value", ")", ".", "setBitLength", "(", "len", "(", "prepend", ")", "+", "len", "(", "value", ")", ")", "if", "not", "internalFormat", ":", "value", "=", "cls", "(", "value", ")", "return", "value" ]
[ 592, 4 ]
[ 614, 20 ]
python
en
['en', 'en', 'en']
True
BitString.fromBinaryString
(cls, value, internalFormat=False, prepend=None)
Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111'
Create a |ASN.1| object initialized from a string of '0' and '1'.
def fromBinaryString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ try: value = SizedInteger(value or '0', 2).setBitLength(len(value)) except ValueError: raise error.PyAsn1Error('%s.fromBinaryString() error: %s' % (cls.__name__, sys.exc_info()[1])) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value
[ "def", "fromBinaryString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ")", ":", "try", ":", "value", "=", "SizedInteger", "(", "value", "or", "'0'", ",", "2", ")", ".", "setBitLength", "(", "len", "(", "value", ")", ")", "except", "ValueError", ":", "raise", "error", ".", "PyAsn1Error", "(", "'%s.fromBinaryString() error: %s'", "%", "(", "cls", ".", "__name__", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", ")", "if", "prepend", "is", "not", "None", ":", "value", "=", "SizedInteger", "(", "(", "SizedInteger", "(", "prepend", ")", "<<", "len", "(", "value", ")", ")", "|", "value", ")", ".", "setBitLength", "(", "len", "(", "prepend", ")", "+", "len", "(", "value", ")", ")", "if", "not", "internalFormat", ":", "value", "=", "cls", "(", "value", ")", "return", "value" ]
[ 617, 4 ]
[ 639, 20 ]
python
en
['en', 'en', 'en']
True
BitString.fromOctetString
(cls, value, internalFormat=False, prepend=None, padding=0)
Create a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`str` (Py2) or :class:`bytes` (Py3) Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
Create a |ASN.1| object initialized from a string.
def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0): """Create a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`str` (Py2) or :class:`bytes` (Py3) Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3) """ value = SizedInteger(integer.from_bytes(value) >> padding).setBitLength(len(value) * 8 - padding) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value
[ "def", "fromOctetString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ",", "padding", "=", "0", ")", ":", "value", "=", "SizedInteger", "(", "integer", ".", "from_bytes", "(", "value", ")", ">>", "padding", ")", ".", "setBitLength", "(", "len", "(", "value", ")", "*", "8", "-", "padding", ")", "if", "prepend", "is", "not", "None", ":", "value", "=", "SizedInteger", "(", "(", "SizedInteger", "(", "prepend", ")", "<<", "len", "(", "value", ")", ")", "|", "value", ")", ".", "setBitLength", "(", "len", "(", "prepend", ")", "+", "len", "(", "value", ")", ")", "if", "not", "internalFormat", ":", "value", "=", "cls", "(", "value", ")", "return", "value" ]
[ 642, 4 ]
[ 660, 20 ]
python
en
['en', 'en', 'en']
True
OctetString.fromBinaryString
(value)
Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111'
Create a |ASN.1| object initialized from a string of '0' and '1'.
def fromBinaryString(value): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ bitNo = 8 byte = 0 r = [] for v in value: if bitNo: bitNo -= 1 else: bitNo = 7 r.append(byte) byte = 0 if v in ('0', '1'): v = int(v) else: raise error.PyAsn1Error( 'Non-binary OCTET STRING initializer %s' % (v,) ) byte |= v << bitNo r.append(byte) return octets.ints2octs(r)
[ "def", "fromBinaryString", "(", "value", ")", ":", "bitNo", "=", "8", "byte", "=", "0", "r", "=", "[", "]", "for", "v", "in", "value", ":", "if", "bitNo", ":", "bitNo", "-=", "1", "else", ":", "bitNo", "=", "7", "r", ".", "append", "(", "byte", ")", "byte", "=", "0", "if", "v", "in", "(", "'0'", ",", "'1'", ")", ":", "v", "=", "int", "(", "v", ")", "else", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Non-binary OCTET STRING initializer %s'", "%", "(", "v", ",", ")", ")", "byte", "|=", "v", "<<", "bitNo", "r", ".", "append", "(", "byte", ")", "return", "octets", ".", "ints2octs", "(", "r", ")" ]
[ 973, 4 ]
[ 1001, 34 ]
python
en
['en', 'en', 'en']
True
OctetString.fromHexString
(value)
Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF'
Create a |ASN.1| object initialized from the hex string.
def fromHexString(value): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ r = [] p = [] for v in value: if p: r.append(int(p + v, 16)) p = None else: p = v if p: r.append(int(p + '0', 16)) return octets.ints2octs(r)
[ "def", "fromHexString", "(", "value", ")", ":", "r", "=", "[", "]", "p", "=", "[", "]", "for", "v", "in", "value", ":", "if", "p", ":", "r", ".", "append", "(", "int", "(", "p", "+", "v", ",", "16", ")", ")", "p", "=", "None", "else", ":", "p", "=", "v", "if", "p", ":", "r", ".", "append", "(", "int", "(", "p", "+", "'0'", ",", "16", ")", ")", "return", "octets", ".", "ints2octs", "(", "r", ")" ]
[ 1004, 4 ]
[ 1023, 34 ]
python
en
['en', 'en', 'en']
True
ObjectIdentifier.isPrefixOf
(self, other)
Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise.
Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
def isPrefixOf(self, other): """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. """ l = len(self) if l <= len(other): if self._value[:l] == other[:l]: return True return False
[ "def", "isPrefixOf", "(", "self", ",", "other", ")", ":", "l", "=", "len", "(", "self", ")", "if", "l", "<=", "len", "(", "other", ")", ":", "if", "self", ".", "_value", "[", ":", "l", "]", "==", "other", "[", ":", "l", "]", ":", "return", "True", "return", "False" ]
[ 1209, 4 ]
[ 1227, 20 ]
python
en
['en', 'en', 'en']
True
Real.isPlusInf
(self)
Indicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise.
Indicate PLUS-INFINITY object value
def isPlusInf(self): """Indicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise. """ return self._value == self._plusInf
[ "def", "isPlusInf", "(", "self", ")", ":", "return", "self", ".", "_value", "==", "self", ".", "_plusInf" ]
[ 1387, 4 ]
[ 1397, 43 ]
python
en
['nl', 'en', 'en']
True
Real.isMinusInf
(self)
Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise.
Indicate MINUS-INFINITY object value
def isMinusInf(self): """Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise. """ return self._value == self._minusInf
[ "def", "isMinusInf", "(", "self", ")", ":", "return", "self", ".", "_value", "==", "self", ".", "_minusInf" ]
[ 1400, 4 ]
[ 1409, 44 ]
python
en
['nl', 'en', 'it']
False
SequenceOfAndSetOfBase.getComponentByPosition
(self, idx, default=noValue, instantiate=True)
Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (if *componentType* is set). In the latter case a new component type gets instantiated and appended to the |ASN.1| sequence. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value Examples -------- .. code-block:: python # can also be SetOf class MySequenceOf(SequenceOf): componentType = OctetString() s = MySequenceOf() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False)
Return |ASN.1| type component value by position.
def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (if *componentType* is set). In the latter case a new component type gets instantiated and appended to the |ASN.1| sequence. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value Examples -------- .. code-block:: python # can also be SetOf class MySequenceOf(SequenceOf): componentType = OctetString() s = MySequenceOf() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) """ if isinstance(idx, slice): indices = tuple(range(len(self))) return [self.getComponentByPosition(subidx, default, instantiate) for subidx in indices[idx]] if idx < 0: idx = len(self) + idx if idx < 0: raise error.PyAsn1Error( 'SequenceOf/SetOf index is out of range') try: componentValue = self._componentValues[idx] except (KeyError, error.PyAsn1Error): if not instantiate: return default self.setComponentByPosition(idx) componentValue = self._componentValues[idx] if default is noValue or componentValue.isValue: return componentValue else: return default
[ "def", "getComponentByPosition", "(", "self", ",", "idx", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "if", "isinstance", "(", "idx", ",", "slice", ")", ":", "indices", "=", "tuple", "(", "range", "(", "len", "(", "self", ")", ")", ")", "return", "[", "self", ".", "getComponentByPosition", "(", "subidx", ",", "default", ",", "instantiate", ")", "for", "subidx", "in", "indices", "[", "idx", "]", "]", "if", "idx", "<", "0", ":", "idx", "=", "len", "(", "self", ")", "+", "idx", "if", "idx", "<", "0", ":", "raise", "error", ".", "PyAsn1Error", "(", "'SequenceOf/SetOf index is out of range'", ")", "try", ":", "componentValue", "=", "self", ".", "_componentValues", "[", "idx", "]", "except", "(", "KeyError", ",", "error", ".", "PyAsn1Error", ")", ":", "if", "not", "instantiate", ":", "return", "default", "self", ".", "setComponentByPosition", "(", "idx", ")", "componentValue", "=", "self", ".", "_componentValues", "[", "idx", "]", "if", "default", "is", "noValue", "or", "componentValue", ".", "isValue", ":", "return", "componentValue", "else", ":", "return", "default" ]
[ 1747, 4 ]
[ 1838, 26 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.setComponentByPosition
(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer IndexError When idx > len(self)
Assign |ASN.1| type component by position.
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer IndexError When idx > len(self) """ if isinstance(idx, slice): indices = tuple(range(len(self))) startIdx = indices and indices[idx][0] or 0 for subIdx, subValue in enumerate(value): self.setComponentByPosition( startIdx + subIdx, subValue, verifyConstraints, matchTags, matchConstraints) return self if idx < 0: idx = len(self) + idx if idx < 0: raise error.PyAsn1Error( 'SequenceOf/SetOf index is out of range') componentType = self.componentType if self._componentValues is noValue: componentValues = {} else: componentValues = self._componentValues currentValue = componentValues.get(idx, noValue) if value is noValue: if componentType is not None: value = componentType.clone() elif currentValue is noValue: raise error.PyAsn1Error('Component type not defined') elif not isinstance(value, base.Asn1Item): if (componentType is not None and isinstance(componentType, base.SimpleAsn1Type)): value = componentType.clone(value=value) elif (currentValue is not noValue and isinstance(currentValue, base.SimpleAsn1Type)): value = currentValue.clone(value=value) else: raise error.PyAsn1Error( 'Non-ASN.1 value %r and undefined component' ' type at %r' % (value, self)) elif componentType is not None and (matchTags or matchConstraints): subtypeChecker = ( self.strictConstraints and componentType.isSameTypeWith or componentType.isSuperTypeOf) if not subtypeChecker(value, verifyConstraints and matchTags, verifyConstraints and matchConstraints): # TODO: we should wrap componentType with UnnamedType to carry # additional properties associated with componentType if componentType.typeId != Any.typeId: raise error.PyAsn1Error( 'Component value is tag-incompatible: %r vs ' '%r' % (value, componentType)) componentValues[idx] = value self._componentValues = componentValues return self
[ "def", "setComponentByPosition", "(", "self", ",", "idx", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "if", "isinstance", "(", "idx", ",", "slice", ")", ":", "indices", "=", "tuple", "(", "range", "(", "len", "(", "self", ")", ")", ")", "startIdx", "=", "indices", "and", "indices", "[", "idx", "]", "[", "0", "]", "or", "0", "for", "subIdx", ",", "subValue", "in", "enumerate", "(", "value", ")", ":", "self", ".", "setComponentByPosition", "(", "startIdx", "+", "subIdx", ",", "subValue", ",", "verifyConstraints", ",", "matchTags", ",", "matchConstraints", ")", "return", "self", "if", "idx", "<", "0", ":", "idx", "=", "len", "(", "self", ")", "+", "idx", "if", "idx", "<", "0", ":", "raise", "error", ".", "PyAsn1Error", "(", "'SequenceOf/SetOf index is out of range'", ")", "componentType", "=", "self", ".", "componentType", "if", "self", ".", "_componentValues", "is", "noValue", ":", "componentValues", "=", "{", "}", "else", ":", "componentValues", "=", "self", ".", "_componentValues", "currentValue", "=", "componentValues", ".", "get", "(", "idx", ",", "noValue", ")", "if", "value", "is", "noValue", ":", "if", "componentType", "is", "not", "None", ":", "value", "=", "componentType", ".", "clone", "(", ")", "elif", "currentValue", "is", "noValue", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component type not defined'", ")", "elif", "not", "isinstance", "(", "value", ",", "base", ".", "Asn1Item", ")", ":", "if", "(", "componentType", "is", "not", "None", "and", "isinstance", "(", "componentType", ",", "base", ".", "SimpleAsn1Type", ")", ")", ":", "value", "=", "componentType", ".", "clone", "(", "value", "=", "value", ")", "elif", "(", "currentValue", "is", "not", "noValue", "and", "isinstance", "(", "currentValue", ",", "base", ".", "SimpleAsn1Type", ")", ")", ":", "value", "=", "currentValue", ".", "clone", "(", "value", "=", "value", ")", "else", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Non-ASN.1 value %r and undefined component'", "' type at %r'", "%", "(", "value", ",", "self", ")", ")", "elif", "componentType", "is", "not", "None", "and", "(", "matchTags", "or", "matchConstraints", ")", ":", "subtypeChecker", "=", "(", "self", ".", "strictConstraints", "and", "componentType", ".", "isSameTypeWith", "or", "componentType", ".", "isSuperTypeOf", ")", "if", "not", "subtypeChecker", "(", "value", ",", "verifyConstraints", "and", "matchTags", ",", "verifyConstraints", "and", "matchConstraints", ")", ":", "# TODO: we should wrap componentType with UnnamedType to carry", "# additional properties associated with componentType", "if", "componentType", ".", "typeId", "!=", "Any", ".", "typeId", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component value is tag-incompatible: %r vs '", "'%r'", "%", "(", "value", ",", "componentType", ")", ")", "componentValues", "[", "idx", "]", "=", "value", "self", ".", "_componentValues", "=", "componentValues", "return", "self" ]
[ 1840, 4 ]
[ 1949, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.clear
(self)
Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in.
Remove all components and become an empty |ASN.1| value object.
def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in. """ self._componentValues = {} return self
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "{", "}", "return", "self" ]
[ 1961, 4 ]
[ 1968, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.reset
(self)
Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects.
Remove all components and become a |ASN.1| schema object.
def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue return self
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "noValue", "return", "self" ]
[ 1970, 4 ]
[ 1977, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.isValue
(self)
Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc).
Indicate that |ASN.1| object represents ASN.1 value.
def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). """ if self._componentValues is noValue: return False if len(self._componentValues) != len(self): return False for componentValue in self._componentValues.values(): if componentValue is noValue or not componentValue.isValue: return False return True
[ "def", "isValue", "(", "self", ")", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "False", "if", "len", "(", "self", ".", "_componentValues", ")", "!=", "len", "(", "self", ")", ":", "return", "False", "for", "componentValue", "in", "self", ".", "_componentValues", ".", "values", "(", ")", ":", "if", "componentValue", "is", "noValue", "or", "not", "componentValue", ".", "isValue", ":", "return", "False", "return", "True" ]
[ 2006, 4 ]
[ 2042, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.isInconsistent
(self)
Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found
Run necessary checks to ensure |ASN.1| object consistency.
def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """ if self.componentType is noValue or not self.subtypeSpec: return False if self._componentValues is noValue: return True mapping = {} for idx, value in self._componentValues.items(): # Absent fields are not in the mapping if value is noValue: continue mapping[idx] = value try: # Represent SequenceOf/SetOf as a bare dict to constraints chain self.subtypeSpec(mapping) except error.PyAsn1Error: exc = sys.exc_info()[1] return exc return False
[ "def", "isInconsistent", "(", "self", ")", ":", "if", "self", ".", "componentType", "is", "noValue", "or", "not", "self", ".", "subtypeSpec", ":", "return", "False", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "True", "mapping", "=", "{", "}", "for", "idx", ",", "value", "in", "self", ".", "_componentValues", ".", "items", "(", ")", ":", "# Absent fields are not in the mapping", "if", "value", "is", "noValue", ":", "continue", "mapping", "[", "idx", "]", "=", "value", "try", ":", "# Represent SequenceOf/SetOf as a bare dict to constraints chain", "self", ".", "subtypeSpec", "(", "mapping", ")", "except", "error", ".", "PyAsn1Error", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "return", "exc", "return", "False" ]
[ 2045, 4 ]
[ 2078, 20 ]
python
en
['en', 'mg', 'en']
True
SequenceAndSetBase.clear
(self)
Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in.
Remove all components and become an empty |ASN.1| value object.
def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in. """ self._componentValues = [] self._dynamicNames = self.DynamicNames() return self
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "[", "]", "self", ".", "_dynamicNames", "=", "self", ".", "DynamicNames", "(", ")", "return", "self" ]
[ 2293, 4 ]
[ 2301, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.reset
(self)
Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects.
Remove all components and become a |ASN.1| schema object.
def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue self._dynamicNames = self.DynamicNames() return self
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "noValue", "self", ".", "_dynamicNames", "=", "self", ".", "DynamicNames", "(", ")", "return", "self" ]
[ 2303, 4 ]
[ 2311, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.getComponentByName
(self, name, default=noValue, instantiate=True)
Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value
Returns |ASN.1| type component by name.
def getComponentByName(self, name, default=noValue, instantiate=True): """Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) else: try: idx = self._dynamicNames.getPositionByName(name) except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) return self.getComponentByPosition(idx, default=default, instantiate=instantiate)
[ "def", "getComponentByName", "(", "self", ",", "name", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "if", "self", ".", "_componentTypeLen", ":", "idx", "=", "self", ".", "componentType", ".", "getPositionByName", "(", "name", ")", "else", ":", "try", ":", "idx", "=", "self", ".", "_dynamicNames", ".", "getPositionByName", "(", "name", ")", "except", "KeyError", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Name %s not found'", "%", "(", "name", ",", ")", ")", "return", "self", ".", "getComponentByPosition", "(", "idx", ",", "default", "=", "default", ",", "instantiate", "=", "instantiate", ")" ]
[ 2330, 4 ]
[ 2367, 89 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.setComponentByName
(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self
Assign |ASN.1| type component by name.
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) else: try: idx = self._dynamicNames.getPositionByName(name) except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints )
[ "def", "setComponentByName", "(", "self", ",", "name", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "if", "self", ".", "_componentTypeLen", ":", "idx", "=", "self", ".", "componentType", ".", "getPositionByName", "(", "name", ")", "else", ":", "try", ":", "idx", "=", "self", ".", "_dynamicNames", ".", "getPositionByName", "(", "name", ")", "except", "KeyError", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Name %s not found'", "%", "(", "name", ",", ")", ")", "return", "self", ".", "setComponentByPosition", "(", "idx", ",", "value", ",", "verifyConstraints", ",", "matchTags", ",", "matchConstraints", ")" ]
[ 2369, 4 ]
[ 2413, 9 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.getComponentByPosition
(self, idx, default=noValue, instantiate=True)
Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 schema object gets instantiated. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object Examples -------- .. code-block:: python # can also be Set class MySequence(Sequence): componentType = NamedTypes( NamedType('id', OctetString()) ) s = MySequence() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False)
Returns |ASN.1| type component by index.
def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 schema object gets instantiated. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object Examples -------- .. code-block:: python # can also be Set class MySequence(Sequence): componentType = NamedTypes( NamedType('id', OctetString()) ) s = MySequence() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) """ try: if self._componentValues is noValue: componentValue = noValue else: componentValue = self._componentValues[idx] except IndexError: componentValue = noValue if not instantiate: if componentValue is noValue or not componentValue.isValue: return default else: return componentValue if componentValue is noValue: self.setComponentByPosition(idx) componentValue = self._componentValues[idx] if default is noValue or componentValue.isValue: return componentValue else: return default
[ "def", "getComponentByPosition", "(", "self", ",", "idx", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "try", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "componentValue", "=", "noValue", "else", ":", "componentValue", "=", "self", ".", "_componentValues", "[", "idx", "]", "except", "IndexError", ":", "componentValue", "=", "noValue", "if", "not", "instantiate", ":", "if", "componentValue", "is", "noValue", "or", "not", "componentValue", ".", "isValue", ":", "return", "default", "else", ":", "return", "componentValue", "if", "componentValue", "is", "noValue", ":", "self", ".", "setComponentByPosition", "(", "idx", ")", "componentValue", "=", "self", ".", "_componentValues", "[", "idx", "]", "if", "default", "is", "noValue", "or", "componentValue", ".", "isValue", ":", "return", "componentValue", "else", ":", "return", "default" ]
[ 2415, 4 ]
[ 2507, 26 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.setComponentByPosition
(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 component otherwise. In the latter case a new component of given ASN.1 type gets instantiated and appended to |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self
Assign |ASN.1| type component by position.
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 component otherwise. In the latter case a new component of given ASN.1 type gets instantiated and appended to |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self """ componentType = self.componentType componentTypeLen = self._componentTypeLen if self._componentValues is noValue: componentValues = [] else: componentValues = self._componentValues try: currentValue = componentValues[idx] except IndexError: currentValue = noValue if componentTypeLen: if componentTypeLen < idx: raise error.PyAsn1Error('component index out of range') componentValues = [noValue] * componentTypeLen if value is noValue: if componentTypeLen: value = componentType.getTypeByPosition(idx) if isinstance(value, base.ConstructedAsn1Type): value = value.clone(cloneValueFlag=componentType[idx].isDefaulted) elif currentValue is noValue: raise error.PyAsn1Error('Component type not defined') elif not isinstance(value, base.Asn1Item): if componentTypeLen: subComponentType = componentType.getTypeByPosition(idx) if isinstance(subComponentType, base.SimpleAsn1Type): value = subComponentType.clone(value=value) else: raise error.PyAsn1Error('%s can cast only scalar values' % componentType.__class__.__name__) elif currentValue is not noValue and isinstance(currentValue, base.SimpleAsn1Type): value = currentValue.clone(value=value) else: raise error.PyAsn1Error('%s undefined component type' % componentType.__class__.__name__) elif ((verifyConstraints or matchTags or matchConstraints) and componentTypeLen): subComponentType = componentType.getTypeByPosition(idx) if subComponentType is not noValue: subtypeChecker = (self.strictConstraints and subComponentType.isSameTypeWith or subComponentType.isSuperTypeOf) if not subtypeChecker(value, verifyConstraints and matchTags, verifyConstraints and matchConstraints): if not componentType[idx].openType: raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, componentType)) if componentTypeLen or idx in self._dynamicNames: componentValues[idx] = value elif len(componentValues) == idx: componentValues.append(value) self._dynamicNames.addField(idx) else: raise error.PyAsn1Error('Component index out of range') self._componentValues = componentValues return self
[ "def", "setComponentByPosition", "(", "self", ",", "idx", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "componentType", "=", "self", ".", "componentType", "componentTypeLen", "=", "self", ".", "_componentTypeLen", "if", "self", ".", "_componentValues", "is", "noValue", ":", "componentValues", "=", "[", "]", "else", ":", "componentValues", "=", "self", ".", "_componentValues", "try", ":", "currentValue", "=", "componentValues", "[", "idx", "]", "except", "IndexError", ":", "currentValue", "=", "noValue", "if", "componentTypeLen", ":", "if", "componentTypeLen", "<", "idx", ":", "raise", "error", ".", "PyAsn1Error", "(", "'component index out of range'", ")", "componentValues", "=", "[", "noValue", "]", "*", "componentTypeLen", "if", "value", "is", "noValue", ":", "if", "componentTypeLen", ":", "value", "=", "componentType", ".", "getTypeByPosition", "(", "idx", ")", "if", "isinstance", "(", "value", ",", "base", ".", "ConstructedAsn1Type", ")", ":", "value", "=", "value", ".", "clone", "(", "cloneValueFlag", "=", "componentType", "[", "idx", "]", ".", "isDefaulted", ")", "elif", "currentValue", "is", "noValue", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component type not defined'", ")", "elif", "not", "isinstance", "(", "value", ",", "base", ".", "Asn1Item", ")", ":", "if", "componentTypeLen", ":", "subComponentType", "=", "componentType", ".", "getTypeByPosition", "(", "idx", ")", "if", "isinstance", "(", "subComponentType", ",", "base", ".", "SimpleAsn1Type", ")", ":", "value", "=", "subComponentType", ".", "clone", "(", "value", "=", "value", ")", "else", ":", "raise", "error", ".", "PyAsn1Error", "(", "'%s can cast only scalar values'", "%", "componentType", ".", "__class__", ".", "__name__", ")", "elif", "currentValue", "is", "not", "noValue", "and", "isinstance", "(", "currentValue", ",", "base", ".", "SimpleAsn1Type", ")", ":", "value", "=", "currentValue", ".", "clone", "(", "value", "=", "value", ")", "else", ":", "raise", "error", ".", "PyAsn1Error", "(", "'%s undefined component type'", "%", "componentType", ".", "__class__", ".", "__name__", ")", "elif", "(", "(", "verifyConstraints", "or", "matchTags", "or", "matchConstraints", ")", "and", "componentTypeLen", ")", ":", "subComponentType", "=", "componentType", ".", "getTypeByPosition", "(", "idx", ")", "if", "subComponentType", "is", "not", "noValue", ":", "subtypeChecker", "=", "(", "self", ".", "strictConstraints", "and", "subComponentType", ".", "isSameTypeWith", "or", "subComponentType", ".", "isSuperTypeOf", ")", "if", "not", "subtypeChecker", "(", "value", ",", "verifyConstraints", "and", "matchTags", ",", "verifyConstraints", "and", "matchConstraints", ")", ":", "if", "not", "componentType", "[", "idx", "]", ".", "openType", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component value is tag-incompatible: %r vs %r'", "%", "(", "value", ",", "componentType", ")", ")", "if", "componentTypeLen", "or", "idx", "in", "self", ".", "_dynamicNames", ":", "componentValues", "[", "idx", "]", "=", "value", "elif", "len", "(", "componentValues", ")", "==", "idx", ":", "componentValues", ".", "append", "(", "value", ")", "self", ".", "_dynamicNames", ".", "addField", "(", "idx", ")", "else", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Component index out of range'", ")", "self", ".", "_componentValues", "=", "componentValues", "return", "self" ]
[ 2509, 4 ]
[ 2614, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.isValue
(self)
Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). It is sufficient for |ASN.1| objects to have all non-optional and non-defaulted components being value objects to be considered as a value objects as a whole. In other words, even having one or more optional components not turned into value objects, |ASN.1| object is still considered as a value object. Defaulted components are normally value objects by default.
Indicate that |ASN.1| object represents ASN.1 value.
def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). It is sufficient for |ASN.1| objects to have all non-optional and non-defaulted components being value objects to be considered as a value objects as a whole. In other words, even having one or more optional components not turned into value objects, |ASN.1| object is still considered as a value object. Defaulted components are normally value objects by default. """ if self._componentValues is noValue: return False componentType = self.componentType if componentType: for idx, subComponentType in enumerate(componentType.namedTypes): if subComponentType.isDefaulted or subComponentType.isOptional: continue if not self._componentValues: return False componentValue = self._componentValues[idx] if componentValue is noValue or not componentValue.isValue: return False else: for componentValue in self._componentValues: if componentValue is noValue or not componentValue.isValue: return False return True
[ "def", "isValue", "(", "self", ")", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "False", "componentType", "=", "self", ".", "componentType", "if", "componentType", ":", "for", "idx", ",", "subComponentType", "in", "enumerate", "(", "componentType", ".", "namedTypes", ")", ":", "if", "subComponentType", ".", "isDefaulted", "or", "subComponentType", ".", "isOptional", ":", "continue", "if", "not", "self", ".", "_componentValues", ":", "return", "False", "componentValue", "=", "self", ".", "_componentValues", "[", "idx", "]", "if", "componentValue", "is", "noValue", "or", "not", "componentValue", ".", "isValue", ":", "return", "False", "else", ":", "for", "componentValue", "in", "self", ".", "_componentValues", ":", "if", "componentValue", "is", "noValue", "or", "not", "componentValue", ".", "isValue", ":", "return", "False", "return", "True" ]
[ 2617, 4 ]
[ 2672, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.isInconsistent
(self)
Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found
Run necessary checks to ensure |ASN.1| object consistency.
def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """ if self.componentType is noValue or not self.subtypeSpec: return False if self._componentValues is noValue: return True mapping = {} for idx, value in enumerate(self._componentValues): # Absent fields are not in the mapping if value is noValue: continue name = self.componentType.getNameByPosition(idx) mapping[name] = value try: # Represent Sequence/Set as a bare dict to constraints chain self.subtypeSpec(mapping) except error.PyAsn1Error: exc = sys.exc_info()[1] return exc return False
[ "def", "isInconsistent", "(", "self", ")", ":", "if", "self", ".", "componentType", "is", "noValue", "or", "not", "self", ".", "subtypeSpec", ":", "return", "False", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "True", "mapping", "=", "{", "}", "for", "idx", ",", "value", "in", "enumerate", "(", "self", ".", "_componentValues", ")", ":", "# Absent fields are not in the mapping", "if", "value", "is", "noValue", ":", "continue", "name", "=", "self", ".", "componentType", ".", "getNameByPosition", "(", "idx", ")", "mapping", "[", "name", "]", "=", "value", "try", ":", "# Represent Sequence/Set as a bare dict to constraints chain", "self", ".", "subtypeSpec", "(", "mapping", ")", "except", "error", ".", "PyAsn1Error", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "return", "exc", "return", "False" ]
[ 2675, 4 ]
[ 2710, 20 ]
python
en
['en', 'mg', 'en']
True
SequenceAndSetBase.prettyPrint
(self, scope=0)
Return an object representation string. Returns ------- : :class:`str` Human-friendly object representation.
Return an object representation string.
def prettyPrint(self, scope=0): """Return an object representation string. Returns ------- : :class:`str` Human-friendly object representation. """ scope += 1 representation = self.__class__.__name__ + ':\n' for idx, componentValue in enumerate(self._componentValues): if componentValue is not noValue and componentValue.isValue: representation += ' ' * scope if self.componentType: representation += self.componentType.getNameByPosition(idx) else: representation += self._dynamicNames.getNameByPosition(idx) representation = '%s=%s\n' % ( representation, componentValue.prettyPrint(scope) ) return representation
[ "def", "prettyPrint", "(", "self", ",", "scope", "=", "0", ")", ":", "scope", "+=", "1", "representation", "=", "self", ".", "__class__", ".", "__name__", "+", "':\\n'", "for", "idx", ",", "componentValue", "in", "enumerate", "(", "self", ".", "_componentValues", ")", ":", "if", "componentValue", "is", "not", "noValue", "and", "componentValue", ".", "isValue", ":", "representation", "+=", "' '", "*", "scope", "if", "self", ".", "componentType", ":", "representation", "+=", "self", ".", "componentType", ".", "getNameByPosition", "(", "idx", ")", "else", ":", "representation", "+=", "self", ".", "_dynamicNames", ".", "getNameByPosition", "(", "idx", ")", "representation", "=", "'%s=%s\\n'", "%", "(", "representation", ",", "componentValue", ".", "prettyPrint", "(", "scope", ")", ")", "return", "representation" ]
[ 2712, 4 ]
[ 2732, 29 ]
python
en
['en', 'en', 'en']
True
Set.getComponentByType
(self, tagSet, default=noValue, instantiate=True, innerFlag=False)
Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`noValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object
Returns |ASN.1| type component by ASN.1 tag.
def getComponentByType(self, tagSet, default=noValue, instantiate=True, innerFlag=False): """Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`noValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object """ componentValue = self.getComponentByPosition( self.componentType.getPositionByType(tagSet), default=default, instantiate=instantiate ) if innerFlag and isinstance(componentValue, Set): # get inner component by inner tagSet return componentValue.getComponent(innerFlag=True) else: # get outer component by inner tagSet return componentValue
[ "def", "getComponentByType", "(", "self", ",", "tagSet", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ",", "innerFlag", "=", "False", ")", ":", "componentValue", "=", "self", ".", "getComponentByPosition", "(", "self", ".", "componentType", ".", "getPositionByType", "(", "tagSet", ")", ",", "default", "=", "default", ",", "instantiate", "=", "instantiate", ")", "if", "innerFlag", "and", "isinstance", "(", "componentValue", ",", "Set", ")", ":", "# get inner component by inner tagSet", "return", "componentValue", ".", "getComponent", "(", "innerFlag", "=", "True", ")", "else", ":", "# get outer component by inner tagSet", "return", "componentValue" ]
[ 2821, 4 ]
[ 2857, 33 ]
python
en
['en', 'en', 'en']
True
Set.setComponentByType
(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False)
Assign |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching innerFlag: :class:`bool` If :obj:`True`, search for matching *tagSet* recursively. Returns ------- self
Assign |ASN.1| type component by ASN.1 tag.
def setComponentByType(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False): """Assign |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching innerFlag: :class:`bool` If :obj:`True`, search for matching *tagSet* recursively. Returns ------- self """ idx = self.componentType.getPositionByType(tagSet) if innerFlag: # set inner component by inner tagSet componentType = self.componentType.getTypeByPosition(idx) if componentType.tagSet: return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints ) else: componentType = self.getComponentByPosition(idx) return componentType.setComponentByType( tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag ) else: # set outer component by inner tagSet return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints )
[ "def", "setComponentByType", "(", "self", ",", "tagSet", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ",", "innerFlag", "=", "False", ")", ":", "idx", "=", "self", ".", "componentType", ".", "getPositionByType", "(", "tagSet", ")", "if", "innerFlag", ":", "# set inner component by inner tagSet", "componentType", "=", "self", ".", "componentType", ".", "getTypeByPosition", "(", "idx", ")", "if", "componentType", ".", "tagSet", ":", "return", "self", ".", "setComponentByPosition", "(", "idx", ",", "value", ",", "verifyConstraints", ",", "matchTags", ",", "matchConstraints", ")", "else", ":", "componentType", "=", "self", ".", "getComponentByPosition", "(", "idx", ")", "return", "componentType", ".", "setComponentByType", "(", "tagSet", ",", "value", ",", "verifyConstraints", ",", "matchTags", ",", "matchConstraints", ",", "innerFlag", "=", "innerFlag", ")", "else", ":", "# set outer component by inner tagSet", "return", "self", ".", "setComponentByPosition", "(", "idx", ",", "value", ",", "verifyConstraints", ",", "matchTags", ",", "matchConstraints", ")" ]
[ 2859, 4 ]
[ 2912, 13 ]
python
en
['en', 'en', 'en']
True
clear_collection
(collection)
Removes every document from the collection, to make it easy to see what has been added by the current test run.
Removes every document from the collection, to make it easy to see what has been added by the current test run.
def clear_collection(collection): """ Removes every document from the collection, to make it easy to see what has been added by the current test run. """ for doc in collection.stream(): doc.reference.delete()
[ "def", "clear_collection", "(", "collection", ")", ":", "for", "doc", "in", "collection", ".", "stream", "(", ")", ":", "doc", ".", "reference", ".", "delete", "(", ")" ]
[ 21, 0 ]
[ 26, 30 ]
python
en
['en', 'en', 'en']
True
Filter.__init__
(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_properties, allowed_protocols=allowed_protocols, allowed_content_types=allowed_content_types, attr_val_is_uri=attr_val_is_uri, svg_attr_val_allows_ref=svg_attr_val_allows_ref, svg_allow_local_href=svg_allow_local_href)
Creates a Filter :arg allowed_elements: set of elements to allow--everything else will be escaped :arg allowed_attributes: set of attributes to allow in elements--everything else will be stripped :arg allowed_css_properties: set of CSS properties to allow--everything else will be stripped :arg allowed_css_keywords: set of CSS keywords to allow--everything else will be stripped :arg allowed_svg_properties: set of SVG properties to allow--everything else will be removed :arg allowed_protocols: set of allowed protocols for URIs :arg allowed_content_types: set of allowed content types for ``data`` URIs. :arg attr_val_is_uri: set of attributes that have URI values--values that have a scheme not listed in ``allowed_protocols`` are removed :arg svg_attr_val_allows_ref: set of SVG attributes that can have references :arg svg_allow_local_href: set of SVG elements that can have local hrefs--these are removed
Creates a Filter
def __init__(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_properties, allowed_protocols=allowed_protocols, allowed_content_types=allowed_content_types, attr_val_is_uri=attr_val_is_uri, svg_attr_val_allows_ref=svg_attr_val_allows_ref, svg_allow_local_href=svg_allow_local_href): """Creates a Filter :arg allowed_elements: set of elements to allow--everything else will be escaped :arg allowed_attributes: set of attributes to allow in elements--everything else will be stripped :arg allowed_css_properties: set of CSS properties to allow--everything else will be stripped :arg allowed_css_keywords: set of CSS keywords to allow--everything else will be stripped :arg allowed_svg_properties: set of SVG properties to allow--everything else will be removed :arg allowed_protocols: set of allowed protocols for URIs :arg allowed_content_types: set of allowed content types for ``data`` URIs. :arg attr_val_is_uri: set of attributes that have URI values--values that have a scheme not listed in ``allowed_protocols`` are removed :arg svg_attr_val_allows_ref: set of SVG attributes that can have references :arg svg_allow_local_href: set of SVG elements that can have local hrefs--these are removed """ super(Filter, self).__init__(source) warnings.warn(_deprecation_msg, DeprecationWarning) self.allowed_elements = allowed_elements self.allowed_attributes = allowed_attributes self.allowed_css_properties = allowed_css_properties self.allowed_css_keywords = allowed_css_keywords self.allowed_svg_properties = allowed_svg_properties self.allowed_protocols = allowed_protocols self.allowed_content_types = allowed_content_types self.attr_val_is_uri = attr_val_is_uri self.svg_attr_val_allows_ref = svg_attr_val_allows_ref self.svg_allow_local_href = svg_allow_local_href
[ "def", "__init__", "(", "self", ",", "source", ",", "allowed_elements", "=", "allowed_elements", ",", "allowed_attributes", "=", "allowed_attributes", ",", "allowed_css_properties", "=", "allowed_css_properties", ",", "allowed_css_keywords", "=", "allowed_css_keywords", ",", "allowed_svg_properties", "=", "allowed_svg_properties", ",", "allowed_protocols", "=", "allowed_protocols", ",", "allowed_content_types", "=", "allowed_content_types", ",", "attr_val_is_uri", "=", "attr_val_is_uri", ",", "svg_attr_val_allows_ref", "=", "svg_attr_val_allows_ref", ",", "svg_allow_local_href", "=", "svg_allow_local_href", ")", ":", "super", "(", "Filter", ",", "self", ")", ".", "__init__", "(", "source", ")", "warnings", ".", "warn", "(", "_deprecation_msg", ",", "DeprecationWarning", ")", "self", ".", "allowed_elements", "=", "allowed_elements", "self", ".", "allowed_attributes", "=", "allowed_attributes", "self", ".", "allowed_css_properties", "=", "allowed_css_properties", "self", ".", "allowed_css_keywords", "=", "allowed_css_keywords", "self", ".", "allowed_svg_properties", "=", "allowed_svg_properties", "self", ".", "allowed_protocols", "=", "allowed_protocols", "self", ".", "allowed_content_types", "=", "allowed_content_types", "self", ".", "attr_val_is_uri", "=", "attr_val_is_uri", "self", ".", "svg_attr_val_allows_ref", "=", "svg_attr_val_allows_ref", "self", ".", "svg_allow_local_href", "=", "svg_allow_local_href" ]
[ 725, 4 ]
[ 781, 56 ]
python
en
['en', 'gl', 'en']
True
ItemRecommendationEvaluation.__init__
(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['PREC', 'RECALL', 'MAP', 'NDCG']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t')
Class to evaluate predictions in a item recommendation (ranking) scenario :param sep: Delimiter for input files :type sep: str, default '\t' :param n_ranks: List of positions to evaluate the ranking :type n_ranks: list, default [1, 3, 5, 10] :param metrics: List of evaluation metrics :type metrics: list, default ('PREC', 'RECALL', 'MAP', 'NDCG') :param all_but_one_eval: If True, considers only one pair (u, i) from the test set to evaluate the ranking :type all_but_one_eval: bool, default False :param verbose: Print the evaluation results :type verbose: bool, default True :param as_table: Print the evaluation results as table (only work with verbose=True) :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t'
Class to evaluate predictions in a item recommendation (ranking) scenario
def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['PREC', 'RECALL', 'MAP', 'NDCG']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'): """ Class to evaluate predictions in a item recommendation (ranking) scenario :param sep: Delimiter for input files :type sep: str, default '\t' :param n_ranks: List of positions to evaluate the ranking :type n_ranks: list, default [1, 3, 5, 10] :param metrics: List of evaluation metrics :type metrics: list, default ('PREC', 'RECALL', 'MAP', 'NDCG') :param all_but_one_eval: If True, considers only one pair (u, i) from the test set to evaluate the ranking :type all_but_one_eval: bool, default False :param verbose: Print the evaluation results :type verbose: bool, default True :param as_table: Print the evaluation results as table (only work with verbose=True) :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t' """ metrics = [m + '@' + str(n) for m in metrics for n in n_ranks] super(ItemRecommendationEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep) self.n_ranks = n_ranks
[ "def", "__init__", "(", "self", ",", "sep", "=", "'\\t'", ",", "n_ranks", "=", "list", "(", "[", "1", ",", "3", ",", "5", ",", "10", "]", ")", ",", "metrics", "=", "list", "(", "[", "'PREC'", ",", "'RECALL'", ",", "'MAP'", ",", "'NDCG'", "]", ")", ",", "all_but_one_eval", "=", "False", ",", "verbose", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ")", ":", "metrics", "=", "[", "m", "+", "'@'", "+", "str", "(", "n", ")", "for", "m", "in", "metrics", "for", "n", "in", "n_ranks", "]", "super", "(", "ItemRecommendationEvaluation", ",", "self", ")", ".", "__init__", "(", "sep", "=", "sep", ",", "metrics", "=", "metrics", ",", "all_but_one_eval", "=", "all_but_one_eval", ",", "verbose", "=", "verbose", ",", "as_table", "=", "as_table", ",", "table_sep", "=", "table_sep", ")", "self", ".", "n_ranks", "=", "n_ranks" ]
[ 28, 4 ]
[ 61, 30 ]
python
en
['en', 'error', 'th']
False
ItemRecommendationEvaluation.evaluate
(self, predictions, test_set)
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict :param predictions: Dictionary with ranking information :type predictions: dict :param test_set: Dictionary with test set information. :type test_set: dict :return: Dictionary with all evaluation metrics and results :rtype: dict
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict
def evaluate(self, predictions, test_set): """ Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict :param predictions: Dictionary with ranking information :type predictions: dict :param test_set: Dictionary with test set information. :type test_set: dict :return: Dictionary with all evaluation metrics and results :rtype: dict """ eval_results = {} num_user = len(test_set['users']) partial_map_all = None if self.all_but_one_eval: for user in test_set['users']: # select a random item test_set['items_seen_by_user'][user] = [random.choice(test_set['items_seen_by_user'].get(user, [-1]))] for i, n in enumerate(self.n_ranks): if n < 1: raise ValueError('Error: N must >= 1.') partial_precision = list() partial_recall = list() partial_ndcg = list() partial_map = list() for user in test_set['users']: hit_cont = 0 # Generate user intersection list between the recommended items and test. list_feedback = set(list(predictions.get(user, []))[:n]) intersection = list(list_feedback.intersection(test_set['items_seen_by_user'].get(user, []))) if len(intersection) > 0: ig_ranking = np.zeros(n) for item in intersection: hit_cont += 1 ig_ranking[list(predictions[user]).index(item)] = 1 partial_precision.append(precision_at_k([ig_ranking], n)) partial_recall.append((float(len(intersection)) / float(len(test_set['items_seen_by_user'][user])))) partial_map.append(mean_average_precision([ig_ranking])) partial_ndcg.append(ndcg_at_k(list(ig_ranking))) partial_map_all = partial_map # create a dictionary with final results eval_results.update({ 'PREC@' + str(n): round(sum(partial_precision) / float(num_user), 6), 'RECALL@' + str(n): round(sum(partial_recall) / float(num_user), 6), 'NDCG@' + str(n): round(sum(partial_ndcg) / float(num_user), 6), 'MAP@' + str(n): round(sum(partial_map) / float(num_user), 6), 'MAP': round(sum(partial_map_all) / float(num_user), 6) }) if self.verbose: self.print_results(eval_results) return eval_results
[ "def", "evaluate", "(", "self", ",", "predictions", ",", "test_set", ")", ":", "eval_results", "=", "{", "}", "num_user", "=", "len", "(", "test_set", "[", "'users'", "]", ")", "partial_map_all", "=", "None", "if", "self", ".", "all_but_one_eval", ":", "for", "user", "in", "test_set", "[", "'users'", "]", ":", "# select a random item", "test_set", "[", "'items_seen_by_user'", "]", "[", "user", "]", "=", "[", "random", ".", "choice", "(", "test_set", "[", "'items_seen_by_user'", "]", ".", "get", "(", "user", ",", "[", "-", "1", "]", ")", ")", "]", "for", "i", ",", "n", "in", "enumerate", "(", "self", ".", "n_ranks", ")", ":", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "'Error: N must >= 1.'", ")", "partial_precision", "=", "list", "(", ")", "partial_recall", "=", "list", "(", ")", "partial_ndcg", "=", "list", "(", ")", "partial_map", "=", "list", "(", ")", "for", "user", "in", "test_set", "[", "'users'", "]", ":", "hit_cont", "=", "0", "# Generate user intersection list between the recommended items and test.", "list_feedback", "=", "set", "(", "list", "(", "predictions", ".", "get", "(", "user", ",", "[", "]", ")", ")", "[", ":", "n", "]", ")", "intersection", "=", "list", "(", "list_feedback", ".", "intersection", "(", "test_set", "[", "'items_seen_by_user'", "]", ".", "get", "(", "user", ",", "[", "]", ")", ")", ")", "if", "len", "(", "intersection", ")", ">", "0", ":", "ig_ranking", "=", "np", ".", "zeros", "(", "n", ")", "for", "item", "in", "intersection", ":", "hit_cont", "+=", "1", "ig_ranking", "[", "list", "(", "predictions", "[", "user", "]", ")", ".", "index", "(", "item", ")", "]", "=", "1", "partial_precision", ".", "append", "(", "precision_at_k", "(", "[", "ig_ranking", "]", ",", "n", ")", ")", "partial_recall", ".", "append", "(", "(", "float", "(", "len", "(", "intersection", ")", ")", "/", "float", "(", "len", "(", "test_set", "[", "'items_seen_by_user'", "]", "[", "user", "]", ")", ")", ")", ")", "partial_map", ".", "append", "(", "mean_average_precision", "(", "[", "ig_ranking", "]", ")", ")", "partial_ndcg", ".", "append", "(", "ndcg_at_k", "(", "list", "(", "ig_ranking", ")", ")", ")", "partial_map_all", "=", "partial_map", "# create a dictionary with final results", "eval_results", ".", "update", "(", "{", "'PREC@'", "+", "str", "(", "n", ")", ":", "round", "(", "sum", "(", "partial_precision", ")", "/", "float", "(", "num_user", ")", ",", "6", ")", ",", "'RECALL@'", "+", "str", "(", "n", ")", ":", "round", "(", "sum", "(", "partial_recall", ")", "/", "float", "(", "num_user", ")", ",", "6", ")", ",", "'NDCG@'", "+", "str", "(", "n", ")", ":", "round", "(", "sum", "(", "partial_ndcg", ")", "/", "float", "(", "num_user", ")", ",", "6", ")", ",", "'MAP@'", "+", "str", "(", "n", ")", ":", "round", "(", "sum", "(", "partial_map", ")", "/", "float", "(", "num_user", ")", ",", "6", ")", ",", "'MAP'", ":", "round", "(", "sum", "(", "partial_map_all", ")", "/", "float", "(", "num_user", ")", ",", "6", ")", "}", ")", "if", "self", ".", "verbose", ":", "self", ".", "print_results", "(", "eval_results", ")", "return", "eval_results" ]
[ 63, 4 ]
[ 129, 27 ]
python
en
['en', 'error', 'th']
False
deconstructible
(*args, path=None)
Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path.
Class decorator that allows the decorated class to be serialized by the migrations subsystem.
def deconstructible(*args, path=None): """ Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path. """ def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Return a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Fallback version if path: module_name, _, name = path.rpartition('.') else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" % (name, module_name, get_docs_version())) return ( path or '%s.%s' % (obj.__class__.__module__, name), obj._constructor_args[0], obj._constructor_args[1], ) klass.__new__ = staticmethod(__new__) klass.deconstruct = deconstruct return klass if not args: return decorator return decorator(*args)
[ "def", "deconstructible", "(", "*", "args", ",", "path", "=", "None", ")", ":", "def", "decorator", "(", "klass", ")", ":", "def", "__new__", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# We capture the arguments to make returning them trivial", "obj", "=", "super", "(", "klass", ",", "cls", ")", ".", "__new__", "(", "cls", ")", "obj", ".", "_constructor_args", "=", "(", "args", ",", "kwargs", ")", "return", "obj", "def", "deconstruct", "(", "obj", ")", ":", "\"\"\"\n Return a 3-tuple of class import path, positional arguments,\n and keyword arguments.\n \"\"\"", "# Fallback version", "if", "path", ":", "module_name", ",", "_", ",", "name", "=", "path", ".", "rpartition", "(", "'.'", ")", "else", ":", "module_name", "=", "obj", ".", "__module__", "name", "=", "obj", ".", "__class__", ".", "__name__", "# Make sure it's actually there and not an inner class", "module", "=", "import_module", "(", "module_name", ")", "if", "not", "hasattr", "(", "module", ",", "name", ")", ":", "raise", "ValueError", "(", "\"Could not find object %s in %s.\\n\"", "\"Please note that you cannot serialize things like inner \"", "\"classes. Please move the object into the main module \"", "\"body to use migrations.\\n\"", "\"For more information, see \"", "\"https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values\"", "%", "(", "name", ",", "module_name", ",", "get_docs_version", "(", ")", ")", ")", "return", "(", "path", "or", "'%s.%s'", "%", "(", "obj", ".", "__class__", ".", "__module__", ",", "name", ")", ",", "obj", ".", "_constructor_args", "[", "0", "]", ",", "obj", ".", "_constructor_args", "[", "1", "]", ",", ")", "klass", ".", "__new__", "=", "staticmethod", "(", "__new__", ")", "klass", ".", "deconstruct", "=", "deconstruct", "return", "klass", "if", "not", "args", ":", "return", "decorator", "return", "decorator", "(", "*", "args", ")" ]
[ 5, 0 ]
[ 54, 27 ]
python
en
['en', 'error', 'th']
False
AppAssertionCredentials.__init__
(self, email=None, *args, **kwargs)
Constructor for AppAssertionCredentials Args: email: an email that specifies the service account to use. Only necessary if using custom service accounts (see https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#createdefaultserviceaccount).
Constructor for AppAssertionCredentials
def __init__(self, email=None, *args, **kwargs): """Constructor for AppAssertionCredentials Args: email: an email that specifies the service account to use. Only necessary if using custom service accounts (see https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#createdefaultserviceaccount). """ if 'scopes' in kwargs: warnings.warn(_SCOPES_WARNING) kwargs['scopes'] = None # Assertion type is no longer used, but still in the # parent class signature. super(AppAssertionCredentials, self).__init__(None, *args, **kwargs) self.service_account_email = email self.scopes = None self.invalid = True
[ "def", "__init__", "(", "self", ",", "email", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'scopes'", "in", "kwargs", ":", "warnings", ".", "warn", "(", "_SCOPES_WARNING", ")", "kwargs", "[", "'scopes'", "]", "=", "None", "# Assertion type is no longer used, but still in the", "# parent class signature.", "super", "(", "AppAssertionCredentials", ",", "self", ")", ".", "__init__", "(", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "service_account_email", "=", "email", "self", ".", "scopes", "=", "None", "self", ".", "invalid", "=", "True" ]
[ 56, 4 ]
[ 74, 27 ]
python
en
['da', 'en', 'en']
True
AppAssertionCredentials.retrieve_scopes
(self, http)
Retrieves the canonical list of scopes for this access token. Overrides client.Credentials.retrieve_scopes. Fetches scopes info from the metadata server. Args: http: httplib2.Http, an http object to be used to make the refresh request. Returns: A set of strings containing the canonical list of scopes.
Retrieves the canonical list of scopes for this access token.
def retrieve_scopes(self, http): """Retrieves the canonical list of scopes for this access token. Overrides client.Credentials.retrieve_scopes. Fetches scopes info from the metadata server. Args: http: httplib2.Http, an http object to be used to make the refresh request. Returns: A set of strings containing the canonical list of scopes. """ self._retrieve_info(http) return self.scopes
[ "def", "retrieve_scopes", "(", "self", ",", "http", ")", ":", "self", ".", "_retrieve_info", "(", "http", ")", "return", "self", ".", "scopes" ]
[ 85, 4 ]
[ 99, 26 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials._retrieve_info
(self, http)
Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests.
Retrieves service account info for invalid credentials.
def _retrieve_info(self, http): """Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests. """ if self.invalid: info = _metadata.get_service_account_info( http, service_account=self.service_account_email or 'default') self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes']
[ "def", "_retrieve_info", "(", "self", ",", "http", ")", ":", "if", "self", ".", "invalid", ":", "info", "=", "_metadata", ".", "get_service_account_info", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", "or", "'default'", ")", "self", ".", "invalid", "=", "False", "self", ".", "service_account_email", "=", "info", "[", "'email'", "]", "self", ".", "scopes", "=", "info", "[", "'scopes'", "]" ]
[ 101, 4 ]
[ 113, 40 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials._refresh
(self, http)
Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
Refreshes the access token.
def _refresh(self, http): """Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ try: self._retrieve_info(http) self.access_token, self.token_expiry = _metadata.get_token( http, service_account=self.service_account_email) except http_client.HTTPException as err: raise client.HttpAccessTokenRefreshError(str(err))
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "try", ":", "self", ".", "_retrieve_info", "(", "http", ")", "self", ".", "access_token", ",", "self", ".", "token_expiry", "=", "_metadata", ".", "get_token", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", ")", "except", "http_client", ".", "HTTPException", "as", "err", ":", "raise", "client", ".", "HttpAccessTokenRefreshError", "(", "str", "(", "err", ")", ")" ]
[ 115, 4 ]
[ 131, 62 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials.sign_blob
(self, blob)
Cryptographically sign a blob (of bytes). This method is provided to support a common interface, but the actual key used for a Google Compute Engine service account is not available, so it can't be used to sign content. Args: blob: bytes, Message to be signed. Raises: NotImplementedError, always.
Cryptographically sign a blob (of bytes).
def sign_blob(self, blob): """Cryptographically sign a blob (of bytes). This method is provided to support a common interface, but the actual key used for a Google Compute Engine service account is not available, so it can't be used to sign content. Args: blob: bytes, Message to be signed. Raises: NotImplementedError, always. """ raise NotImplementedError( 'Compute Engine service accounts cannot sign blobs')
[ "def", "sign_blob", "(", "self", ",", "blob", ")", ":", "raise", "NotImplementedError", "(", "'Compute Engine service accounts cannot sign blobs'", ")" ]
[ 141, 4 ]
[ 155, 64 ]
python
en
['en', 'en', 'en']
True
check_cs_op
(result, func, cargs)
Check the status code of a coordinate sequence operation.
Check the status code of a coordinate sequence operation.
def check_cs_op(result, func, cargs): "Check the status code of a coordinate sequence operation." if result == 0: raise GEOSException('Could not set value on coordinate sequence') else: return result
[ "def", "check_cs_op", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "0", ":", "raise", "GEOSException", "(", "'Could not set value on coordinate sequence'", ")", "else", ":", "return", "result" ]
[ 9, 0 ]
[ 14, 21 ]
python
en
['en', 'en', 'en']
True
check_cs_get
(result, func, cargs)
Check the coordinate sequence retrieval.
Check the coordinate sequence retrieval.
def check_cs_get(result, func, cargs): "Check the coordinate sequence retrieval." check_cs_op(result, func, cargs) # Object in by reference, return its value. return last_arg_byref(cargs)
[ "def", "check_cs_get", "(", "result", ",", "func", ",", "cargs", ")", ":", "check_cs_op", "(", "result", ",", "func", ",", "cargs", ")", "# Object in by reference, return its value.", "return", "last_arg_byref", "(", "cargs", ")" ]
[ 17, 0 ]
[ 21, 32 ]
python
en
['en', 'en', 'en']
True
install_given_reqs
( requirements: List[InstallRequirement], install_options: List[str], global_options: Sequence[str], root: Optional[str], home: Optional[str], prefix: Optional[str], warn_script_location: bool, use_user_site: bool, pycompile: bool, )
Install everything in the given list. (to be called after having downloaded and unpacked the packages)
Install everything in the given list.
def install_given_reqs( requirements: List[InstallRequirement], install_options: List[str], global_options: Sequence[str], root: Optional[str], home: Optional[str], prefix: Optional[str], warn_script_location: bool, use_user_site: bool, pycompile: bool, ) -> List[InstallationResult]: """ Install everything in the given list. (to be called after having downloaded and unpacked the packages) """ to_install = collections.OrderedDict(_validate_requirements(requirements)) if to_install: logger.info( 'Installing collected packages: %s', ', '.join(to_install.keys()), ) installed = [] with indent_log(): for req_name, requirement in to_install.items(): if requirement.should_reinstall: logger.info('Attempting uninstall: %s', req_name) with indent_log(): uninstalled_pathset = requirement.uninstall( auto_confirm=True ) else: uninstalled_pathset = None try: requirement.install( install_options, global_options, root=root, home=home, prefix=prefix, warn_script_location=warn_script_location, use_user_site=use_user_site, pycompile=pycompile, ) except Exception: # if install did not succeed, rollback previous uninstall if uninstalled_pathset and not requirement.install_succeeded: uninstalled_pathset.rollback() raise else: if uninstalled_pathset and requirement.install_succeeded: uninstalled_pathset.commit() installed.append(InstallationResult(req_name)) return installed
[ "def", "install_given_reqs", "(", "requirements", ":", "List", "[", "InstallRequirement", "]", ",", "install_options", ":", "List", "[", "str", "]", ",", "global_options", ":", "Sequence", "[", "str", "]", ",", "root", ":", "Optional", "[", "str", "]", ",", "home", ":", "Optional", "[", "str", "]", ",", "prefix", ":", "Optional", "[", "str", "]", ",", "warn_script_location", ":", "bool", ",", "use_user_site", ":", "bool", ",", "pycompile", ":", "bool", ",", ")", "->", "List", "[", "InstallationResult", "]", ":", "to_install", "=", "collections", ".", "OrderedDict", "(", "_validate_requirements", "(", "requirements", ")", ")", "if", "to_install", ":", "logger", ".", "info", "(", "'Installing collected packages: %s'", ",", "', '", ".", "join", "(", "to_install", ".", "keys", "(", ")", ")", ",", ")", "installed", "=", "[", "]", "with", "indent_log", "(", ")", ":", "for", "req_name", ",", "requirement", "in", "to_install", ".", "items", "(", ")", ":", "if", "requirement", ".", "should_reinstall", ":", "logger", ".", "info", "(", "'Attempting uninstall: %s'", ",", "req_name", ")", "with", "indent_log", "(", ")", ":", "uninstalled_pathset", "=", "requirement", ".", "uninstall", "(", "auto_confirm", "=", "True", ")", "else", ":", "uninstalled_pathset", "=", "None", "try", ":", "requirement", ".", "install", "(", "install_options", ",", "global_options", ",", "root", "=", "root", ",", "home", "=", "home", ",", "prefix", "=", "prefix", ",", "warn_script_location", "=", "warn_script_location", ",", "use_user_site", "=", "use_user_site", ",", "pycompile", "=", "pycompile", ",", ")", "except", "Exception", ":", "# if install did not succeed, rollback previous uninstall", "if", "uninstalled_pathset", "and", "not", "requirement", ".", "install_succeeded", ":", "uninstalled_pathset", ".", "rollback", "(", ")", "raise", "else", ":", "if", "uninstalled_pathset", "and", "requirement", ".", "install_succeeded", ":", "uninstalled_pathset", ".", "commit", "(", ")", "installed", ".", "append", "(", "InstallationResult", "(", "req_name", ")", ")", "return", "installed" ]
[ 34, 0 ]
[ 93, 20 ]
python
en
['en', 'error', 'th']
False
run
(argv=None)
The main function which creates the pipeline and runs it.
The main function which creates the pipeline and runs it.
def run(argv=None): """The main function which creates the pipeline and runs it.""" parser = argparse.ArgumentParser() # Here we add some specific command line arguments we expect. # Specifically we have the input file to read and the output table to write. # This is the final stage of the pipeline, where we define the destination # of the data. In this case we are writing to BigQuery. parser.add_argument( '--input', dest='input', required=False, help='Input file to read. This can be a local file or ' 'a file in a Google Storage Bucket.', # This example file contains a total of only 10 lines. # Useful for developing on a small set of data. default='gs://python-dataflow-example/data_files/head_usa_names.csv') # This defaults to the lake dataset in your BigQuery project. You'll have # to create the lake dataset yourself using this command: # bq mk lake parser.add_argument('--output', dest='output', required=False, help='Output BQ table to write results to.', default='lake.usa_names') # Parse arguments from the command line. known_args, pipeline_args = parser.parse_known_args(argv) # DataIngestion is a class we built in this script to hold the logic for # transforming the file into a BigQuery table. data_ingestion = DataIngestion() # Initiate the pipeline using the pipeline arguments passed in from the # command line. This includes information such as the project ID and # where Dataflow should store temp files. p = beam.Pipeline(options=PipelineOptions(pipeline_args)) (p # Read the file. This is the source of the pipeline. All further # processing starts with lines read from the file. We use the input # argument from the command line. We also skip the first line which is a # header row. | 'Read from a File' >> beam.io.ReadFromText(known_args.input, skip_header_lines=1) # This stage of the pipeline translates from a CSV file single row # input as a string, to a dictionary object consumable by BigQuery. # It refers to a function we have written. This function will # be run in parallel on different workers using input from the # previous stage of the pipeline. | 'String To BigQuery Row' >> beam.Map(lambda s: data_ingestion.parse_method(s)) | 'Write to BigQuery' >> beam.io.Write( beam.io.BigQuerySink( # The table name is a required argument for the BigQuery sink. # In this case we use the value passed in from the command line. known_args.output, # Here we use the simplest way of defining a schema: # fieldName:fieldType schema='state:STRING,gender:STRING,year:STRING,name:STRING,' 'number:STRING,created_date:STRING', # Creates the table in BigQuery if it does not yet exist. create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, # Deletes all data in the BigQuery table before writing. write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE))) p.run().wait_until_finish()
[ "def", "run", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Here we add some specific command line arguments we expect.", "# Specifically we have the input file to read and the output table to write.", "# This is the final stage of the pipeline, where we define the destination", "# of the data. In this case we are writing to BigQuery.", "parser", ".", "add_argument", "(", "'--input'", ",", "dest", "=", "'input'", ",", "required", "=", "False", ",", "help", "=", "'Input file to read. This can be a local file or '", "'a file in a Google Storage Bucket.'", ",", "# This example file contains a total of only 10 lines.", "# Useful for developing on a small set of data.", "default", "=", "'gs://python-dataflow-example/data_files/head_usa_names.csv'", ")", "# This defaults to the lake dataset in your BigQuery project. You'll have", "# to create the lake dataset yourself using this command:", "# bq mk lake", "parser", ".", "add_argument", "(", "'--output'", ",", "dest", "=", "'output'", ",", "required", "=", "False", ",", "help", "=", "'Output BQ table to write results to.'", ",", "default", "=", "'lake.usa_names'", ")", "# Parse arguments from the command line.", "known_args", ",", "pipeline_args", "=", "parser", ".", "parse_known_args", "(", "argv", ")", "# DataIngestion is a class we built in this script to hold the logic for", "# transforming the file into a BigQuery table.", "data_ingestion", "=", "DataIngestion", "(", ")", "# Initiate the pipeline using the pipeline arguments passed in from the", "# command line. This includes information such as the project ID and", "# where Dataflow should store temp files.", "p", "=", "beam", ".", "Pipeline", "(", "options", "=", "PipelineOptions", "(", "pipeline_args", ")", ")", "(", "p", "# Read the file. This is the source of the pipeline. All further", "# processing starts with lines read from the file. We use the input", "# argument from the command line. We also skip the first line which is a", "# header row.", "|", "'Read from a File'", ">>", "beam", ".", "io", ".", "ReadFromText", "(", "known_args", ".", "input", ",", "skip_header_lines", "=", "1", ")", "# This stage of the pipeline translates from a CSV file single row", "# input as a string, to a dictionary object consumable by BigQuery.", "# It refers to a function we have written. This function will", "# be run in parallel on different workers using input from the", "# previous stage of the pipeline.", "|", "'String To BigQuery Row'", ">>", "beam", ".", "Map", "(", "lambda", "s", ":", "data_ingestion", ".", "parse_method", "(", "s", ")", ")", "|", "'Write to BigQuery'", ">>", "beam", ".", "io", ".", "Write", "(", "beam", ".", "io", ".", "BigQuerySink", "(", "# The table name is a required argument for the BigQuery sink.", "# In this case we use the value passed in from the command line.", "known_args", ".", "output", ",", "# Here we use the simplest way of defining a schema:", "# fieldName:fieldType", "schema", "=", "'state:STRING,gender:STRING,year:STRING,name:STRING,'", "'number:STRING,created_date:STRING'", ",", "# Creates the table in BigQuery if it does not yet exist.", "create_disposition", "=", "beam", ".", "io", ".", "BigQueryDisposition", ".", "CREATE_IF_NEEDED", ",", "# Deletes all data in the BigQuery table before writing.", "write_disposition", "=", "beam", ".", "io", ".", "BigQueryDisposition", ".", "WRITE_TRUNCATE", ")", ")", ")", "p", ".", "run", "(", ")", ".", "wait_until_finish", "(", ")" ]
[ 61, 0 ]
[ 128, 31 ]
python
en
['en', 'en', 'en']
True
DataIngestion.parse_method
(self, string_input)
This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery. Args: string_input: A comma separated list of values in the form of state_abbreviation,gender,year,name,count_of_babies,dataset_created_date Example string_input: KS,F,1923,Dorothy,654,11/28/2016 Returns: A dict mapping BigQuery column names as keys to the corresponding value parsed from string_input. In this example, the data is not transformed, and remains in the same format as the CSV. example output: { 'state': 'KS', 'gender': 'F', 'year': '1923', 'name': 'Dorothy', 'number': '654', 'created_date': '11/28/2016' }
This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery.
def parse_method(self, string_input): """This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery. Args: string_input: A comma separated list of values in the form of state_abbreviation,gender,year,name,count_of_babies,dataset_created_date Example string_input: KS,F,1923,Dorothy,654,11/28/2016 Returns: A dict mapping BigQuery column names as keys to the corresponding value parsed from string_input. In this example, the data is not transformed, and remains in the same format as the CSV. example output: { 'state': 'KS', 'gender': 'F', 'year': '1923', 'name': 'Dorothy', 'number': '654', 'created_date': '11/28/2016' } """ # Strip out carriage return, newline and quote characters. values = re.split(",", re.sub('\r\n', '', re.sub(u'"', '', string_input))) row = dict( zip(('state', 'gender', 'year', 'name', 'number', 'created_date'), values)) return row
[ "def", "parse_method", "(", "self", ",", "string_input", ")", ":", "# Strip out carriage return, newline and quote characters.", "values", "=", "re", ".", "split", "(", "\",\"", ",", "re", ".", "sub", "(", "'\\r\\n'", ",", "''", ",", "re", ".", "sub", "(", "u'\"'", ",", "''", ",", "string_input", ")", ")", ")", "row", "=", "dict", "(", "zip", "(", "(", "'state'", ",", "'gender'", ",", "'year'", ",", "'name'", ",", "'number'", ",", "'created_date'", ")", ",", "values", ")", ")", "return", "row" ]
[ 29, 4 ]
[ 58, 18 ]
python
en
['en', 'en', 'en']
True
View.__init__
(self, **kwargs)
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value)
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Go through keyword arguments, and either save their values to our", "# instance, or raise an error.", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
[ 37, 4 ]
[ 45, 37 ]
python
en
['en', 'error', 'th']
False
View.as_view
(cls, **initkwargs)
Main entry point for a request-response process.
Main entry point for a request-response process.
def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError( 'The method name %s is not accepted as a keyword argument ' 'to %s().' % (key, cls.__name__) ) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) self.setup(request, *args, **kwargs) if not hasattr(self, 'request'): raise AttributeError( "%s instance has no 'request' attribute. Did you override " "setup() and forget to call super()?" % cls.__name__ ) return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
[ "def", "as_view", "(", "cls", ",", "*", "*", "initkwargs", ")", ":", "for", "key", "in", "initkwargs", ":", "if", "key", "in", "cls", ".", "http_method_names", ":", "raise", "TypeError", "(", "'The method name %s is not accepted as a keyword argument '", "'to %s().'", "%", "(", "key", ",", "cls", ".", "__name__", ")", ")", "if", "not", "hasattr", "(", "cls", ",", "key", ")", ":", "raise", "TypeError", "(", "\"%s() received an invalid keyword %r. as_view \"", "\"only accepts arguments that are already \"", "\"attributes of the class.\"", "%", "(", "cls", ".", "__name__", ",", "key", ")", ")", "def", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "cls", "(", "*", "*", "initkwargs", ")", "self", ".", "setup", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "hasattr", "(", "self", ",", "'request'", ")", ":", "raise", "AttributeError", "(", "\"%s instance has no 'request' attribute. Did you override \"", "\"setup() and forget to call super()?\"", "%", "cls", ".", "__name__", ")", "return", "self", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "view", ".", "view_class", "=", "cls", "view", ".", "view_initkwargs", "=", "initkwargs", "# take name and docstring from class", "update_wrapper", "(", "view", ",", "cls", ",", "updated", "=", "(", ")", ")", "# and possible attributes set by decorators", "# like csrf_exempt from dispatch", "update_wrapper", "(", "view", ",", "cls", ".", "dispatch", ",", "assigned", "=", "(", ")", ")", "return", "view" ]
[ 48, 4 ]
[ 79, 19 ]
python
en
['en', 'en', 'en']
True
View.setup
(self, request, *args, **kwargs)
Initialize attributes shared by all view methods.
Initialize attributes shared by all view methods.
def setup(self, request, *args, **kwargs): """Initialize attributes shared by all view methods.""" if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs
[ "def", "setup", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'get'", ")", "and", "not", "hasattr", "(", "self", ",", "'head'", ")", ":", "self", ".", "head", "=", "self", ".", "get", "self", ".", "request", "=", "request", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs" ]
[ 81, 4 ]
[ 87, 28 ]
python
en
['en', 'en', 'en']
True
View.options
(self, request, *args, **kwargs)
Handle responding to requests for the OPTIONS HTTP verb.
Handle responding to requests for the OPTIONS HTTP verb.
def options(self, request, *args, **kwargs): """Handle responding to requests for the OPTIONS HTTP verb.""" response = HttpResponse() response.headers['Allow'] = ', '.join(self._allowed_methods()) response.headers['Content-Length'] = '0' return response
[ "def", "options", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "HttpResponse", "(", ")", "response", ".", "headers", "[", "'Allow'", "]", "=", "', '", ".", "join", "(", "self", ".", "_allowed_methods", "(", ")", ")", "response", ".", "headers", "[", "'Content-Length'", "]", "=", "'0'", "return", "response" ]
[ 106, 4 ]
[ 111, 23 ]
python
en
['en', 'en', 'en']
True
TemplateResponseMixin.render_to_response
(self, context, **response_kwargs)
Return a response, using the `response_class` for this view, with a template rendered with the given context. Pass response_kwargs to the constructor of the response class.
Return a response, using the `response_class` for this view, with a template rendered with the given context.
def render_to_response(self, context, **response_kwargs): """ Return a response, using the `response_class` for this view, with a template rendered with the given context. Pass response_kwargs to the constructor of the response class. """ response_kwargs.setdefault('content_type', self.content_type) return self.response_class( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, **response_kwargs )
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "response_kwargs", ".", "setdefault", "(", "'content_type'", ",", "self", ".", "content_type", ")", "return", "self", ".", "response_class", "(", "request", "=", "self", ".", "request", ",", "template", "=", "self", ".", "get_template_names", "(", ")", ",", "context", "=", "context", ",", "using", "=", "self", ".", "template_engine", ",", "*", "*", "response_kwargs", ")" ]
[ 124, 4 ]
[ 138, 9 ]
python
en
['en', 'error', 'th']
False
TemplateResponseMixin.get_template_names
(self)
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden.
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden.
def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden. """ if self.template_name is None: raise ImproperlyConfigured( "TemplateResponseMixin requires either a definition of " "'template_name' or an implementation of 'get_template_names()'") else: return [self.template_name]
[ "def", "get_template_names", "(", "self", ")", ":", "if", "self", ".", "template_name", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"TemplateResponseMixin requires either a definition of \"", "\"'template_name' or an implementation of 'get_template_names()'\"", ")", "else", ":", "return", "[", "self", ".", "template_name", "]" ]
[ 140, 4 ]
[ 150, 39 ]
python
en
['en', 'error', 'th']
False
RedirectView.get_redirect_url
(self, *args, **kwargs)
Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method.
Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method.
def get_redirect_url(self, *args, **kwargs): """ Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method. """ if self.url: url = self.url % kwargs elif self.pattern_name: url = reverse(self.pattern_name, args=args, kwargs=kwargs) else: return None args = self.request.META.get('QUERY_STRING', '') if args and self.query_string: url = "%s?%s" % (url, args) return url
[ "def", "get_redirect_url", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "url", ":", "url", "=", "self", ".", "url", "%", "kwargs", "elif", "self", ".", "pattern_name", ":", "url", "=", "reverse", "(", "self", ".", "pattern_name", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "else", ":", "return", "None", "args", "=", "self", ".", "request", ".", "META", ".", "get", "(", "'QUERY_STRING'", ",", "''", ")", "if", "args", "and", "self", ".", "query_string", ":", "url", "=", "\"%s?%s\"", "%", "(", "url", ",", "args", ")", "return", "url" ]
[ 169, 4 ]
[ 185, 18 ]
python
en
['en', 'error', 'th']
False
get_hstore_oids
(connection_alias)
Return hstore and hstore array OIDs.
Return hstore and hstore array OIDs.
def get_hstore_oids(connection_alias): """Return hstore and hstore array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute( "SELECT t.oid, typarray " "FROM pg_type t " "JOIN pg_namespace ns ON typnamespace = ns.oid " "WHERE typname = 'hstore'" ) oids = [] array_oids = [] for row in cursor: oids.append(row[0]) array_oids.append(row[1]) return tuple(oids), tuple(array_oids)
[ "def", "get_hstore_oids", "(", "connection_alias", ")", ":", "with", "connections", "[", "connection_alias", "]", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT t.oid, typarray \"", "\"FROM pg_type t \"", "\"JOIN pg_namespace ns ON typnamespace = ns.oid \"", "\"WHERE typname = 'hstore'\"", ")", "oids", "=", "[", "]", "array_oids", "=", "[", "]", "for", "row", "in", "cursor", ":", "oids", ".", "append", "(", "row", "[", "0", "]", ")", "array_oids", ".", "append", "(", "row", "[", "1", "]", ")", "return", "tuple", "(", "oids", ")", ",", "tuple", "(", "array_oids", ")" ]
[ 11, 0 ]
[ 25, 45 ]
python
en
['en', 'en', 'en']
True
get_citext_oids
(connection_alias)
Return citext array OIDs.
Return citext array OIDs.
def get_citext_oids(connection_alias): """Return citext array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute("SELECT typarray FROM pg_type WHERE typname = 'citext'") return tuple(row[0] for row in cursor)
[ "def", "get_citext_oids", "(", "connection_alias", ")", ":", "with", "connections", "[", "connection_alias", "]", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT typarray FROM pg_type WHERE typname = 'citext'\"", ")", "return", "tuple", "(", "row", "[", "0", "]", "for", "row", "in", "cursor", ")" ]
[ 29, 0 ]
[ 33, 46 ]
python
en
['en', 'fr', 'en']
True
generate_recommendations
(user_idx, user_rated, row_factor, col_factor, k)
Generate recommendations for a user. Args: user_idx: the row index of the user in the ratings matrix, user_rated: the list of item indexes (column indexes in the ratings matrix) previously rated by that user (which will be excluded from the recommendations), row_factor: the row factors of the recommendation model col_factor: the column factors of the recommendation model k: number of recommendations requested Returns: list of k item indexes with the predicted highest rating, excluding those that the user has already rated
Generate recommendations for a user.
def generate_recommendations(user_idx, user_rated, row_factor, col_factor, k): """Generate recommendations for a user. Args: user_idx: the row index of the user in the ratings matrix, user_rated: the list of item indexes (column indexes in the ratings matrix) previously rated by that user (which will be excluded from the recommendations), row_factor: the row factors of the recommendation model col_factor: the column factors of the recommendation model k: number of recommendations requested Returns: list of k item indexes with the predicted highest rating, excluding those that the user has already rated """ # bounds checking for args assert (row_factor.shape[0] - len(user_rated)) >= k # retrieve user factor user_f = row_factor[user_idx] # dot product of item factors with user factor gives predicted ratings pred_ratings = col_factor.dot(user_f) # find candidate recommended item indexes sorted by predicted rating k_r = k + len(user_rated) candidate_items = np.argsort(pred_ratings)[-k_r:] # remove previously rated items and take top k recommended_items = [i for i in candidate_items if i not in user_rated] recommended_items = recommended_items[-k:] # flip to sort highest rated first recommended_items.reverse() return recommended_items
[ "def", "generate_recommendations", "(", "user_idx", ",", "user_rated", ",", "row_factor", ",", "col_factor", ",", "k", ")", ":", "# bounds checking for args", "assert", "(", "row_factor", ".", "shape", "[", "0", "]", "-", "len", "(", "user_rated", ")", ")", ">=", "k", "# retrieve user factor", "user_f", "=", "row_factor", "[", "user_idx", "]", "# dot product of item factors with user factor gives predicted ratings", "pred_ratings", "=", "col_factor", ".", "dot", "(", "user_f", ")", "# find candidate recommended item indexes sorted by predicted rating", "k_r", "=", "k", "+", "len", "(", "user_rated", ")", "candidate_items", "=", "np", ".", "argsort", "(", "pred_ratings", ")", "[", "-", "k_r", ":", "]", "# remove previously rated items and take top k", "recommended_items", "=", "[", "i", "for", "i", "in", "candidate_items", "if", "i", "not", "in", "user_rated", "]", "recommended_items", "=", "recommended_items", "[", "-", "k", ":", "]", "# flip to sort highest rated first", "recommended_items", ".", "reverse", "(", ")", "return", "recommended_items" ]
[ 120, 0 ]
[ 161, 26 ]
python
en
['en', 'en', 'en']
True
Recommendations._load_model
(self, local_model_path)
Load recommendation model files from GCS. Args: local_model_path: (string) local path to model files
Load recommendation model files from GCS.
def _load_model(self, local_model_path): """Load recommendation model files from GCS. Args: local_model_path: (string) local path to model files """ # download files from GCS to local storage os.makedirs(os.path.join(local_model_path, 'model'), exist_ok=True) os.makedirs(os.path.join(local_model_path, 'data'), exist_ok=True) client = storage.Client() bucket = client.get_bucket(self._bucket) logging.info('Downloading blobs.') model_files = [ROW_MODEL_FILE, COL_MODEL_FILE, USER_MODEL_FILE, ITEM_MODEL_FILE, USER_ITEM_DATA_FILE] for model_file in model_files: blob = bucket.blob(model_file) with open(os.path.join(local_model_path, model_file), 'wb') as file_obj: blob.download_to_file(file_obj) logging.info('Finished downloading blobs.') # load npy arrays for user/item factors and user/item maps self.user_factor = np.load(os.path.join(local_model_path, ROW_MODEL_FILE)) self.item_factor = np.load(os.path.join(local_model_path, COL_MODEL_FILE)) self.user_map = np.load(os.path.join(local_model_path, USER_MODEL_FILE)) self.item_map = np.load(os.path.join(local_model_path, ITEM_MODEL_FILE)) logging.info('Finished loading arrays.') # load user_item history into pandas dataframe views_df = pd.read_csv(os.path.join(local_model_path, USER_ITEM_DATA_FILE), sep=',', header=0) self.user_items = views_df.groupby('clientId') logging.info('Finished loading model.')
[ "def", "_load_model", "(", "self", ",", "local_model_path", ")", ":", "# download files from GCS to local storage", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "'model'", ")", ",", "exist_ok", "=", "True", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "'data'", ")", ",", "exist_ok", "=", "True", ")", "client", "=", "storage", ".", "Client", "(", ")", "bucket", "=", "client", ".", "get_bucket", "(", "self", ".", "_bucket", ")", "logging", ".", "info", "(", "'Downloading blobs.'", ")", "model_files", "=", "[", "ROW_MODEL_FILE", ",", "COL_MODEL_FILE", ",", "USER_MODEL_FILE", ",", "ITEM_MODEL_FILE", ",", "USER_ITEM_DATA_FILE", "]", "for", "model_file", "in", "model_files", ":", "blob", "=", "bucket", ".", "blob", "(", "model_file", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "model_file", ")", ",", "'wb'", ")", "as", "file_obj", ":", "blob", ".", "download_to_file", "(", "file_obj", ")", "logging", ".", "info", "(", "'Finished downloading blobs.'", ")", "# load npy arrays for user/item factors and user/item maps", "self", ".", "user_factor", "=", "np", ".", "load", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "ROW_MODEL_FILE", ")", ")", "self", ".", "item_factor", "=", "np", ".", "load", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "COL_MODEL_FILE", ")", ")", "self", ".", "user_map", "=", "np", ".", "load", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "USER_MODEL_FILE", ")", ")", "self", ".", "item_map", "=", "np", ".", "load", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "ITEM_MODEL_FILE", ")", ")", "logging", ".", "info", "(", "'Finished loading arrays.'", ")", "# load user_item history into pandas dataframe", "views_df", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "USER_ITEM_DATA_FILE", ")", ",", "sep", "=", "','", ",", "header", "=", "0", ")", "self", ".", "user_items", "=", "views_df", ".", "groupby", "(", "'clientId'", ")", "logging", ".", "info", "(", "'Finished loading model.'", ")" ]
[ 47, 2 ]
[ 83, 43 ]
python
en
['en', 'en', 'en']
True
Recommendations.get_recommendations
(self, user_id, num_recs)
Given a user id, return list of num_recs recommended item ids. Args: user_id: (string) The user id num_recs: (int) The number of recommended items to return Returns: [item_id_0, item_id_1, ... item_id_k-1]: The list of k recommended items, if user id is found. None: The user id was not found.
Given a user id, return list of num_recs recommended item ids.
def get_recommendations(self, user_id, num_recs): """Given a user id, return list of num_recs recommended item ids. Args: user_id: (string) The user id num_recs: (int) The number of recommended items to return Returns: [item_id_0, item_id_1, ... item_id_k-1]: The list of k recommended items, if user id is found. None: The user id was not found. """ article_recommendations = None # map user id into ratings matrix user index user_idx = np.searchsorted(self.user_map, user_id) if user_idx: # get already viewed items from views dataframe already_rated = self.user_items.get_group(user_id).contentId already_rated_idx = [np.searchsorted(self.item_map, i) for i in already_rated] # generate list of recommended article indexes from model recommendations = generate_recommendations(user_idx, already_rated_idx, self.user_factor, self.item_factor, num_recs) # map article indexes back to article ids article_recommendations = [self.item_map[i] for i in recommendations] return article_recommendations
[ "def", "get_recommendations", "(", "self", ",", "user_id", ",", "num_recs", ")", ":", "article_recommendations", "=", "None", "# map user id into ratings matrix user index", "user_idx", "=", "np", ".", "searchsorted", "(", "self", ".", "user_map", ",", "user_id", ")", "if", "user_idx", ":", "# get already viewed items from views dataframe", "already_rated", "=", "self", ".", "user_items", ".", "get_group", "(", "user_id", ")", ".", "contentId", "already_rated_idx", "=", "[", "np", ".", "searchsorted", "(", "self", ".", "item_map", ",", "i", ")", "for", "i", "in", "already_rated", "]", "# generate list of recommended article indexes from model", "recommendations", "=", "generate_recommendations", "(", "user_idx", ",", "already_rated_idx", ",", "self", ".", "user_factor", ",", "self", ".", "item_factor", ",", "num_recs", ")", "# map article indexes back to article ids", "article_recommendations", "=", "[", "self", ".", "item_map", "[", "i", "]", "for", "i", "in", "recommendations", "]", "return", "article_recommendations" ]
[ 85, 2 ]
[ 117, 34 ]
python
en
['en', 'en', 'en']
True
ResponsiveBreakpointsCache.__init__
(self, **cache_options)
Initialize the cache :param cache_options: Cache configuration options
Initialize the cache
def __init__(self, **cache_options): """ Initialize the cache :param cache_options: Cache configuration options """ self._cache_adapter = None cache_adapter = cache_options.get("cache_adapter") self.set_cache_adapter(cache_adapter)
[ "def", "__init__", "(", "self", ",", "*", "*", "cache_options", ")", ":", "self", ".", "_cache_adapter", "=", "None", "cache_adapter", "=", "cache_options", ".", "get", "(", "\"cache_adapter\"", ")", "self", ".", "set_cache_adapter", "(", "cache_adapter", ")" ]
[ 13, 4 ]
[ 24, 45 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.set_cache_adapter
(self, cache_adapter)
Assigns cache adapter :param cache_adapter: The cache adapter used to store and retrieve values :return: Returns True if the cache_adapter is valid
Assigns cache adapter
def set_cache_adapter(self, cache_adapter): """ Assigns cache adapter :param cache_adapter: The cache adapter used to store and retrieve values :return: Returns True if the cache_adapter is valid """ if cache_adapter is None or not isinstance(cache_adapter, CacheAdapter): return False self._cache_adapter = cache_adapter return True
[ "def", "set_cache_adapter", "(", "self", ",", "cache_adapter", ")", ":", "if", "cache_adapter", "is", "None", "or", "not", "isinstance", "(", "cache_adapter", ",", "CacheAdapter", ")", ":", "return", "False", "self", ".", "_cache_adapter", "=", "cache_adapter", "return", "True" ]
[ 26, 4 ]
[ 39, 19 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.enabled
(self)
Indicates whether cache is enabled or not :return: Rrue if a _cache_adapter has been set
Indicates whether cache is enabled or not
def enabled(self): """ Indicates whether cache is enabled or not :return: Rrue if a _cache_adapter has been set """ return self._cache_adapter is not None
[ "def", "enabled", "(", "self", ")", ":", "return", "self", ".", "_cache_adapter", "is", "not", "None" ]
[ 42, 4 ]
[ 48, 46 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache._options_to_parameters
(**options)
Extract the parameters required in order to calculate the key of the cache. :param options: Input options :return: A list of values used to calculate the cache key
Extract the parameters required in order to calculate the key of the cache.
def _options_to_parameters(**options): """ Extract the parameters required in order to calculate the key of the cache. :param options: Input options :return: A list of values used to calculate the cache key """ options_copy = copy.deepcopy(options) transformation, _ = cloudinary.utils.generate_transformation_string(**options_copy) file_format = options.get("format", "") storage_type = options.get("type", "upload") resource_type = options.get("resource_type", "image") return storage_type, resource_type, transformation, file_format
[ "def", "_options_to_parameters", "(", "*", "*", "options", ")", ":", "options_copy", "=", "copy", ".", "deepcopy", "(", "options", ")", "transformation", ",", "_", "=", "cloudinary", ".", "utils", ".", "generate_transformation_string", "(", "*", "*", "options_copy", ")", "file_format", "=", "options", ".", "get", "(", "\"format\"", ",", "\"\"", ")", "storage_type", "=", "options", ".", "get", "(", "\"type\"", ",", "\"upload\"", ")", "resource_type", "=", "options", ".", "get", "(", "\"resource_type\"", ",", "\"image\"", ")", "return", "storage_type", ",", "resource_type", ",", "transformation", ",", "file_format" ]
[ 51, 4 ]
[ 65, 71 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.get
(self, public_id, **options)
Retrieve the breakpoints of a particular derived resource identified by the public_id and options :param public_id: The public ID of the resource :param options: The public ID of the resource :return: Array of responsive breakpoints, None if not found
Retrieve the breakpoints of a particular derived resource identified by the public_id and options
def get(self, public_id, **options): """ Retrieve the breakpoints of a particular derived resource identified by the public_id and options :param public_id: The public ID of the resource :param options: The public ID of the resource :return: Array of responsive breakpoints, None if not found """ params = self._options_to_parameters(**options) return self._cache_adapter.get(public_id, *params)
[ "def", "get", "(", "self", ",", "public_id", ",", "*", "*", "options", ")", ":", "params", "=", "self", ".", "_options_to_parameters", "(", "*", "*", "options", ")", "return", "self", ".", "_cache_adapter", ".", "get", "(", "public_id", ",", "*", "params", ")" ]
[ 68, 4 ]
[ 79, 58 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.set
(self, public_id, value, **options)
Set responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param value: Array of responsive breakpoints to set :param options: Additional options :return: True on success or False on failure
Set responsive breakpoints identified by public ID and options
def set(self, public_id, value, **options): """ Set responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param value: Array of responsive breakpoints to set :param options: Additional options :return: True on success or False on failure """ if not (isinstance(value, (list, tuple))): raise ValueError("A list of breakpoints is expected") storage_type, resource_type, transformation, file_format = self._options_to_parameters(**options) return self._cache_adapter.set(public_id, storage_type, resource_type, transformation, file_format, value)
[ "def", "set", "(", "self", ",", "public_id", ",", "value", ",", "*", "*", "options", ")", ":", "if", "not", "(", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "raise", "ValueError", "(", "\"A list of breakpoints is expected\"", ")", "storage_type", ",", "resource_type", ",", "transformation", ",", "file_format", "=", "self", ".", "_options_to_parameters", "(", "*", "*", "options", ")", "return", "self", ".", "_cache_adapter", ".", "set", "(", "public_id", ",", "storage_type", ",", "resource_type", ",", "transformation", ",", "file_format", ",", "value", ")" ]
[ 82, 4 ]
[ 97, 114 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.delete
(self, public_id, **options)
Delete responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param options: Additional options :return: True on success or False on failure
Delete responsive breakpoints identified by public ID and options
def delete(self, public_id, **options): """ Delete responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param options: Additional options :return: True on success or False on failure """ params = self._options_to_parameters(**options) return self._cache_adapter.delete(public_id, *params)
[ "def", "delete", "(", "self", ",", "public_id", ",", "*", "*", "options", ")", ":", "params", "=", "self", ".", "_options_to_parameters", "(", "*", "*", "options", ")", "return", "self", ".", "_cache_adapter", ".", "delete", "(", "public_id", ",", "*", "params", ")" ]
[ 100, 4 ]
[ 111, 61 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.flush_all
(self)
Flush all entries from cache :return: True on success or False on failure
Flush all entries from cache
def flush_all(self): """ Flush all entries from cache :return: True on success or False on failure """ return self._cache_adapter.flush_all()
[ "def", "flush_all", "(", "self", ")", ":", "return", "self", ".", "_cache_adapter", ".", "flush_all", "(", ")" ]
[ 114, 4 ]
[ 120, 46 ]
python
en
['en', 'error', 'th']
False
AddDiskResourcesIfNeeded
(context)
Checks context if disk resources need to be added.
Checks context if disk resources need to be added.
def AddDiskResourcesIfNeeded(context): """Checks context if disk resources need to be added.""" if default.DISK_RESOURCES in context.properties: return context.properties[default.DISK_RESOURCES] else: return []
[ "def", "AddDiskResourcesIfNeeded", "(", "context", ")", ":", "if", "default", ".", "DISK_RESOURCES", "in", "context", ".", "properties", ":", "return", "context", ".", "properties", "[", "default", ".", "DISK_RESOURCES", "]", "else", ":", "return", "[", "]" ]
[ 30, 0 ]
[ 35, 13 ]
python
en
['en', 'en', 'en']
True
AutoName
(base, resource, *args)
Helper method to generate names automatically based on default.
Helper method to generate names automatically based on default.
def AutoName(base, resource, *args): """Helper method to generate names automatically based on default.""" auto_name = '%s-%s' % (base, '-'.join(list(args) + [default.AKA[resource]])) if not RFC1035_RE.match(auto_name): raise Error('"%s" name for type %s does not match RFC1035 regex (%s)' % (auto_name, resource, RFC1035_RE.pattern)) return auto_name
[ "def", "AutoName", "(", "base", ",", "resource", ",", "*", "args", ")", ":", "auto_name", "=", "'%s-%s'", "%", "(", "base", ",", "'-'", ".", "join", "(", "list", "(", "args", ")", "+", "[", "default", ".", "AKA", "[", "resource", "]", "]", ")", ")", "if", "not", "RFC1035_RE", ".", "match", "(", "auto_name", ")", ":", "raise", "Error", "(", "'\"%s\" name for type %s does not match RFC1035 regex (%s)'", "%", "(", "auto_name", ",", "resource", ",", "RFC1035_RE", ".", "pattern", ")", ")", "return", "auto_name" ]
[ 38, 0 ]
[ 44, 18 ]
python
en
['en', 'en', 'en']
True
AutoRef
(base, resource, *args)
Helper method that builds a reference for an auto-named resource.
Helper method that builds a reference for an auto-named resource.
def AutoRef(base, resource, *args): """Helper method that builds a reference for an auto-named resource.""" return Ref(AutoName(base, resource, *args))
[ "def", "AutoRef", "(", "base", ",", "resource", ",", "*", "args", ")", ":", "return", "Ref", "(", "AutoName", "(", "base", ",", "resource", ",", "*", "args", ")", ")" ]
[ 47, 0 ]
[ 49, 45 ]
python
en
['en', 'en', 'en']
True
OrderedItems
(dict_obj)
Convenient method to yield sorted iteritems of a dictionary.
Convenient method to yield sorted iteritems of a dictionary.
def OrderedItems(dict_obj): """Convenient method to yield sorted iteritems of a dictionary.""" keys = dict_obj.keys() keys.sort() for k in keys: yield (k, dict_obj[k])
[ "def", "OrderedItems", "(", "dict_obj", ")", ":", "keys", "=", "dict_obj", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "k", "in", "keys", ":", "yield", "(", "k", ",", "dict_obj", "[", "k", "]", ")" ]
[ 52, 0 ]
[ 57, 26 ]
python
en
['en', 'en', 'en']
True
ShortenZoneName
(zone)
Given a string that looks like a zone name, creates a shorter version.
Given a string that looks like a zone name, creates a shorter version.
def ShortenZoneName(zone): """Given a string that looks like a zone name, creates a shorter version.""" geo, coord, number, letter = re.findall(r'(\w+)-(\w+)(\d)-(\w)', zone)[0] geo = geo.lower() if len(geo) == 2 else default.LOC[geo.lower()] coord = default.LOC[coord.lower()] number = str(number) letter = letter.lower() return geo + '-' + coord + number + letter
[ "def", "ShortenZoneName", "(", "zone", ")", ":", "geo", ",", "coord", ",", "number", ",", "letter", "=", "re", ".", "findall", "(", "r'(\\w+)-(\\w+)(\\d)-(\\w)'", ",", "zone", ")", "[", "0", "]", "geo", "=", "geo", ".", "lower", "(", ")", "if", "len", "(", "geo", ")", "==", "2", "else", "default", ".", "LOC", "[", "geo", ".", "lower", "(", ")", "]", "coord", "=", "default", ".", "LOC", "[", "coord", ".", "lower", "(", ")", "]", "number", "=", "str", "(", "number", ")", "letter", "=", "letter", ".", "lower", "(", ")", "return", "geo", "+", "'-'", "+", "coord", "+", "number", "+", "letter" ]
[ 60, 0 ]
[ 67, 44 ]
python
en
['en', 'en', 'en']
True
ZoneToRegion
(zone)
Derives the region from a zone name.
Derives the region from a zone name.
def ZoneToRegion(zone): """Derives the region from a zone name.""" parts = zone.split('-') if len(parts) != 3: raise Error('Cannot derive region from zone "%s"' % zone) return '-'.join(parts[:2])
[ "def", "ZoneToRegion", "(", "zone", ")", ":", "parts", "=", "zone", ".", "split", "(", "'-'", ")", "if", "len", "(", "parts", ")", "!=", "3", ":", "raise", "Error", "(", "'Cannot derive region from zone \"%s\"'", "%", "zone", ")", "return", "'-'", ".", "join", "(", "parts", "[", ":", "2", "]", ")" ]
[ 70, 0 ]
[ 75, 28 ]
python
en
['en', 'en', 'en']
True
FormatException
(message)
Adds more information to the exception.
Adds more information to the exception.
def FormatException(message): """Adds more information to the exception.""" message = ('Exception Type: %s\n' 'Details: %s\n' 'Message: %s\n') % (sys.exc_type, traceback.format_exc(), message) return message
[ "def", "FormatException", "(", "message", ")", ":", "message", "=", "(", "'Exception Type: %s\\n'", "'Details: %s\\n'", "'Message: %s\\n'", ")", "%", "(", "sys", ".", "exc_type", ",", "traceback", ".", "format_exc", "(", ")", ",", "message", ")", "return", "message" ]
[ 78, 0 ]
[ 83, 16 ]
python
en
['en', 'en', 'en']
True
SummarizeResources
(res_dict)
Summarizes the name of resources per resource type.
Summarizes the name of resources per resource type.
def SummarizeResources(res_dict): """Summarizes the name of resources per resource type.""" result = {} for res in res_dict: result.setdefault(res['type'], []).append(res['name']) return result
[ "def", "SummarizeResources", "(", "res_dict", ")", ":", "result", "=", "{", "}", "for", "res", "in", "res_dict", ":", "result", ".", "setdefault", "(", "res", "[", "'type'", "]", ",", "[", "]", ")", ".", "append", "(", "res", "[", "'name'", "]", ")", "return", "result" ]
[ 160, 0 ]
[ 165, 15 ]
python
en
['en', 'en', 'en']
True
ListPropertyValuesOfType
(res_dict, prop, res_type)
Lists all the values for a property of a certain type.
Lists all the values for a property of a certain type.
def ListPropertyValuesOfType(res_dict, prop, res_type): """Lists all the values for a property of a certain type.""" return [r['properties'][prop] for r in res_dict if r['type'] == res_type]
[ "def", "ListPropertyValuesOfType", "(", "res_dict", ",", "prop", ",", "res_type", ")", ":", "return", "[", "r", "[", "'properties'", "]", "[", "prop", "]", "for", "r", "in", "res_dict", "if", "r", "[", "'type'", "]", "==", "res_type", "]" ]
[ 168, 0 ]
[ 170, 75 ]
python
en
['en', 'en', 'en']
True
MakeResource
(resource_list, output_list=None)
Wrapper for a DM template basic spec.
Wrapper for a DM template basic spec.
def MakeResource(resource_list, output_list=None): """Wrapper for a DM template basic spec.""" content = {'resources': resource_list} if output_list: content['outputs'] = output_list return yaml.dump(content)
[ "def", "MakeResource", "(", "resource_list", ",", "output_list", "=", "None", ")", ":", "content", "=", "{", "'resources'", ":", "resource_list", "}", "if", "output_list", ":", "content", "[", "'outputs'", "]", "=", "output_list", "return", "yaml", ".", "dump", "(", "content", ")" ]
[ 173, 0 ]
[ 178, 27 ]
python
en
['en', 'en', 'en']
True
TakeZoneOut
(properties)
Given a properties dictionary, removes the zone specific information.
Given a properties dictionary, removes the zone specific information.
def TakeZoneOut(properties): """Given a properties dictionary, removes the zone specific information.""" def _CleanZoneUrl(value): value = value.split('/')[-1] if IsComputeLink(value) else value return value for name in default.VM_ZONE_PROPERTIES: if name in properties: properties[name] = _CleanZoneUrl(properties[name]) if default.ZONE in properties: properties.pop(default.ZONE) if default.BOOTDISK in properties: properties[default.BOOTDISK] = _CleanZoneUrl(properties[default.BOOTDISK]) if default.DISKS in properties: for disk in properties[default.DISKS]: # Don't touch references to other disks if default.DISK_SOURCE in disk: continue if default.INITIALIZEP in disk: disk_init = disk[default.INITIALIZEP] if default.DISKTYPE in disk_init: disk_init[default.DISKTYPE] = _CleanZoneUrl(disk_init[default.DISKTYPE])
[ "def", "TakeZoneOut", "(", "properties", ")", ":", "def", "_CleanZoneUrl", "(", "value", ")", ":", "value", "=", "value", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "IsComputeLink", "(", "value", ")", "else", "value", "return", "value", "for", "name", "in", "default", ".", "VM_ZONE_PROPERTIES", ":", "if", "name", "in", "properties", ":", "properties", "[", "name", "]", "=", "_CleanZoneUrl", "(", "properties", "[", "name", "]", ")", "if", "default", ".", "ZONE", "in", "properties", ":", "properties", ".", "pop", "(", "default", ".", "ZONE", ")", "if", "default", ".", "BOOTDISK", "in", "properties", ":", "properties", "[", "default", ".", "BOOTDISK", "]", "=", "_CleanZoneUrl", "(", "properties", "[", "default", ".", "BOOTDISK", "]", ")", "if", "default", ".", "DISKS", "in", "properties", ":", "for", "disk", "in", "properties", "[", "default", ".", "DISKS", "]", ":", "# Don't touch references to other disks", "if", "default", ".", "DISK_SOURCE", "in", "disk", ":", "continue", "if", "default", ".", "INITIALIZEP", "in", "disk", ":", "disk_init", "=", "disk", "[", "default", ".", "INITIALIZEP", "]", "if", "default", ".", "DISKTYPE", "in", "disk_init", ":", "disk_init", "[", "default", ".", "DISKTYPE", "]", "=", "_CleanZoneUrl", "(", "disk_init", "[", "default", ".", "DISKTYPE", "]", ")" ]
[ 181, 0 ]
[ 203, 80 ]
python
en
['en', 'en', 'en']
True
FormatErrorsDec
(func)
Decorator to format exceptions if they get raised.
Decorator to format exceptions if they get raised.
def FormatErrorsDec(func): """Decorator to format exceptions if they get raised.""" def FormatErrorsWrap(context): try: return func(context) except Exception as e: raise Error(FormatException(e.message)) return FormatErrorsWrap
[ "def", "FormatErrorsDec", "(", "func", ")", ":", "def", "FormatErrorsWrap", "(", "context", ")", ":", "try", ":", "return", "func", "(", "context", ")", "except", "Exception", "as", "e", ":", "raise", "Error", "(", "FormatException", "(", "e", ".", "message", ")", ")", "return", "FormatErrorsWrap" ]
[ 218, 0 ]
[ 227, 25 ]
python
en
['en', 'en', 'en']
True
ModelBackend.user_can_authenticate
(self, user)
Reject users with is_active=False. Custom user models that don't have that attribute are allowed.
Reject users with is_active=False. Custom user models that don't have that attribute are allowed.
def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ is_active = getattr(user, 'is_active', None) return is_active or is_active is None
[ "def", "user_can_authenticate", "(", "self", ",", "user", ")", ":", "is_active", "=", "getattr", "(", "user", ",", "'is_active'", ",", "None", ")", "return", "is_active", "or", "is_active", "is", "None" ]
[ 50, 4 ]
[ 56, 45 ]
python
en
['en', 'error', 'th']
False
ModelBackend._get_permissions
(self, user_obj, obj, from_name)
Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively.
Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively.
def _get_permissions(self, user_obj, obj, from_name): """ Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively. """ if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() perm_cache_name = '_%s_perm_cache' % from_name if not hasattr(user_obj, perm_cache_name): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj) perms = perms.values_list('content_type__app_label', 'codename').order_by() setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms}) return getattr(user_obj, perm_cache_name)
[ "def", "_get_permissions", "(", "self", ",", "user_obj", ",", "obj", ",", "from_name", ")", ":", "if", "not", "user_obj", ".", "is_active", "or", "user_obj", ".", "is_anonymous", "or", "obj", "is", "not", "None", ":", "return", "set", "(", ")", "perm_cache_name", "=", "'_%s_perm_cache'", "%", "from_name", "if", "not", "hasattr", "(", "user_obj", ",", "perm_cache_name", ")", ":", "if", "user_obj", ".", "is_superuser", ":", "perms", "=", "Permission", ".", "objects", ".", "all", "(", ")", "else", ":", "perms", "=", "getattr", "(", "self", ",", "'_get_%s_permissions'", "%", "from_name", ")", "(", "user_obj", ")", "perms", "=", "perms", ".", "values_list", "(", "'content_type__app_label'", ",", "'codename'", ")", ".", "order_by", "(", ")", "setattr", "(", "user_obj", ",", "perm_cache_name", ",", "{", "\"%s.%s\"", "%", "(", "ct", ",", "name", ")", "for", "ct", ",", "name", "in", "perms", "}", ")", "return", "getattr", "(", "user_obj", ",", "perm_cache_name", ")" ]
[ 66, 4 ]
[ 83, 49 ]
python
en
['en', 'error', 'th']
False
ModelBackend.get_user_permissions
(self, user_obj, obj=None)
Return a set of permission strings the user `user_obj` has from their `user_permissions`.
Return a set of permission strings the user `user_obj` has from their `user_permissions`.
def get_user_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from their `user_permissions`. """ return self._get_permissions(user_obj, obj, 'user')
[ "def", "get_user_permissions", "(", "self", ",", "user_obj", ",", "obj", "=", "None", ")", ":", "return", "self", ".", "_get_permissions", "(", "user_obj", ",", "obj", ",", "'user'", ")" ]
[ 85, 4 ]
[ 90, 59 ]
python
en
['en', 'error', 'th']
False
ModelBackend.get_group_permissions
(self, user_obj, obj=None)
Return a set of permission strings the user `user_obj` has from the groups they belong.
Return a set of permission strings the user `user_obj` has from the groups they belong.
def get_group_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from the groups they belong. """ return self._get_permissions(user_obj, obj, 'group')
[ "def", "get_group_permissions", "(", "self", ",", "user_obj", ",", "obj", "=", "None", ")", ":", "return", "self", ".", "_get_permissions", "(", "user_obj", ",", "obj", ",", "'group'", ")" ]
[ 92, 4 ]
[ 97, 60 ]
python
en
['en', 'error', 'th']
False
ModelBackend.has_module_perms
(self, user_obj, app_label)
Return True if user_obj has any permissions in the given app_label.
Return True if user_obj has any permissions in the given app_label.
def has_module_perms(self, user_obj, app_label): """ Return True if user_obj has any permissions in the given app_label. """ return user_obj.is_active and any( perm[:perm.index('.')] == app_label for perm in self.get_all_permissions(user_obj) )
[ "def", "has_module_perms", "(", "self", ",", "user_obj", ",", "app_label", ")", ":", "return", "user_obj", ".", "is_active", "and", "any", "(", "perm", "[", ":", "perm", ".", "index", "(", "'.'", ")", "]", "==", "app_label", "for", "perm", "in", "self", ".", "get_all_permissions", "(", "user_obj", ")", ")" ]
[ 109, 4 ]
[ 116, 9 ]
python
en
['en', 'error', 'th']
False
ModelBackend.with_perm
(self, perm, is_active=True, include_superusers=True, obj=None)
Return users that have permission "perm". By default, filter out inactive users and include superusers.
Return users that have permission "perm". By default, filter out inactive users and include superusers.
def with_perm(self, perm, is_active=True, include_superusers=True, obj=None): """ Return users that have permission "perm". By default, filter out inactive users and include superusers. """ if isinstance(perm, str): try: app_label, codename = perm.split('.') except ValueError: raise ValueError( 'Permission name should be in the form ' 'app_label.permission_codename.' ) elif not isinstance(perm, Permission): raise TypeError( 'The `perm` argument must be a string or a permission instance.' ) UserModel = get_user_model() if obj is not None: return UserModel._default_manager.none() permission_q = Q(group__user=OuterRef('pk')) | Q(user=OuterRef('pk')) if isinstance(perm, Permission): permission_q &= Q(pk=perm.pk) else: permission_q &= Q(codename=codename, content_type__app_label=app_label) user_q = Exists(Permission.objects.filter(permission_q)) if include_superusers: user_q |= Q(is_superuser=True) if is_active is not None: user_q &= Q(is_active=is_active) return UserModel._default_manager.filter(user_q)
[ "def", "with_perm", "(", "self", ",", "perm", ",", "is_active", "=", "True", ",", "include_superusers", "=", "True", ",", "obj", "=", "None", ")", ":", "if", "isinstance", "(", "perm", ",", "str", ")", ":", "try", ":", "app_label", ",", "codename", "=", "perm", ".", "split", "(", "'.'", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Permission name should be in the form '", "'app_label.permission_codename.'", ")", "elif", "not", "isinstance", "(", "perm", ",", "Permission", ")", ":", "raise", "TypeError", "(", "'The `perm` argument must be a string or a permission instance.'", ")", "UserModel", "=", "get_user_model", "(", ")", "if", "obj", "is", "not", "None", ":", "return", "UserModel", ".", "_default_manager", ".", "none", "(", ")", "permission_q", "=", "Q", "(", "group__user", "=", "OuterRef", "(", "'pk'", ")", ")", "|", "Q", "(", "user", "=", "OuterRef", "(", "'pk'", ")", ")", "if", "isinstance", "(", "perm", ",", "Permission", ")", ":", "permission_q", "&=", "Q", "(", "pk", "=", "perm", ".", "pk", ")", "else", ":", "permission_q", "&=", "Q", "(", "codename", "=", "codename", ",", "content_type__app_label", "=", "app_label", ")", "user_q", "=", "Exists", "(", "Permission", ".", "objects", ".", "filter", "(", "permission_q", ")", ")", "if", "include_superusers", ":", "user_q", "|=", "Q", "(", "is_superuser", "=", "True", ")", "if", "is_active", "is", "not", "None", ":", "user_q", "&=", "Q", "(", "is_active", "=", "is_active", ")", "return", "UserModel", ".", "_default_manager", ".", "filter", "(", "user_q", ")" ]
[ 118, 4 ]
[ 152, 56 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.authenticate
(self, request, remote_user)
The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found in the database.
The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``.
def authenticate(self, request, remote_user): """ The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found in the database. """ if not remote_user: return user = None username = self.clean_username(remote_user) # Note that this could be accomplished in one try-except clause, but # instead we use get_or_create when creating unknown users since it has # built-in safeguards for multiple threads. if self.create_unknown_user: user, created = UserModel._default_manager.get_or_create(**{ UserModel.USERNAME_FIELD: username }) if created: user = self.configure_user(request, user) else: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: pass return user if self.user_can_authenticate(user) else None
[ "def", "authenticate", "(", "self", ",", "request", ",", "remote_user", ")", ":", "if", "not", "remote_user", ":", "return", "user", "=", "None", "username", "=", "self", ".", "clean_username", "(", "remote_user", ")", "# Note that this could be accomplished in one try-except clause, but", "# instead we use get_or_create when creating unknown users since it has", "# built-in safeguards for multiple threads.", "if", "self", ".", "create_unknown_user", ":", "user", ",", "created", "=", "UserModel", ".", "_default_manager", ".", "get_or_create", "(", "*", "*", "{", "UserModel", ".", "USERNAME_FIELD", ":", "username", "}", ")", "if", "created", ":", "user", "=", "self", ".", "configure_user", "(", "request", ",", "user", ")", "else", ":", "try", ":", "user", "=", "UserModel", ".", "_default_manager", ".", "get_by_natural_key", "(", "username", ")", "except", "UserModel", ".", "DoesNotExist", ":", "pass", "return", "user", "if", "self", ".", "user_can_authenticate", "(", "user", ")", "else", "None" ]
[ 182, 4 ]
[ 210, 65 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.clean_username
(self, username)
Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged.
Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username.
def clean_username(self, username): """ Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged. """ return username
[ "def", "clean_username", "(", "self", ",", "username", ")", ":", "return", "username" ]
[ 212, 4 ]
[ 219, 23 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.configure_user
(self, request, user)
Configure a user after creation and return the updated user. By default, return the user unmodified.
Configure a user after creation and return the updated user.
def configure_user(self, request, user): """ Configure a user after creation and return the updated user. By default, return the user unmodified. """ return user
[ "def", "configure_user", "(", "self", ",", "request", ",", "user", ")", ":", "return", "user" ]
[ 221, 4 ]
[ 227, 19 ]
python
en
['en', 'error', 'th']
False
dollars_to_math
(source)
r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like "``$HOME``". Don't make any changes on lines starting with spaces, because those are indented and hence part of a block of code or examples. This also doesn't replaces dollar signs enclosed in curly braces, to avoid nested math environments, such as :: $f(n) = 0 \text{ if $n$ is prime}$ Thus the above line would get changed to `f(n) = 0 \text{ if $n$ is prime}`
r""" Replace dollar signs with backticks.
def dollars_to_math(source): r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like "``$HOME``". Don't make any changes on lines starting with spaces, because those are indented and hence part of a block of code or examples. This also doesn't replaces dollar signs enclosed in curly braces, to avoid nested math environments, such as :: $f(n) = 0 \text{ if $n$ is prime}$ Thus the above line would get changed to `f(n) = 0 \text{ if $n$ is prime}` """ s = "\n".join(source) if s.find("$") == -1: return # This searches for "$blah$" inside a pair of curly braces -- # don't change these, since they're probably coming from a nested # math environment. So for each match, we replace it with a temporary # string, and later on we substitute the original back. global _data _data = {} def repl(matchobj): global _data s = matchobj.group(0) t = "___XXX_REPL_%d___" % len(_data) _data[t] = s return t s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s) # matches $...$ dollars = re.compile(r"(?<!\$)(?<!\\)\$([^\$]+?)\$") # regular expression for \$ slashdollar = re.compile(r"\\\$") s = dollars.sub(r":math:`\1`", s) s = slashdollar.sub(r"$", s) # change the original {...} things in: for r in _data: s = s.replace(r, _data[r]) # now save results in "source" source[:] = [s]
[ "def", "dollars_to_math", "(", "source", ")", ":", "s", "=", "\"\\n\"", ".", "join", "(", "source", ")", "if", "s", ".", "find", "(", "\"$\"", ")", "==", "-", "1", ":", "return", "# This searches for \"$blah$\" inside a pair of curly braces --", "# don't change these, since they're probably coming from a nested", "# math environment. So for each match, we replace it with a temporary", "# string, and later on we substitute the original back.", "global", "_data", "_data", "=", "{", "}", "def", "repl", "(", "matchobj", ")", ":", "global", "_data", "s", "=", "matchobj", ".", "group", "(", "0", ")", "t", "=", "\"___XXX_REPL_%d___\"", "%", "len", "(", "_data", ")", "_data", "[", "t", "]", "=", "s", "return", "t", "s", "=", "re", ".", "sub", "(", "r\"({[^{}$]*\\$[^{}$]*\\$[^{}]*})\"", ",", "repl", ",", "s", ")", "# matches $...$", "dollars", "=", "re", ".", "compile", "(", "r\"(?<!\\$)(?<!\\\\)\\$([^\\$]+?)\\$\"", ")", "# regular expression for \\$", "slashdollar", "=", "re", ".", "compile", "(", "r\"\\\\\\$\"", ")", "s", "=", "dollars", ".", "sub", "(", "r\":math:`\\1`\"", ",", "s", ")", "s", "=", "slashdollar", ".", "sub", "(", "r\"$\"", ",", "s", ")", "# change the original {...} things in:", "for", "r", "in", "_data", ":", "s", "=", "s", ".", "replace", "(", "r", ",", "_data", "[", "r", "]", ")", "# now save results in \"source\"", "source", "[", ":", "]", "=", "[", "s", "]" ]
[ 2, 0 ]
[ 49, 19 ]
python
cy
['en', 'cy', 'hi']
False
LayerMapping.__init__
(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None)
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None): """ A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage. """ # Getting the DataSource and the associated Layer. if isinstance(data, (str, Path)): self.ds = DataSource(data, encoding=encoding) else: self.ds = data self.layer = self.ds[layer] self.using = using if using is not None else router.db_for_write(model) self.spatial_backend = connections[self.using].ops # Setting the mapping & model attributes. self.mapping = mapping self.model = model # Checking the layer -- initialization of the object will fail if # things don't check out before hand. self.check_layer() # Getting the geometry column associated with the model (an # exception will be raised if there is no geometry column). if connections[self.using].features.supports_transform: self.geo_field = self.geometry_field() else: transform = False # Checking the source spatial reference system, and getting # the coordinate transformation object (unless the `transform` # keyword is set to False) if transform: self.source_srs = self.check_srs(source_srs) self.transform = self.coord_transform() else: self.transform = transform # Setting the encoding for OFTString fields, if specified. if encoding: # Making sure the encoding exists, if not a LookupError # exception will be thrown. from codecs import lookup lookup(encoding) self.encoding = encoding else: self.encoding = None if unique: self.check_unique(unique) transaction_mode = 'autocommit' # Has to be set to autocommit. self.unique = unique else: self.unique = None # Setting the transaction decorator with the function in the # transaction modes dictionary. self.transaction_mode = transaction_mode if transaction_mode == 'autocommit': self.transaction_decorator = None elif transaction_mode == 'commit_on_success': self.transaction_decorator = transaction.atomic else: raise LayerMapError('Unrecognized transaction mode: %s' % transaction_mode)
[ "def", "__init__", "(", "self", ",", "model", ",", "data", ",", "mapping", ",", "layer", "=", "0", ",", "source_srs", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "transaction_mode", "=", "'commit_on_success'", ",", "transform", "=", "True", ",", "unique", "=", "None", ",", "using", "=", "None", ")", ":", "# Getting the DataSource and the associated Layer.", "if", "isinstance", "(", "data", ",", "(", "str", ",", "Path", ")", ")", ":", "self", ".", "ds", "=", "DataSource", "(", "data", ",", "encoding", "=", "encoding", ")", "else", ":", "self", ".", "ds", "=", "data", "self", ".", "layer", "=", "self", ".", "ds", "[", "layer", "]", "self", ".", "using", "=", "using", "if", "using", "is", "not", "None", "else", "router", ".", "db_for_write", "(", "model", ")", "self", ".", "spatial_backend", "=", "connections", "[", "self", ".", "using", "]", ".", "ops", "# Setting the mapping & model attributes.", "self", ".", "mapping", "=", "mapping", "self", ".", "model", "=", "model", "# Checking the layer -- initialization of the object will fail if", "# things don't check out before hand.", "self", ".", "check_layer", "(", ")", "# Getting the geometry column associated with the model (an", "# exception will be raised if there is no geometry column).", "if", "connections", "[", "self", ".", "using", "]", ".", "features", ".", "supports_transform", ":", "self", ".", "geo_field", "=", "self", ".", "geometry_field", "(", ")", "else", ":", "transform", "=", "False", "# Checking the source spatial reference system, and getting", "# the coordinate transformation object (unless the `transform`", "# keyword is set to False)", "if", "transform", ":", "self", ".", "source_srs", "=", "self", ".", "check_srs", "(", "source_srs", ")", "self", ".", "transform", "=", "self", ".", "coord_transform", "(", ")", "else", ":", "self", ".", "transform", "=", "transform", "# Setting the encoding for OFTString fields, if specified.", "if", "encoding", ":", "# Making sure the encoding exists, if not a LookupError", "# exception will be thrown.", "from", "codecs", "import", "lookup", "lookup", "(", "encoding", ")", "self", ".", "encoding", "=", "encoding", "else", ":", "self", ".", "encoding", "=", "None", "if", "unique", ":", "self", ".", "check_unique", "(", "unique", ")", "transaction_mode", "=", "'autocommit'", "# Has to be set to autocommit.", "self", ".", "unique", "=", "unique", "else", ":", "self", ".", "unique", "=", "None", "# Setting the transaction decorator with the function in the", "# transaction modes dictionary.", "self", ".", "transaction_mode", "=", "transaction_mode", "if", "transaction_mode", "==", "'autocommit'", ":", "self", ".", "transaction_decorator", "=", "None", "elif", "transaction_mode", "==", "'commit_on_success'", ":", "self", ".", "transaction_decorator", "=", "transaction", ".", "atomic", "else", ":", "raise", "LayerMapError", "(", "'Unrecognized transaction mode: %s'", "%", "transaction_mode", ")" ]
[ 85, 4 ]
[ 154, 87 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_fid_range
(self, fid_range)
Check the `fid_range` keyword.
Check the `fid_range` keyword.
def check_fid_range(self, fid_range): "Check the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeError else: return None
[ "def", "check_fid_range", "(", "self", ",", "fid_range", ")", ":", "if", "fid_range", ":", "if", "isinstance", "(", "fid_range", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "slice", "(", "*", "fid_range", ")", "elif", "isinstance", "(", "fid_range", ",", "slice", ")", ":", "return", "fid_range", "else", ":", "raise", "TypeError", "else", ":", "return", "None" ]
[ 157, 4 ]
[ 167, 23 ]
python
en
['en', 'hmn', 'en']
True
LayerMapping.check_layer
(self)
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
def check_layer(self): """ Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. # TODO: Support more than one geometry field / model. However, this # depends on the GDAL Driver in use. self.geom_field = False self.fields = {} # Getting lists of the field names and the field types available in # the OGR Layer. ogr_fields = self.layer.fields ogr_field_types = self.layer.field_types # Function for determining if the OGR mapping field is in the Layer. def check_ogr_fld(ogr_map_fld): try: idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld) return idx # No need to increment through each feature in the model, simply check # the Layer metadata against what was given in the mapping dictionary. for field_name, ogr_name in self.mapping.items(): # Ensuring that a corresponding field exists in the model # for the given field name in the mapping. try: model_field = self.model._meta.get_field(field_name) except FieldDoesNotExist: raise LayerMapError('Given mapping field "%s" not in given Model fields.' % field_name) # Getting the string name for the Django field class (e.g., 'PointField'). fld_name = model_field.__class__.__name__ if isinstance(model_field, GeometryField): if self.geom_field: raise LayerMapError('LayerMapping does not support more than one GeometryField per model.') # Getting the coordinate dimension of the geometry field. coord_dim = model_field.dim try: if coord_dim == 3: gtype = OGRGeomType(ogr_name + '25D') else: gtype = OGRGeomType(ogr_name) except GDALException: raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name) # Making sure that the OGR Layer's Geometry is compatible. ltype = self.layer.geom_type if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)): raise LayerMapError('Invalid mapping geometry; model has %s%s, ' 'layer geometry type is %s.' % (fld_name, '(dim=3)' if coord_dim == 3 else '', ltype)) # Setting the `geom_field` attribute w/the name of the model field # that is a Geometry. Also setting the coordinate dimension # attribute. self.geom_field = field_name self.coord_dim = coord_dim fields_val = model_field elif isinstance(model_field, models.ForeignKey): if isinstance(ogr_name, dict): # Is every given related model mapping field in the Layer? rel_model = model_field.remote_field.model for rel_name, ogr_field in ogr_name.items(): idx = check_ogr_fld(ogr_field) try: rel_model._meta.get_field(rel_name) except FieldDoesNotExist: raise LayerMapError('ForeignKey mapping field "%s" not in %s fields.' % (rel_name, rel_model.__class__.__name__)) fields_val = rel_model else: raise TypeError('ForeignKey mapping must be of dictionary type.') else: # Is the model field type supported by LayerMapping? if model_field.__class__ not in self.FIELD_TYPES: raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name) # Is the OGR field in the Layer? idx = check_ogr_fld(ogr_name) ogr_field = ogr_field_types[idx] # Can the OGR field type be mapped to the Django field type? if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]): raise LayerMapError('OGR field "%s" (of type %s) cannot be mapped to Django %s.' % (ogr_field, ogr_field.__name__, fld_name)) fields_val = model_field self.fields[field_name] = fields_val
[ "def", "check_layer", "(", "self", ")", ":", "# The geometry field of the model is set here.", "# TODO: Support more than one geometry field / model. However, this", "# depends on the GDAL Driver in use.", "self", ".", "geom_field", "=", "False", "self", ".", "fields", "=", "{", "}", "# Getting lists of the field names and the field types available in", "# the OGR Layer.", "ogr_fields", "=", "self", ".", "layer", ".", "fields", "ogr_field_types", "=", "self", ".", "layer", ".", "field_types", "# Function for determining if the OGR mapping field is in the Layer.", "def", "check_ogr_fld", "(", "ogr_map_fld", ")", ":", "try", ":", "idx", "=", "ogr_fields", ".", "index", "(", "ogr_map_fld", ")", "except", "ValueError", ":", "raise", "LayerMapError", "(", "'Given mapping OGR field \"%s\" not found in OGR Layer.'", "%", "ogr_map_fld", ")", "return", "idx", "# No need to increment through each feature in the model, simply check", "# the Layer metadata against what was given in the mapping dictionary.", "for", "field_name", ",", "ogr_name", "in", "self", ".", "mapping", ".", "items", "(", ")", ":", "# Ensuring that a corresponding field exists in the model", "# for the given field name in the mapping.", "try", ":", "model_field", "=", "self", ".", "model", ".", "_meta", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "raise", "LayerMapError", "(", "'Given mapping field \"%s\" not in given Model fields.'", "%", "field_name", ")", "# Getting the string name for the Django field class (e.g., 'PointField').", "fld_name", "=", "model_field", ".", "__class__", ".", "__name__", "if", "isinstance", "(", "model_field", ",", "GeometryField", ")", ":", "if", "self", ".", "geom_field", ":", "raise", "LayerMapError", "(", "'LayerMapping does not support more than one GeometryField per model.'", ")", "# Getting the coordinate dimension of the geometry field.", "coord_dim", "=", "model_field", ".", "dim", "try", ":", "if", "coord_dim", "==", "3", ":", "gtype", "=", "OGRGeomType", "(", "ogr_name", "+", "'25D'", ")", "else", ":", "gtype", "=", "OGRGeomType", "(", "ogr_name", ")", "except", "GDALException", ":", "raise", "LayerMapError", "(", "'Invalid mapping for GeometryField \"%s\".'", "%", "field_name", ")", "# Making sure that the OGR Layer's Geometry is compatible.", "ltype", "=", "self", ".", "layer", ".", "geom_type", "if", "not", "(", "ltype", ".", "name", ".", "startswith", "(", "gtype", ".", "name", ")", "or", "self", ".", "make_multi", "(", "ltype", ",", "model_field", ")", ")", ":", "raise", "LayerMapError", "(", "'Invalid mapping geometry; model has %s%s, '", "'layer geometry type is %s.'", "%", "(", "fld_name", ",", "'(dim=3)'", "if", "coord_dim", "==", "3", "else", "''", ",", "ltype", ")", ")", "# Setting the `geom_field` attribute w/the name of the model field", "# that is a Geometry. Also setting the coordinate dimension", "# attribute.", "self", ".", "geom_field", "=", "field_name", "self", ".", "coord_dim", "=", "coord_dim", "fields_val", "=", "model_field", "elif", "isinstance", "(", "model_field", ",", "models", ".", "ForeignKey", ")", ":", "if", "isinstance", "(", "ogr_name", ",", "dict", ")", ":", "# Is every given related model mapping field in the Layer?", "rel_model", "=", "model_field", ".", "remote_field", ".", "model", "for", "rel_name", ",", "ogr_field", "in", "ogr_name", ".", "items", "(", ")", ":", "idx", "=", "check_ogr_fld", "(", "ogr_field", ")", "try", ":", "rel_model", ".", "_meta", ".", "get_field", "(", "rel_name", ")", "except", "FieldDoesNotExist", ":", "raise", "LayerMapError", "(", "'ForeignKey mapping field \"%s\" not in %s fields.'", "%", "(", "rel_name", ",", "rel_model", ".", "__class__", ".", "__name__", ")", ")", "fields_val", "=", "rel_model", "else", ":", "raise", "TypeError", "(", "'ForeignKey mapping must be of dictionary type.'", ")", "else", ":", "# Is the model field type supported by LayerMapping?", "if", "model_field", ".", "__class__", "not", "in", "self", ".", "FIELD_TYPES", ":", "raise", "LayerMapError", "(", "'Django field type \"%s\" has no OGR mapping (yet).'", "%", "fld_name", ")", "# Is the OGR field in the Layer?", "idx", "=", "check_ogr_fld", "(", "ogr_name", ")", "ogr_field", "=", "ogr_field_types", "[", "idx", "]", "# Can the OGR field type be mapped to the Django field type?", "if", "not", "issubclass", "(", "ogr_field", ",", "self", ".", "FIELD_TYPES", "[", "model_field", ".", "__class__", "]", ")", ":", "raise", "LayerMapError", "(", "'OGR field \"%s\" (of type %s) cannot be mapped to Django %s.'", "%", "(", "ogr_field", ",", "ogr_field", ".", "__name__", ",", "fld_name", ")", ")", "fields_val", "=", "model_field", "self", ".", "fields", "[", "field_name", "]", "=", "fields_val" ]
[ 169, 4 ]
[ 264, 48 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_srs
(self, source_srs)
Check the compatibility of the given spatial reference object.
Check the compatibility of the given spatial reference object.
def check_srs(self, source_srs): "Check the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance(source_srs, (int, str)): sr = SpatialReference(source_srs) else: # Otherwise just pulling the SpatialReference from the layer sr = self.layer.srs if not sr: raise LayerMapError('No source reference system defined.') else: return sr
[ "def", "check_srs", "(", "self", ",", "source_srs", ")", ":", "if", "isinstance", "(", "source_srs", ",", "SpatialReference", ")", ":", "sr", "=", "source_srs", "elif", "isinstance", "(", "source_srs", ",", "self", ".", "spatial_backend", ".", "spatial_ref_sys", "(", ")", ")", ":", "sr", "=", "source_srs", ".", "srs", "elif", "isinstance", "(", "source_srs", ",", "(", "int", ",", "str", ")", ")", ":", "sr", "=", "SpatialReference", "(", "source_srs", ")", "else", ":", "# Otherwise just pulling the SpatialReference from the layer", "sr", "=", "self", ".", "layer", ".", "srs", "if", "not", "sr", ":", "raise", "LayerMapError", "(", "'No source reference system defined.'", ")", "else", ":", "return", "sr" ]
[ 266, 4 ]
[ 282, 21 ]
python
en
['en', 'en', 'en']
True
LayerMapping.check_unique
(self, unique)
Check the `unique` keyword parameter -- may be a sequence or string.
Check the `unique` keyword parameter -- may be a sequence or string.
def check_unique(self, unique): "Check the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise ValueError elif isinstance(unique, str): # Only a single field passed in. if unique not in self.mapping: raise ValueError else: raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
[ "def", "check_unique", "(", "self", ",", "unique", ")", ":", "if", "isinstance", "(", "unique", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List of fields to determine uniqueness with", "for", "attr", "in", "unique", ":", "if", "attr", "not", "in", "self", ".", "mapping", ":", "raise", "ValueError", "elif", "isinstance", "(", "unique", ",", "str", ")", ":", "# Only a single field passed in.", "if", "unique", "not", "in", "self", ".", "mapping", ":", "raise", "ValueError", "else", ":", "raise", "TypeError", "(", "'Unique keyword argument must be set with a tuple, list, or string.'", ")" ]
[ 284, 4 ]
[ 296, 97 ]
python
en
['en', 'en', 'en']
True
LayerMapping.feature_kwargs
(self, feat)
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
def feature_kwargs(self, feat): """ Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the # dictionary mapping. for field_name, ogr_name in self.mapping.items(): model_field = self.fields[field_name] if isinstance(model_field, GeometryField): # Verify OGR geometry. try: val = self.verify_geom(feat.geom, model_field) except GDALException: raise LayerMapError('Could not retrieve geometry from feature.') elif isinstance(model_field, models.base.ModelBase): # The related _model_, not a field was passed in -- indicating # another mapping for the related Model. val = self.verify_fk(feat, model_field, ogr_name) else: # Otherwise, verify OGR Field type. val = self.verify_ogr_field(feat[ogr_name], model_field) # Setting the keyword arguments for the field name with the # value obtained above. kwargs[field_name] = val return kwargs
[ "def", "feature_kwargs", "(", "self", ",", "feat", ")", ":", "# The keyword arguments for model construction.", "kwargs", "=", "{", "}", "# Incrementing through each model field and OGR field in the", "# dictionary mapping.", "for", "field_name", ",", "ogr_name", "in", "self", ".", "mapping", ".", "items", "(", ")", ":", "model_field", "=", "self", ".", "fields", "[", "field_name", "]", "if", "isinstance", "(", "model_field", ",", "GeometryField", ")", ":", "# Verify OGR geometry.", "try", ":", "val", "=", "self", ".", "verify_geom", "(", "feat", ".", "geom", ",", "model_field", ")", "except", "GDALException", ":", "raise", "LayerMapError", "(", "'Could not retrieve geometry from feature.'", ")", "elif", "isinstance", "(", "model_field", ",", "models", ".", "base", ".", "ModelBase", ")", ":", "# The related _model_, not a field was passed in -- indicating", "# another mapping for the related Model.", "val", "=", "self", ".", "verify_fk", "(", "feat", ",", "model_field", ",", "ogr_name", ")", "else", ":", "# Otherwise, verify OGR Field type.", "val", "=", "self", ".", "verify_ogr_field", "(", "feat", "[", "ogr_name", "]", ",", "model_field", ")", "# Setting the keyword arguments for the field name with the", "# value obtained above.", "kwargs", "[", "field_name", "]", "=", "val", "return", "kwargs" ]
[ 299, 4 ]
[ 330, 21 ]
python
en
['en', 'error', 'th']
False
LayerMapping.unique_kwargs
(self, kwargs)
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, str): return {self.unique: kwargs[self.unique]} else: return {fld: kwargs[fld] for fld in self.unique}
[ "def", "unique_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "unique", ",", "str", ")", ":", "return", "{", "self", ".", "unique", ":", "kwargs", "[", "self", ".", "unique", "]", "}", "else", ":", "return", "{", "fld", ":", "kwargs", "[", "fld", "]", "for", "fld", "in", "self", ".", "unique", "}" ]
[ 332, 4 ]
[ 341, 60 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_ogr_field
(self, ogr_field, model_field)
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
def verify_ogr_field(self, ogr_field, model_field): """ Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception. """ if (isinstance(ogr_field, OFTString) and isinstance(model_field, (models.CharField, models.TextField))): if self.encoding and ogr_field.value is not None: # The encoding for OGR data sources may be specified here # (e.g., 'cp437' for Census Bureau boundary files). val = force_str(ogr_field.value, self.encoding) else: val = ogr_field.value if model_field.max_length and val is not None and len(val) > model_field.max_length: raise InvalidString('%s model field maximum string length is %s, given %s characters.' % (model_field.name, model_field.max_length, len(val))) elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField): try: # Creating an instance of the Decimal value to use. d = Decimal(str(ogr_field.value)) except DecimalInvalidOperation: raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value) # Getting the decimal value as a tuple. dtup = d.as_tuple() digits = dtup[1] d_idx = dtup[2] # index where the decimal is # Maximum amount of precision, or digits to the left of the decimal. max_prec = model_field.max_digits - model_field.decimal_places # Getting the digits to the left of the decimal place for the # given decimal. if d_idx < 0: n_prec = len(digits[:d_idx]) else: n_prec = len(digits) + d_idx # If we have more than the maximum digits allowed, then throw an # InvalidDecimal exception. if n_prec > max_prec: raise InvalidDecimal( 'A DecimalField with max_digits %d, decimal_places %d must ' 'round to an absolute value less than 10^%d.' % (model_field.max_digits, model_field.decimal_places, max_prec) ) val = d elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField): # Attempt to convert any OFTReal and OFTString value to an OFTInteger. try: val = int(ogr_field.value) except ValueError: raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value) else: val = ogr_field.value return val
[ "def", "verify_ogr_field", "(", "self", ",", "ogr_field", ",", "model_field", ")", ":", "if", "(", "isinstance", "(", "ogr_field", ",", "OFTString", ")", "and", "isinstance", "(", "model_field", ",", "(", "models", ".", "CharField", ",", "models", ".", "TextField", ")", ")", ")", ":", "if", "self", ".", "encoding", "and", "ogr_field", ".", "value", "is", "not", "None", ":", "# The encoding for OGR data sources may be specified here", "# (e.g., 'cp437' for Census Bureau boundary files).", "val", "=", "force_str", "(", "ogr_field", ".", "value", ",", "self", ".", "encoding", ")", "else", ":", "val", "=", "ogr_field", ".", "value", "if", "model_field", ".", "max_length", "and", "val", "is", "not", "None", "and", "len", "(", "val", ")", ">", "model_field", ".", "max_length", ":", "raise", "InvalidString", "(", "'%s model field maximum string length is %s, given %s characters.'", "%", "(", "model_field", ".", "name", ",", "model_field", ".", "max_length", ",", "len", "(", "val", ")", ")", ")", "elif", "isinstance", "(", "ogr_field", ",", "OFTReal", ")", "and", "isinstance", "(", "model_field", ",", "models", ".", "DecimalField", ")", ":", "try", ":", "# Creating an instance of the Decimal value to use.", "d", "=", "Decimal", "(", "str", "(", "ogr_field", ".", "value", ")", ")", "except", "DecimalInvalidOperation", ":", "raise", "InvalidDecimal", "(", "'Could not construct decimal from: %s'", "%", "ogr_field", ".", "value", ")", "# Getting the decimal value as a tuple.", "dtup", "=", "d", ".", "as_tuple", "(", ")", "digits", "=", "dtup", "[", "1", "]", "d_idx", "=", "dtup", "[", "2", "]", "# index where the decimal is", "# Maximum amount of precision, or digits to the left of the decimal.", "max_prec", "=", "model_field", ".", "max_digits", "-", "model_field", ".", "decimal_places", "# Getting the digits to the left of the decimal place for the", "# given decimal.", "if", "d_idx", "<", "0", ":", "n_prec", "=", "len", "(", "digits", "[", ":", "d_idx", "]", ")", "else", ":", "n_prec", "=", "len", "(", "digits", ")", "+", "d_idx", "# If we have more than the maximum digits allowed, then throw an", "# InvalidDecimal exception.", "if", "n_prec", ">", "max_prec", ":", "raise", "InvalidDecimal", "(", "'A DecimalField with max_digits %d, decimal_places %d must '", "'round to an absolute value less than 10^%d.'", "%", "(", "model_field", ".", "max_digits", ",", "model_field", ".", "decimal_places", ",", "max_prec", ")", ")", "val", "=", "d", "elif", "isinstance", "(", "ogr_field", ",", "(", "OFTReal", ",", "OFTString", ")", ")", "and", "isinstance", "(", "model_field", ",", "models", ".", "IntegerField", ")", ":", "# Attempt to convert any OFTReal and OFTString value to an OFTInteger.", "try", ":", "val", "=", "int", "(", "ogr_field", ".", "value", ")", "except", "ValueError", ":", "raise", "InvalidInteger", "(", "'Could not construct integer from: %s'", "%", "ogr_field", ".", "value", ")", "else", ":", "val", "=", "ogr_field", ".", "value", "return", "val" ]
[ 344, 4 ]
[ 399, 18 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_fk
(self, feat, rel_model, rel_mapping)
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient mechanism exists for caching related # ForeignKey models. # Constructing and verifying the related model keyword arguments. fk_kwargs = {} for field_name, ogr_name in rel_mapping.items(): fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name)) # Attempting to retrieve and return the related model. try: return rel_model.objects.using(self.using).get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey( 'No ForeignKey %s model found with keyword arguments: %s' % (rel_model.__name__, fk_kwargs) )
[ "def", "verify_fk", "(", "self", ",", "feat", ",", "rel_model", ",", "rel_mapping", ")", ":", "# TODO: It is expensive to retrieve a model for every record --", "# explore if an efficient mechanism exists for caching related", "# ForeignKey models.", "# Constructing and verifying the related model keyword arguments.", "fk_kwargs", "=", "{", "}", "for", "field_name", ",", "ogr_name", "in", "rel_mapping", ".", "items", "(", ")", ":", "fk_kwargs", "[", "field_name", "]", "=", "self", ".", "verify_ogr_field", "(", "feat", "[", "ogr_name", "]", ",", "rel_model", ".", "_meta", ".", "get_field", "(", "field_name", ")", ")", "# Attempting to retrieve and return the related model.", "try", ":", "return", "rel_model", ".", "objects", ".", "using", "(", "self", ".", "using", ")", ".", "get", "(", "*", "*", "fk_kwargs", ")", "except", "ObjectDoesNotExist", ":", "raise", "MissingForeignKey", "(", "'No ForeignKey %s model found with keyword arguments: %s'", "%", "(", "rel_model", ".", "__name__", ",", "fk_kwargs", ")", ")" ]
[ 401, 4 ]
[ 422, 13 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_geom
(self, geom, model_field)
Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
def verify_geom(self, geom, model_field): """ Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D one, if necessary. if self.coord_dim != geom.coord_dim: geom.coord_dim = self.coord_dim if self.make_multi(geom.geom_type, model_field): # Constructing a multi-geometry type to contain the single geometry multi_type = self.MULTI_TYPES[geom.geom_type.num] g = OGRGeometry(multi_type) g.add(geom) else: g = geom # Transforming the geometry with our Coordinate Transformation object, # but only if the class variable `transform` is set w/a CoordTransform # object. if self.transform: g.transform(self.transform) # Returning the WKT of the geometry. return g.wkt
[ "def", "verify_geom", "(", "self", ",", "geom", ",", "model_field", ")", ":", "# Downgrade a 3D geom to a 2D one, if necessary.", "if", "self", ".", "coord_dim", "!=", "geom", ".", "coord_dim", ":", "geom", ".", "coord_dim", "=", "self", ".", "coord_dim", "if", "self", ".", "make_multi", "(", "geom", ".", "geom_type", ",", "model_field", ")", ":", "# Constructing a multi-geometry type to contain the single geometry", "multi_type", "=", "self", ".", "MULTI_TYPES", "[", "geom", ".", "geom_type", ".", "num", "]", "g", "=", "OGRGeometry", "(", "multi_type", ")", "g", ".", "add", "(", "geom", ")", "else", ":", "g", "=", "geom", "# Transforming the geometry with our Coordinate Transformation object,", "# but only if the class variable `transform` is set w/a CoordTransform", "# object.", "if", "self", ".", "transform", ":", "g", ".", "transform", "(", "self", ".", "transform", ")", "# Returning the WKT of the geometry.", "return", "g", ".", "wkt" ]
[ 424, 4 ]
[ 449, 20 ]
python
en
['en', 'error', 'th']
False
LayerMapping.coord_transform
(self)
Return the coordinate transformation object.
Return the coordinate transformation object.
def coord_transform(self): "Return the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs # Creating the CoordTransform object return CoordTransform(self.source_srs, target_srs) except Exception as exc: raise LayerMapError( 'Could not translate between the data source and model geometry.' ) from exc
[ "def", "coord_transform", "(", "self", ")", ":", "SpatialRefSys", "=", "self", ".", "spatial_backend", ".", "spatial_ref_sys", "(", ")", "try", ":", "# Getting the target spatial reference system", "target_srs", "=", "SpatialRefSys", ".", "objects", ".", "using", "(", "self", ".", "using", ")", ".", "get", "(", "srid", "=", "self", ".", "geo_field", ".", "srid", ")", ".", "srs", "# Creating the CoordTransform object", "return", "CoordTransform", "(", "self", ".", "source_srs", ",", "target_srs", ")", "except", "Exception", "as", "exc", ":", "raise", "LayerMapError", "(", "'Could not translate between the data source and model geometry.'", ")", "from", "exc" ]
[ 452, 4 ]
[ 464, 22 ]
python
en
['en', 'en', 'en']
True
LayerMapping.geometry_field
(self)
Return the GeometryField instance associated with the geographic column.
Return the GeometryField instance associated with the geographic column.
def geometry_field(self): "Return the GeometryField instance associated with the geographic column." # Use `get_field()` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta return opts.get_field(self.geom_field)
[ "def", "geometry_field", "(", "self", ")", ":", "# Use `get_field()` on the model's options so that we", "# get the correct field instance if there's model inheritance.", "opts", "=", "self", ".", "model", ".", "_meta", "return", "opts", ".", "get_field", "(", "self", ".", "geom_field", ")" ]
[ 466, 4 ]
[ 471, 46 ]
python
en
['en', 'en', 'en']
True
LayerMapping.make_multi
(self, geom_type, model_field)
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return (geom_type.num in self.MULTI_TYPES and model_field.__class__.__name__ == 'Multi%s' % geom_type.django)
[ "def", "make_multi", "(", "self", ",", "geom_type", ",", "model_field", ")", ":", "return", "(", "geom_type", ".", "num", "in", "self", ".", "MULTI_TYPES", "and", "model_field", ".", "__class__", ".", "__name__", "==", "'Multi%s'", "%", "geom_type", ".", "django", ")" ]
[ 473, 4 ]
[ 479, 79 ]
python
en
['en', 'error', 'th']
False
LayerMapping.save
(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)
Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_range: May be set with a slice or tuple of (begin, end) feature ID's to map from the data source. In other words, this keyword enables the user to selectively import a subset range of features in the geographic data source. step: If set with an integer, transactions will occur at every step interval. For example, if step=1000, a commit would occur after the 1,000th feature, the 2,000th feature etc. progress: When this keyword is set, status information will be printed giving the number of features processed and successfully saved. By default, progress information will pe printed every 1000 features processed, however, this default may be overridden by setting this keyword with an integer for the desired interval. stream: Status information will be written to this file handle. Defaults to using `sys.stdout`, but any object with a `write` method is supported. silent: By default, non-fatal error notifications are printed to stdout, but this keyword may be set to disable these notifications. strict: Execution of the model mapping will cease upon the first error encountered. The default behavior is to attempt to continue.
Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization.
def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False): """ Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_range: May be set with a slice or tuple of (begin, end) feature ID's to map from the data source. In other words, this keyword enables the user to selectively import a subset range of features in the geographic data source. step: If set with an integer, transactions will occur at every step interval. For example, if step=1000, a commit would occur after the 1,000th feature, the 2,000th feature etc. progress: When this keyword is set, status information will be printed giving the number of features processed and successfully saved. By default, progress information will pe printed every 1000 features processed, however, this default may be overridden by setting this keyword with an integer for the desired interval. stream: Status information will be written to this file handle. Defaults to using `sys.stdout`, but any object with a `write` method is supported. silent: By default, non-fatal error notifications are printed to stdout, but this keyword may be set to disable these notifications. strict: Execution of the model mapping will cease upon the first error encountered. The default behavior is to attempt to continue. """ # Getting the default Feature ID range. default_range = self.check_fid_range(fid_range) # Setting the progress interval, if requested. if progress: if progress is True or not isinstance(progress, int): progress_interval = 1000 else: progress_interval = progress def _save(feat_range=default_range, num_feat=0, num_saved=0): if feat_range: layer_iter = self.layer[feat_range] else: layer_iter = self.layer for feat in layer_iter: num_feat += 1 # Getting the keyword arguments try: kwargs = self.feature_kwargs(feat) except LayerMapError as msg: # Something borked the validation if strict: raise elif not silent: stream.write('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg)) else: # Constructing the model using the keyword args is_update = False if self.unique: # If we want unique models on a particular field, handle the # geometry appropriately. try: # Getting the keyword arguments and retrieving # the unique model. u_kwargs = self.unique_kwargs(kwargs) m = self.model.objects.using(self.using).get(**u_kwargs) is_update = True # Getting the geometry (in OGR form), creating # one from the kwargs WKT, adding in additional # geometries, and update the attribute with the # just-updated geometry WKT. geom_value = getattr(m, self.geom_field) if geom_value is None: geom = OGRGeometry(kwargs[self.geom_field]) else: geom = geom_value.ogr new = OGRGeometry(kwargs[self.geom_field]) for g in new: geom.add(g) setattr(m, self.geom_field, geom.wkt) except ObjectDoesNotExist: # No unique model exists yet, create. m = self.model(**kwargs) else: m = self.model(**kwargs) try: # Attempting to save. m.save(using=self.using) num_saved += 1 if verbose: stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m)) except Exception as msg: if strict: # Bailing out if the `strict` keyword is set. if not silent: stream.write( 'Failed to save the feature (id: %s) into the ' 'model with the keyword arguments:\n' % feat.fid ) stream.write('%s\n' % kwargs) raise elif not silent: stream.write('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg)) # Printing progress information, if requested. if progress and num_feat % progress_interval == 0: stream.write('Processed %d features, saved %d ...\n' % (num_feat, num_saved)) # Only used for status output purposes -- incremental saving uses the # values returned here. return num_saved, num_feat if self.transaction_decorator is not None: _save = self.transaction_decorator(_save) nfeat = self.layer.num_feat if step and isinstance(step, int) and step < nfeat: # Incremental saving is requested at the given interval (step) if default_range: raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.') beg, num_feat, num_saved = (0, 0, 0) indices = range(step, nfeat, step) n_i = len(indices) for i, end in enumerate(indices): # Constructing the slice to use for this step; the last slice is # special (e.g, [100:] instead of [90:100]). if i + 1 == n_i: step_slice = slice(beg, None) else: step_slice = slice(beg, end) try: num_feat, num_saved = _save(step_slice, num_feat, num_saved) beg = end except Exception: # Deliberately catch everything stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice)) raise else: # Otherwise, just calling the previously defined _save() function. _save()
[ "def", "save", "(", "self", ",", "verbose", "=", "False", ",", "fid_range", "=", "False", ",", "step", "=", "False", ",", "progress", "=", "False", ",", "silent", "=", "False", ",", "stream", "=", "sys", ".", "stdout", ",", "strict", "=", "False", ")", ":", "# Getting the default Feature ID range.", "default_range", "=", "self", ".", "check_fid_range", "(", "fid_range", ")", "# Setting the progress interval, if requested.", "if", "progress", ":", "if", "progress", "is", "True", "or", "not", "isinstance", "(", "progress", ",", "int", ")", ":", "progress_interval", "=", "1000", "else", ":", "progress_interval", "=", "progress", "def", "_save", "(", "feat_range", "=", "default_range", ",", "num_feat", "=", "0", ",", "num_saved", "=", "0", ")", ":", "if", "feat_range", ":", "layer_iter", "=", "self", ".", "layer", "[", "feat_range", "]", "else", ":", "layer_iter", "=", "self", ".", "layer", "for", "feat", "in", "layer_iter", ":", "num_feat", "+=", "1", "# Getting the keyword arguments", "try", ":", "kwargs", "=", "self", ".", "feature_kwargs", "(", "feat", ")", "except", "LayerMapError", "as", "msg", ":", "# Something borked the validation", "if", "strict", ":", "raise", "elif", "not", "silent", ":", "stream", ".", "write", "(", "'Ignoring Feature ID %s because: %s\\n'", "%", "(", "feat", ".", "fid", ",", "msg", ")", ")", "else", ":", "# Constructing the model using the keyword args", "is_update", "=", "False", "if", "self", ".", "unique", ":", "# If we want unique models on a particular field, handle the", "# geometry appropriately.", "try", ":", "# Getting the keyword arguments and retrieving", "# the unique model.", "u_kwargs", "=", "self", ".", "unique_kwargs", "(", "kwargs", ")", "m", "=", "self", ".", "model", ".", "objects", ".", "using", "(", "self", ".", "using", ")", ".", "get", "(", "*", "*", "u_kwargs", ")", "is_update", "=", "True", "# Getting the geometry (in OGR form), creating", "# one from the kwargs WKT, adding in additional", "# geometries, and update the attribute with the", "# just-updated geometry WKT.", "geom_value", "=", "getattr", "(", "m", ",", "self", ".", "geom_field", ")", "if", "geom_value", "is", "None", ":", "geom", "=", "OGRGeometry", "(", "kwargs", "[", "self", ".", "geom_field", "]", ")", "else", ":", "geom", "=", "geom_value", ".", "ogr", "new", "=", "OGRGeometry", "(", "kwargs", "[", "self", ".", "geom_field", "]", ")", "for", "g", "in", "new", ":", "geom", ".", "add", "(", "g", ")", "setattr", "(", "m", ",", "self", ".", "geom_field", ",", "geom", ".", "wkt", ")", "except", "ObjectDoesNotExist", ":", "# No unique model exists yet, create.", "m", "=", "self", ".", "model", "(", "*", "*", "kwargs", ")", "else", ":", "m", "=", "self", ".", "model", "(", "*", "*", "kwargs", ")", "try", ":", "# Attempting to save.", "m", ".", "save", "(", "using", "=", "self", ".", "using", ")", "num_saved", "+=", "1", "if", "verbose", ":", "stream", ".", "write", "(", "'%s: %s\\n'", "%", "(", "'Updated'", "if", "is_update", "else", "'Saved'", ",", "m", ")", ")", "except", "Exception", "as", "msg", ":", "if", "strict", ":", "# Bailing out if the `strict` keyword is set.", "if", "not", "silent", ":", "stream", ".", "write", "(", "'Failed to save the feature (id: %s) into the '", "'model with the keyword arguments:\\n'", "%", "feat", ".", "fid", ")", "stream", ".", "write", "(", "'%s\\n'", "%", "kwargs", ")", "raise", "elif", "not", "silent", ":", "stream", ".", "write", "(", "'Failed to save %s:\\n %s\\nContinuing\\n'", "%", "(", "kwargs", ",", "msg", ")", ")", "# Printing progress information, if requested.", "if", "progress", "and", "num_feat", "%", "progress_interval", "==", "0", ":", "stream", ".", "write", "(", "'Processed %d features, saved %d ...\\n'", "%", "(", "num_feat", ",", "num_saved", ")", ")", "# Only used for status output purposes -- incremental saving uses the", "# values returned here.", "return", "num_saved", ",", "num_feat", "if", "self", ".", "transaction_decorator", "is", "not", "None", ":", "_save", "=", "self", ".", "transaction_decorator", "(", "_save", ")", "nfeat", "=", "self", ".", "layer", ".", "num_feat", "if", "step", "and", "isinstance", "(", "step", ",", "int", ")", "and", "step", "<", "nfeat", ":", "# Incremental saving is requested at the given interval (step)", "if", "default_range", ":", "raise", "LayerMapError", "(", "'The `step` keyword may not be used in conjunction with the `fid_range` keyword.'", ")", "beg", ",", "num_feat", ",", "num_saved", "=", "(", "0", ",", "0", ",", "0", ")", "indices", "=", "range", "(", "step", ",", "nfeat", ",", "step", ")", "n_i", "=", "len", "(", "indices", ")", "for", "i", ",", "end", "in", "enumerate", "(", "indices", ")", ":", "# Constructing the slice to use for this step; the last slice is", "# special (e.g, [100:] instead of [90:100]).", "if", "i", "+", "1", "==", "n_i", ":", "step_slice", "=", "slice", "(", "beg", ",", "None", ")", "else", ":", "step_slice", "=", "slice", "(", "beg", ",", "end", ")", "try", ":", "num_feat", ",", "num_saved", "=", "_save", "(", "step_slice", ",", "num_feat", ",", "num_saved", ")", "beg", "=", "end", "except", "Exception", ":", "# Deliberately catch everything", "stream", ".", "write", "(", "'%s\\nFailed to save slice: %s\\n'", "%", "(", "'=-'", "*", "20", ",", "step_slice", ")", ")", "raise", "else", ":", "# Otherwise, just calling the previously defined _save() function.", "_save", "(", ")" ]
[ 481, 4 ]
[ 636, 19 ]
python
en
['en', 'error', 'th']
False
UserKNN.__init__
(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, rank_length=10, as_binary=False, as_similar_first=True, sep='\t', output_sep='\t')
User KNN for Item Recommendation This algorithm predicts a rank for each user based on the similar items that his neighbors (similar users) consumed. Usage:: >> UserKNN(train, test, as_similar_first=True).compute() >> UserKNN(train, test, ranking_file, as_binary=True).compute() :param train_file: File which contains the train set. This file needs to have at least 3 columns (user item feedback_value). :type train_file: str :param test_file: File which contains the test set. This file needs to have at least 3 columns (user item feedback_value). :type test_file: str, default None :param output_file: File with dir to write the final predictions :type output_file: str, default None :param similarity_metric: Pairwise metric to compute the similarity between the users. Reference about distances: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.pdist.html :type similarity_metric: str, default cosine :param k_neighbors: Number of neighbors to use. If None, k_neighbor = int(sqrt(n_users)) :type k_neighbors: int, default None :param rank_length: Size of the rank that must be generated by the predictions of the recommender algorithm :type rank_length: int, default 10 :param as_binary: If True, the explicit feedback will be transform to binary :type as_binary: bool, default False :param as_similar_first: If True, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. :type as_similar_first: bool, default True :param sep: Delimiter for input files :type sep: str, default '\t' :param output_sep: Delimiter for output file :type output_sep: str, default '\t'
User KNN for Item Recommendation
def __init__(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, rank_length=10, as_binary=False, as_similar_first=True, sep='\t', output_sep='\t'): """ User KNN for Item Recommendation This algorithm predicts a rank for each user based on the similar items that his neighbors (similar users) consumed. Usage:: >> UserKNN(train, test, as_similar_first=True).compute() >> UserKNN(train, test, ranking_file, as_binary=True).compute() :param train_file: File which contains the train set. This file needs to have at least 3 columns (user item feedback_value). :type train_file: str :param test_file: File which contains the test set. This file needs to have at least 3 columns (user item feedback_value). :type test_file: str, default None :param output_file: File with dir to write the final predictions :type output_file: str, default None :param similarity_metric: Pairwise metric to compute the similarity between the users. Reference about distances: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.pdist.html :type similarity_metric: str, default cosine :param k_neighbors: Number of neighbors to use. If None, k_neighbor = int(sqrt(n_users)) :type k_neighbors: int, default None :param rank_length: Size of the rank that must be generated by the predictions of the recommender algorithm :type rank_length: int, default 10 :param as_binary: If True, the explicit feedback will be transform to binary :type as_binary: bool, default False :param as_similar_first: If True, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. :type as_similar_first: bool, default True :param sep: Delimiter for input files :type sep: str, default '\t' :param output_sep: Delimiter for output file :type output_sep: str, default '\t' """ super(UserKNN, self).__init__(train_file=train_file, test_file=test_file, output_file=output_file, as_binary=as_binary, rank_length=rank_length, similarity_metric=similarity_metric, sep=sep, output_sep=output_sep) self.recommender_name = 'UserKNN Algorithm' self.as_similar_first = as_similar_first self.k_neighbors = k_neighbors # internal vars self.su_matrix = None self.users_id_viewed_item = None
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "similarity_metric", "=", "\"cosine\"", ",", "k_neighbors", "=", "None", ",", "rank_length", "=", "10", ",", "as_binary", "=", "False", ",", "as_similar_first", "=", "True", ",", "sep", "=", "'\\t'", ",", "output_sep", "=", "'\\t'", ")", ":", "super", "(", "UserKNN", ",", "self", ")", ".", "__init__", "(", "train_file", "=", "train_file", ",", "test_file", "=", "test_file", ",", "output_file", "=", "output_file", ",", "as_binary", "=", "as_binary", ",", "rank_length", "=", "rank_length", ",", "similarity_metric", "=", "similarity_metric", ",", "sep", "=", "sep", ",", "output_sep", "=", "output_sep", ")", "self", ".", "recommender_name", "=", "'UserKNN Algorithm'", "self", ".", "as_similar_first", "=", "as_similar_first", "self", ".", "k_neighbors", "=", "k_neighbors", "# internal vars", "self", ".", "su_matrix", "=", "None", "self", ".", "users_id_viewed_item", "=", "None" ]
[ 20, 4 ]
[ 81, 40 ]
python
en
['en', 'error', 'th']
False
UserKNN.init_model
(self)
Method to initialize the model. Create and calculate a similarity matrix
Method to initialize the model. Create and calculate a similarity matrix
def init_model(self): """ Method to initialize the model. Create and calculate a similarity matrix """ self.users_id_viewed_item = {} self.create_matrix() self.su_matrix = self.compute_similarity(transpose=False) # Set the value for k if self.k_neighbors is None: self.k_neighbors = int(np.sqrt(len(self.users))) for item in self.items: for user in self.train_set['users_viewed_item'].get(item, []): self.users_id_viewed_item.setdefault(item, []).append(self.user_to_user_id[user])
[ "def", "init_model", "(", "self", ")", ":", "self", ".", "users_id_viewed_item", "=", "{", "}", "self", ".", "create_matrix", "(", ")", "self", ".", "su_matrix", "=", "self", ".", "compute_similarity", "(", "transpose", "=", "False", ")", "# Set the value for k", "if", "self", ".", "k_neighbors", "is", "None", ":", "self", ".", "k_neighbors", "=", "int", "(", "np", ".", "sqrt", "(", "len", "(", "self", ".", "users", ")", ")", ")", "for", "item", "in", "self", ".", "items", ":", "for", "user", "in", "self", ".", "train_set", "[", "'users_viewed_item'", "]", ".", "get", "(", "item", ",", "[", "]", ")", ":", "self", ".", "users_id_viewed_item", ".", "setdefault", "(", "item", ",", "[", "]", ")", ".", "append", "(", "self", ".", "user_to_user_id", "[", "user", "]", ")" ]
[ 83, 4 ]
[ 99, 97 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict
(self)
Method to predict a rank for each user.
Method to predict a rank for each user.
def predict(self): """ Method to predict a rank for each user. """ for u_id, user in enumerate(self.users): if len(self.train_set['feedback'].get(user, [])) != 0: u_list = list(np.flatnonzero(self.matrix[u_id] == 0)) if self.as_similar_first: self.ranking += self.predict_similar_first_scores(user, u_id, u_list) else: self.ranking += self.predict_scores(user, u_id, u_list) else: # Implement cold start user pass
[ "def", "predict", "(", "self", ")", ":", "for", "u_id", ",", "user", "in", "enumerate", "(", "self", ".", "users", ")", ":", "if", "len", "(", "self", ".", "train_set", "[", "'feedback'", "]", ".", "get", "(", "user", ",", "[", "]", ")", ")", "!=", "0", ":", "u_list", "=", "list", "(", "np", ".", "flatnonzero", "(", "self", ".", "matrix", "[", "u_id", "]", "==", "0", ")", ")", "if", "self", ".", "as_similar_first", ":", "self", ".", "ranking", "+=", "self", ".", "predict_similar_first_scores", "(", "user", ",", "u_id", ",", "u_list", ")", "else", ":", "self", ".", "ranking", "+=", "self", ".", "predict_scores", "(", "user", ",", "u_id", ",", "u_list", ")", "else", ":", "# Implement cold start user", "pass" ]
[ 101, 4 ]
[ 117, 20 ]
python
en
['en', 'error', 'th']
False