How to use value method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

univ.py

Source:univ.py Github

copy

Full Screen

1# ASN.1 "universal" data types2import operator, sys3from pyasn1.type import base, tag, constraint, namedtype, namedval, tagmap4from pyasn1.codec.ber import eoo5from pyasn1.compat import octets6from pyasn1 import error7# "Simple" ASN.1 types (yet incomplete)8class Integer(base.AbstractSimpleAsn1Item):9 tagSet = baseTagSet = tag.initTagSet(10 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02)11 )12 namedValues = namedval.NamedValues()13 def __init__(self, value=None, tagSet=None, subtypeSpec=None,14 namedValues=None):15 if namedValues is None:16 self.__namedValues = self.namedValues17 else:18 self.__namedValues = namedValues19 base.AbstractSimpleAsn1Item.__init__(20 self, value, tagSet, subtypeSpec21 )22 def __and__(self, value): return self.clone(self._value & value)23 def __rand__(self, value): return self.clone(value & self._value)24 def __or__(self, value): return self.clone(self._value | value)25 def __ror__(self, value): return self.clone(value | self._value)26 def __xor__(self, value): return self.clone(self._value ^ value)27 def __rxor__(self, value): return self.clone(value ^ self._value)28 def __lshift__(self, value): return self.clone(self._value << value)29 def __rshift__(self, value): return self.clone(self._value >> value)30 def __add__(self, value): return self.clone(self._value + value)31 def __radd__(self, value): return self.clone(value + self._value)32 def __sub__(self, value): return self.clone(self._value - value)33 def __rsub__(self, value): return self.clone(value - self._value)34 def __mul__(self, value): return self.clone(self._value * value)35 def __rmul__(self, value): return self.clone(value * self._value)36 def __mod__(self, value): return self.clone(self._value % value)37 def __rmod__(self, value): return self.clone(value % self._value)38 def __pow__(self, value, modulo=None): return self.clone(pow(self._value, value, modulo))39 def __rpow__(self, value): return self.clone(pow(value, self._value))40 if sys.version_info[0] <= 2:41 def __div__(self, value): return self.clone(self._value // value)42 def __rdiv__(self, value): return self.clone(value // self._value)43 else:44 def __truediv__(self, value): return self.clone(self._value / value)45 def __rtruediv__(self, value): return self.clone(value / self._value)46 def __divmod__(self, value): return self.clone(self._value // value)47 def __rdivmod__(self, value): return self.clone(value // self._value)48 __hash__ = base.AbstractSimpleAsn1Item.__hash__49 def __int__(self): return int(self._value)50 if sys.version_info[0] <= 2:51 def __long__(self): return long(self._value)52 def __float__(self): return float(self._value) 53 def __abs__(self): return abs(self._value)54 def __index__(self): return int(self._value)55 def __lt__(self, value): return self._value < value56 def __le__(self, value): return self._value <= value57 def __eq__(self, value): return self._value == value58 def __ne__(self, value): return self._value != value59 def __gt__(self, value): return self._value > value60 def __ge__(self, value): return self._value >= value61 def prettyIn(self, value):62 if not isinstance(value, str):63 try:64 return int(value)65 except:66 raise error.PyAsn1Error(67 'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])68 )69 r = self.__namedValues.getValue(value)70 if r is not None:71 return r72 try:73 return int(value)74 except:75 raise error.PyAsn1Error(76 'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])77 )78 def prettyOut(self, value):79 r = self.__namedValues.getName(value)80 return r is None and str(value) or repr(r)81 def getNamedValues(self): return self.__namedValues82 def clone(self, value=None, tagSet=None, subtypeSpec=None,83 namedValues=None):84 if value is None and tagSet is None and subtypeSpec is None \85 and namedValues is None:86 return self87 if value is None:88 value = self._value89 if tagSet is None:90 tagSet = self._tagSet91 if subtypeSpec is None:92 subtypeSpec = self._subtypeSpec93 if namedValues is None:94 namedValues = self.__namedValues95 return self.__class__(value, tagSet, subtypeSpec, namedValues)96 def subtype(self, value=None, implicitTag=None, explicitTag=None,97 subtypeSpec=None, namedValues=None):98 if value is None:99 value = self._value100 if implicitTag is not None:101 tagSet = self._tagSet.tagImplicitly(implicitTag)102 elif explicitTag is not None:103 tagSet = self._tagSet.tagExplicitly(explicitTag)104 else:105 tagSet = self._tagSet106 if subtypeSpec is None:107 subtypeSpec = self._subtypeSpec108 else:109 subtypeSpec = subtypeSpec + self._subtypeSpec110 if namedValues is None:111 namedValues = self.__namedValues112 else:113 namedValues = namedValues + self.__namedValues114 return self.__class__(value, tagSet, subtypeSpec, namedValues)115class Boolean(Integer):116 tagSet = baseTagSet = tag.initTagSet(117 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01),118 )119 subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(0,1)120 namedValues = Integer.namedValues.clone(('False', 0), ('True', 1))121class BitString(base.AbstractSimpleAsn1Item):122 tagSet = baseTagSet = tag.initTagSet(123 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03)124 )125 namedValues = namedval.NamedValues()126 def __init__(self, value=None, tagSet=None, subtypeSpec=None,127 namedValues=None):128 if namedValues is None:129 self.__namedValues = self.namedValues130 else:131 self.__namedValues = namedValues132 base.AbstractSimpleAsn1Item.__init__(133 self, value, tagSet, subtypeSpec134 )135 def clone(self, value=None, tagSet=None, subtypeSpec=None,136 namedValues=None):137 if value is None and tagSet is None and subtypeSpec is None \138 and namedValues is None:139 return self140 if value is None:141 value = self._value142 if tagSet is None:143 tagSet = self._tagSet144 if subtypeSpec is None:145 subtypeSpec = self._subtypeSpec146 if namedValues is None:147 namedValues = self.__namedValues148 return self.__class__(value, tagSet, subtypeSpec, namedValues)149 def subtype(self, value=None, implicitTag=None, explicitTag=None,150 subtypeSpec=None, namedValues=None):151 if value is None:152 value = self._value153 if implicitTag is not None:154 tagSet = self._tagSet.tagImplicitly(implicitTag)155 elif explicitTag is not None:156 tagSet = self._tagSet.tagExplicitly(explicitTag)157 else:158 tagSet = self._tagSet159 if subtypeSpec is None:160 subtypeSpec = self._subtypeSpec161 else:162 subtypeSpec = subtypeSpec + self._subtypeSpec163 if namedValues is None:164 namedValues = self.__namedValues165 else:166 namedValues = namedValues + self.__namedValues167 return self.__class__(value, tagSet, subtypeSpec, namedValues)168 def __str__(self): return str(tuple(self))169 # Immutable sequence object protocol170 def __len__(self):171 if self._len is None:172 self._len = len(self._value)173 return self._len174 def __getitem__(self, i):175 if isinstance(i, slice):176 return self.clone(operator.getitem(self._value, i))177 else:178 return self._value[i]179 def __add__(self, value): return self.clone(self._value + value)180 def __radd__(self, value): return self.clone(value + self._value)181 def __mul__(self, value): return self.clone(self._value * value)182 def __rmul__(self, value): return self * value183 def prettyIn(self, value):184 r = []185 if not value:186 return ()187 elif isinstance(value, str):188 if value[0] == '\'':189 if value[-2:] == '\'B':190 for v in value[1:-2]:191 if v == '0':192 r.append(0)193 elif v == '1':194 r.append(1)195 else:196 raise error.PyAsn1Error(197 'Non-binary BIT STRING initializer %s' % (v,)198 )199 return tuple(r)200 elif value[-2:] == '\'H':201 for v in value[1:-2]:202 i = 4203 v = int(v, 16)204 while i:205 i = i - 1206 r.append((v>>i)&0x01)207 return tuple(r)208 else:209 raise error.PyAsn1Error(210 'Bad BIT STRING value notation %s' % (value,)211 ) 212 else:213 for i in value.split(','):214 j = self.__namedValues.getValue(i)215 if j is None:216 raise error.PyAsn1Error(217 'Unknown bit identifier \'%s\'' % (i,)218 )219 if j >= len(r):220 r.extend([0]*(j-len(r)+1))221 r[j] = 1222 return tuple(r)223 elif isinstance(value, (tuple, list)):224 r = tuple(value)225 for b in r:226 if b and b != 1:227 raise error.PyAsn1Error(228 'Non-binary BitString initializer \'%s\'' % (r,)229 )230 return r231 elif isinstance(value, BitString):232 return tuple(value)233 else:234 raise error.PyAsn1Error(235 'Bad BitString initializer type \'%s\'' % (value,)236 )237 def prettyOut(self, value):238 return '\"\'%s\'B\"' % ''.join([str(x) for x in value])239class OctetString(base.AbstractSimpleAsn1Item):240 tagSet = baseTagSet = tag.initTagSet(241 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)242 )243 defaultBinValue = defaultHexValue = base.noValue244 encoding = 'us-ascii'245 def __init__(self, value=None, tagSet=None, subtypeSpec=None,246 encoding=None, binValue=None, hexValue=None):247 if encoding is None:248 self._encoding = self.encoding249 else:250 self._encoding = encoding251 if binValue is not None:252 value = self.fromBinaryString(binValue)253 if hexValue is not None:254 value = self.fromHexString(hexValue)255 if value is None or value is base.noValue:256 value = self.defaultHexValue257 if value is None or value is base.noValue:258 value = self.defaultBinValue259 self.__intValue = None260 base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec)261 def clone(self, value=None, tagSet=None, subtypeSpec=None,262 encoding=None, binValue=None, hexValue=None):263 if value is None and tagSet is None and subtypeSpec is None and \264 encoding is None and binValue is None and hexValue is None:265 return self266 if value is None and binValue is None and hexValue is None:267 value = self._value268 if tagSet is None:269 tagSet = self._tagSet270 if subtypeSpec is None:271 subtypeSpec = self._subtypeSpec272 if encoding is None:273 encoding = self._encoding274 return self.__class__(275 value, tagSet, subtypeSpec, encoding, binValue, hexValue276 )277 278 if sys.version_info[0] <= 2:279 def prettyIn(self, value):280 if isinstance(value, str):281 return value282 elif isinstance(value, (tuple, list)):283 try:284 return ''.join([ chr(x) for x in value ])285 except ValueError:286 raise error.PyAsn1Error(287 'Bad OctetString initializer \'%s\'' % (value,)288 ) 289 else:290 return str(value)291 else:292 def prettyIn(self, value):293 if isinstance(value, bytes):294 return value295 elif isinstance(value, OctetString):296 return value.asOctets()297 elif isinstance(value, (tuple, list, map)):298 try:299 return bytes(value)300 except ValueError:301 raise error.PyAsn1Error(302 'Bad OctetString initializer \'%s\'' % (value,)303 )304 else:305 try:306 return str(value).encode(self._encoding)307 except UnicodeEncodeError:308 raise error.PyAsn1Error(309 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)310 )311 312 def fromBinaryString(self, value):313 bitNo = 8; byte = 0; r = ()314 for v in value:315 if bitNo:316 bitNo = bitNo - 1317 else:318 bitNo = 7319 r = r + (byte,)320 byte = 0321 if v == '0':322 v = 0323 elif v == '1':324 v = 1325 else:326 raise error.PyAsn1Error(327 'Non-binary OCTET STRING initializer %s' % (v,)328 )329 byte = byte | (v << bitNo)330 return octets.ints2octs(r + (byte,))331 332 def fromHexString(self, value): 333 r = p = ()334 for v in value:335 if p:336 r = r + (int(p+v, 16),)337 p = ()338 else:339 p = v340 if p:341 r = r + (int(p+'0', 16),)342 return octets.ints2octs(r)343 def prettyOut(self, value):344 if sys.version_info[0] <= 2:345 numbers = tuple([ ord(x) for x in value ])346 else:347 numbers = tuple(value)348 if [ x for x in numbers if x < 32 or x > 126 ]:349 return '0x' + ''.join([ '%.2x' % x for x in numbers ])350 else:351 return str(value)352 def __repr__(self):353 if self._value is base.noValue:354 return self.__class__.__name__ + '()'355 if [ x for x in self.asNumbers() if x < 32 or x > 126 ]:356 return self.__class__.__name__ + '(hexValue=\'' + ''.join([ '%.2x' % x for x in self.asNumbers() ])+'\')'357 else:358 return self.__class__.__name__ + '(\'' + self.prettyOut(self._value) + '\')'359 360 if sys.version_info[0] <= 2:361 def __str__(self): return str(self._value)362 def __unicode__(self):363 return self._value.decode(self._encoding, 'ignore')364 def asOctets(self): return self._value365 def asNumbers(self):366 if self.__intValue is None:367 self.__intValue = tuple([ ord(x) for x in self._value ])368 return self.__intValue369 else:370 def __str__(self): return self._value.decode(self._encoding, 'ignore')371 def __bytes__(self): return self._value372 def asOctets(self): return self._value373 def asNumbers(self):374 if self.__intValue is None:375 self.__intValue = tuple(self._value)376 return self.__intValue377 378 # Immutable sequence object protocol379 380 def __len__(self):381 if self._len is None:382 self._len = len(self._value)383 return self._len384 def __getitem__(self, i):385 if isinstance(i, slice):386 return self.clone(operator.getitem(self._value, i))387 else:388 return self._value[i]389 def __add__(self, value): return self.clone(self._value + self.prettyIn(value))390 def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value)391 def __mul__(self, value): return self.clone(self._value * value)392 def __rmul__(self, value): return self * value393class Null(OctetString):394 defaultValue = ''.encode() # This is tightly constrained395 tagSet = baseTagSet = tag.initTagSet(396 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05)397 )398 subtypeSpec = OctetString.subtypeSpec+constraint.SingleValueConstraint(''.encode())399 400if sys.version_info[0] <= 2:401 intTypes = (int, long)402else:403 intTypes = int404class ObjectIdentifier(base.AbstractSimpleAsn1Item):405 tagSet = baseTagSet = tag.initTagSet(406 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)407 )408 def __add__(self, other): return self.clone(self._value + other)409 def __radd__(self, other): return self.clone(other + self._value)410 def asTuple(self): return self._value411 412 # Sequence object protocol413 414 def __len__(self):415 if self._len is None:416 self._len = len(self._value)417 return self._len418 def __getitem__(self, i):419 if isinstance(i, slice):420 return self.clone(421 operator.getitem(self._value, i)422 )423 else:424 return self._value[i]425 def __str__(self): return self.prettyPrint()426 427 def index(self, suboid): return self._value.index(suboid)428 def isPrefixOf(self, value):429 """Returns true if argument OID resides deeper in the OID tree"""430 l = len(self)431 if l <= len(value):432 if self._value[:l] == value[:l]:433 return 1434 return 0435 def prettyIn(self, value):436 """Dotted -> tuple of numerics OID converter"""437 if isinstance(value, tuple):438 pass439 elif isinstance(value, ObjectIdentifier):440 return tuple(value) 441 elif isinstance(value, str):442 r = []443 for element in [ x for x in value.split('.') if x != '' ]:444 try:445 r.append(int(element, 0))446 except ValueError:447 raise error.PyAsn1Error(448 'Malformed Object ID %s at %s: %s' %449 (str(value), self.__class__.__name__, sys.exc_info()[1])450 )451 value = tuple(r)452 else:453 try:454 value = tuple(value)455 except TypeError:456 raise error.PyAsn1Error(457 'Malformed Object ID %s at %s: %s' %458 (str(value), self.__class__.__name__,sys.exc_info()[1])459 )460 for x in value:461 if not isinstance(x, intTypes) or x < 0:462 raise error.PyAsn1Error(463 'Invalid sub-ID in %s at %s' % (value, self.__class__.__name__)464 )465 466 return value467 def prettyOut(self, value): return '.'.join([ str(x) for x in value ])468 469class Real(base.AbstractSimpleAsn1Item):470 try:471 _plusInf = float('inf')472 _minusInf = float('-inf')473 _inf = (_plusInf, _minusInf)474 except ValueError:475 # Infinity support is platform and Python dependent476 _plusInf = _minusInf = None477 _inf = ()478 tagSet = baseTagSet = tag.initTagSet(479 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09)480 )481 def __normalizeBase10(self, value):482 m, b, e = value483 while m and m % 10 == 0:484 m = m / 10485 e = e + 1486 return m, b, e487 def prettyIn(self, value):488 if isinstance(value, tuple) and len(value) == 3:489 for d in value:490 if not isinstance(d, intTypes):491 raise error.PyAsn1Error(492 'Lame Real value syntax: %s' % (value,)493 )494 if value[1] not in (2, 10):495 raise error.PyAsn1Error(496 'Prohibited base for Real value: %s' % (value[1],)497 )498 if value[1] == 10:499 value = self.__normalizeBase10(value)500 return value501 elif isinstance(value, intTypes):502 return self.__normalizeBase10((value, 10, 0))503 elif isinstance(value, float):504 if self._inf and value in self._inf:505 return value506 else:507 e = 0508 while int(value) != value:509 value = value * 10510 e = e - 1511 return self.__normalizeBase10((int(value), 10, e))512 elif isinstance(value, Real):513 return tuple(value)514 elif isinstance(value, str): # handle infinite literal515 try:516 return float(value)517 except ValueError:518 pass519 raise error.PyAsn1Error(520 'Bad real value syntax: %s' % (value,)521 )522 523 def prettyOut(self, value):524 if value in self._inf:525 return '\'%s\'' % value526 else:527 return str(value)528 def isPlusInfinity(self): return self._value == self._plusInf529 def isMinusInfinity(self): return self._value == self._minusInf530 def isInfinity(self): return self._value in self._inf531 532 def __str__(self): return str(float(self))533 534 def __add__(self, value): return self.clone(float(self) + value)535 def __radd__(self, value): return self + value536 def __mul__(self, value): return self.clone(float(self) * value)537 def __rmul__(self, value): return self * value538 def __sub__(self, value): return self.clone(float(self) - value)539 def __rsub__(self, value): return self.clone(value - float(self))540 def __mod__(self, value): return self.clone(float(self) % value)541 def __rmod__(self, value): return self.clone(value % float(self))542 def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo))543 def __rpow__(self, value): return self.clone(pow(value, float(self)))544 if sys.version_info[0] <= 2:545 def __div__(self, value): return self.clone(float(self) / value)546 def __rdiv__(self, value): return self.clone(value / float(self))547 else:548 def __truediv__(self, value): return self.clone(float(self) / value)549 def __rtruediv__(self, value): return self.clone(value / float(self))550 def __divmod__(self, value): return self.clone(float(self) // value)551 def __rdivmod__(self, value): return self.clone(value // float(self))552 def __int__(self): return int(float(self))553 if sys.version_info[0] <= 2:554 def __long__(self): return long(float(self))555 def __float__(self):556 if self._value in self._inf:557 return self._value558 else:559 return float(560 self._value[0] * pow(self._value[1], self._value[2])561 )562 def __abs__(self): return abs(float(self))563 def __lt__(self, value): return float(self) < value564 def __le__(self, value): return float(self) <= value565 def __eq__(self, value): return float(self) == value566 def __ne__(self, value): return float(self) != value567 def __gt__(self, value): return float(self) > value568 def __ge__(self, value): return float(self) >= value569 if sys.version_info[0] <= 2:570 def __nonzero__(self): return bool(float(self))571 else:572 def __bool__(self): return bool(float(self))573 __hash__ = base.AbstractSimpleAsn1Item.__hash__574 def __getitem__(self, idx):575 if self._value in self._inf:576 raise error.PyAsn1Error('Invalid infinite value operation')577 else:578 return self._value[idx]579 580class Enumerated(Integer):581 tagSet = baseTagSet = tag.initTagSet(582 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A)583 )584# "Structured" ASN.1 types585class SetOf(base.AbstractConstructedAsn1Item):586 componentType = None587 tagSet = baseTagSet = tag.initTagSet(588 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)589 )590 typeId = 1591 def _cloneComponentValues(self, myClone, cloneValueFlag):592 idx = 0; l = len(self._componentValues)593 while idx < l:594 c = self._componentValues[idx]595 if c is not None:596 if isinstance(c, base.AbstractConstructedAsn1Item):597 myClone.setComponentByPosition(598 idx, c.clone(cloneValueFlag=cloneValueFlag)599 )600 else:601 myClone.setComponentByPosition(idx, c.clone())602 idx = idx + 1603 604 def _verifyComponent(self, idx, value):605 if self._componentType is not None and \606 not self._componentType.isSuperTypeOf(value):607 raise error.PyAsn1Error('Component type error %s' % (value,))608 def getComponentByPosition(self, idx): return self._componentValues[idx]609 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):610 l = len(self._componentValues)611 if idx >= l:612 self._componentValues = self._componentValues + (idx-l+1)*[None]613 if value is None:614 if self._componentValues[idx] is None:615 if self._componentType is None:616 raise error.PyAsn1Error('Component type not defined')617 self._componentValues[idx] = self._componentType.clone()618 self._componentValuesSet = self._componentValuesSet + 1619 return self620 elif not isinstance(value, base.Asn1Item):621 if self._componentType is None:622 raise error.PyAsn1Error('Component type not defined')623 if isinstance(self._componentType, base.AbstractSimpleAsn1Item):624 value = self._componentType.clone(value=value)625 else:626 raise error.PyAsn1Error('Instance value required')627 if verifyConstraints:628 if self._componentType is not None:629 self._verifyComponent(idx, value)630 self._verifySubtypeSpec(value, idx) 631 if self._componentValues[idx] is None:632 self._componentValuesSet = self._componentValuesSet + 1633 self._componentValues[idx] = value634 return self635 def getComponentTagMap(self):636 if self._componentType is not None:637 return self._componentType.getTagMap()638 def prettyPrint(self, scope=0):639 scope = scope + 1640 r = self.__class__.__name__ + ':\n' 641 for idx in range(len(self._componentValues)):642 r = r + ' '*scope643 if self._componentValues[idx] is None:644 r = r + '<empty>'645 else:646 r = r + self._componentValues[idx].prettyPrint(scope)647 return r648class SequenceOf(SetOf):649 tagSet = baseTagSet = tag.initTagSet(650 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)651 )652 typeId = 2653class SequenceAndSetBase(base.AbstractConstructedAsn1Item):654 componentType = namedtype.NamedTypes()655 def __init__(self, componentType=None, tagSet=None,656 subtypeSpec=None, sizeSpec=None):657 base.AbstractConstructedAsn1Item.__init__(658 self, componentType, tagSet, subtypeSpec, sizeSpec659 )660 if self._componentType is None:661 self._componentTypeLen = 0662 else:663 self._componentTypeLen = len(self._componentType)664 def __getitem__(self, idx):665 if isinstance(idx, str):666 return self.getComponentByName(idx)667 else:668 return base.AbstractConstructedAsn1Item.__getitem__(self, idx)669 def __setitem__(self, idx, value):670 if isinstance(idx, str):671 self.setComponentByName(idx, value)672 else:673 base.AbstractConstructedAsn1Item.__setitem__(self, idx, value)674 675 def _cloneComponentValues(self, myClone, cloneValueFlag):676 idx = 0; l = len(self._componentValues)677 while idx < l:678 c = self._componentValues[idx]679 if c is not None:680 if isinstance(c, base.AbstractConstructedAsn1Item):681 myClone.setComponentByPosition(682 idx, c.clone(cloneValueFlag=cloneValueFlag)683 )684 else:685 myClone.setComponentByPosition(idx, c.clone())686 idx = idx + 1687 def _verifyComponent(self, idx, value):688 if idx >= self._componentTypeLen:689 raise error.PyAsn1Error(690 'Component type error out of range'691 )692 t = self._componentType[idx].getType()693 if not t.isSuperTypeOf(value):694 raise error.PyAsn1Error('Component type error %r vs %r' % (t, value))695 def getComponentByName(self, name):696 return self.getComponentByPosition(697 self._componentType.getPositionByName(name)698 )699 def setComponentByName(self, name, value=None, verifyConstraints=True):700 return self.setComponentByPosition(701 self._componentType.getPositionByName(name), value,702 verifyConstraints703 )704 def getComponentByPosition(self, idx):705 try:706 return self._componentValues[idx]707 except IndexError:708 if idx < self._componentTypeLen:709 return710 raise711 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):712 l = len(self._componentValues)713 if idx >= l:714 self._componentValues = self._componentValues + (idx-l+1)*[None]715 if value is None:716 if self._componentValues[idx] is None:717 self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone()718 self._componentValuesSet = self._componentValuesSet + 1719 return self720 elif not isinstance(value, base.Asn1Item):721 t = self._componentType.getTypeByPosition(idx)722 if isinstance(t, base.AbstractSimpleAsn1Item):723 value = t.clone(value=value)724 else:725 raise error.PyAsn1Error('Instance value required')726 if verifyConstraints:727 if self._componentTypeLen:728 self._verifyComponent(idx, value)729 self._verifySubtypeSpec(value, idx) 730 if self._componentValues[idx] is None:731 self._componentValuesSet = self._componentValuesSet + 1732 self._componentValues[idx] = value733 return self734 def getNameByPosition(self, idx):735 if self._componentTypeLen:736 return self._componentType.getNameByPosition(idx)737 def getDefaultComponentByPosition(self, idx):738 if self._componentTypeLen and self._componentType[idx].isDefaulted:739 return self._componentType[idx].getType()740 def getComponentType(self):741 if self._componentTypeLen:742 return self._componentType743 744 def setDefaultComponents(self):745 if self._componentTypeLen == self._componentValuesSet:746 return747 idx = self._componentTypeLen748 while idx:749 idx = idx - 1750 if self._componentType[idx].isDefaulted:751 if self.getComponentByPosition(idx) is None:752 self.setComponentByPosition(idx)753 elif not self._componentType[idx].isOptional:754 if self.getComponentByPosition(idx) is None:755 raise error.PyAsn1Error(756 'Uninitialized component #%s at %r' % (idx, self)757 )758 def prettyPrint(self, scope=0):759 scope = scope + 1760 r = self.__class__.__name__ + ':\n'761 for idx in range(len(self._componentValues)):762 if self._componentValues[idx] is not None:763 r = r + ' '*scope764 componentType = self.getComponentType()765 if componentType is None:766 r = r + '<no-name>'767 else:768 r = r + componentType.getNameByPosition(idx)769 r = '%s=%s\n' % (770 r, self._componentValues[idx].prettyPrint(scope)771 )772 return r773class Sequence(SequenceAndSetBase):774 tagSet = baseTagSet = tag.initTagSet(775 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)776 )777 typeId = 3778 def getComponentTagMapNearPosition(self, idx):779 if self._componentType:780 return self._componentType.getTagMapNearPosition(idx)781 782 def getComponentPositionNearType(self, tagSet, idx):783 if self._componentType:784 return self._componentType.getPositionNearType(tagSet, idx)785 else:786 return idx787 788class Set(SequenceAndSetBase):789 tagSet = baseTagSet = tag.initTagSet(790 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)791 )792 typeId = 4793 def getComponent(self, innerFlag=0): return self794 795 def getComponentByType(self, tagSet, innerFlag=0):796 c = self.getComponentByPosition(797 self._componentType.getPositionByType(tagSet)798 )799 if innerFlag and isinstance(c, Set):800 # get inner component by inner tagSet801 return c.getComponent(1)802 else:803 # get outer component by inner tagSet804 return c805 806 def setComponentByType(self, tagSet, value=None, innerFlag=0,807 verifyConstraints=True):808 idx = self._componentType.getPositionByType(tagSet)809 t = self._componentType.getTypeByPosition(idx)810 if innerFlag: # set inner component by inner tagSet811 if t.getTagSet():812 return self.setComponentByPosition(813 idx, value, verifyConstraints814 )815 else:816 t = self.setComponentByPosition(idx).getComponentByPosition(idx)817 return t.setComponentByType(818 tagSet, value, innerFlag, verifyConstraints819 )820 else: # set outer component by inner tagSet821 return self.setComponentByPosition(822 idx, value, verifyConstraints823 )824 825 def getComponentTagMap(self):826 if self._componentType:827 return self._componentType.getTagMap(True)828 def getComponentPositionByType(self, tagSet):829 if self._componentType:830 return self._componentType.getPositionByType(tagSet)831class Choice(Set):832 tagSet = baseTagSet = tag.TagSet() # untagged833 sizeSpec = constraint.ConstraintsIntersection(834 constraint.ValueSizeConstraint(1, 1)835 )836 typeId = 5837 _currentIdx = None838 def __eq__(self, other):839 if self._componentValues:840 return self._componentValues[self._currentIdx] == other841 return NotImplemented842 def __ne__(self, other):843 if self._componentValues:844 return self._componentValues[self._currentIdx] != other845 return NotImplemented846 def __lt__(self, other):847 if self._componentValues:848 return self._componentValues[self._currentIdx] < other849 return NotImplemented850 def __le__(self, other):851 if self._componentValues:852 return self._componentValues[self._currentIdx] <= other853 return NotImplemented854 def __gt__(self, other):855 if self._componentValues:856 return self._componentValues[self._currentIdx] > other857 return NotImplemented858 def __ge__(self, other):859 if self._componentValues:860 return self._componentValues[self._currentIdx] >= other861 return NotImplemented862 if sys.version_info[0] <= 2:863 def __nonzero__(self): return bool(self._componentValues)864 else:865 def __bool__(self): return bool(self._componentValues)866 def __len__(self): return self._currentIdx is not None and 1 or 0867 868 def verifySizeSpec(self):869 if self._currentIdx is None:870 raise error.PyAsn1Error('Component not chosen')871 else:872 self._sizeSpec(' ')873 def _cloneComponentValues(self, myClone, cloneValueFlag):874 try:875 c = self.getComponent()876 except error.PyAsn1Error:877 pass878 else:879 if isinstance(c, Choice):880 tagSet = c.getEffectiveTagSet()881 else:882 tagSet = c.getTagSet()883 if isinstance(c, base.AbstractConstructedAsn1Item):884 myClone.setComponentByType(885 tagSet, c.clone(cloneValueFlag=cloneValueFlag)886 )887 else:888 myClone.setComponentByType(tagSet, c.clone())889 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):890 l = len(self._componentValues)891 if idx >= l:892 self._componentValues = self._componentValues + (idx-l+1)*[None]893 if self._currentIdx is not None:894 self._componentValues[self._currentIdx] = None895 if value is None:896 if self._componentValues[idx] is None:897 self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone()898 self._componentValuesSet = 1899 self._currentIdx = idx900 return self901 elif not isinstance(value, base.Asn1Item):902 value = self._componentType.getTypeByPosition(idx).clone(903 value=value904 )905 if verifyConstraints:906 if self._componentTypeLen:907 self._verifyComponent(idx, value)908 self._verifySubtypeSpec(value, idx) 909 self._componentValues[idx] = value910 self._currentIdx = idx911 self._componentValuesSet = 1912 return self913 def getMinTagSet(self):914 if self._tagSet:915 return self._tagSet916 else:917 return self._componentType.genMinTagSet()918 def getEffectiveTagSet(self):919 if self._tagSet:920 return self._tagSet921 else:922 c = self.getComponent()923 if isinstance(c, Choice):924 return c.getEffectiveTagSet()925 else:926 return c.getTagSet()927 def getTagMap(self):928 if self._tagSet:929 return Set.getTagMap(self)930 else:931 return Set.getComponentTagMap(self)932 def getComponent(self, innerFlag=0):933 if self._currentIdx is None:934 raise error.PyAsn1Error('Component not chosen')935 else:936 c = self._componentValues[self._currentIdx]937 if innerFlag and isinstance(c, Choice):938 return c.getComponent(innerFlag)939 else:940 return c941 def getName(self, innerFlag=0):942 if self._currentIdx is None:943 raise error.PyAsn1Error('Component not chosen')944 else:945 if innerFlag:946 c = self._componentValues[self._currentIdx]947 if isinstance(c, Choice):948 return c.getName(innerFlag)949 return self._componentType.getNameByPosition(self._currentIdx)950 def setDefaultComponents(self): pass951class Any(OctetString):952 tagSet = baseTagSet = tag.TagSet() # untagged953 typeId = 6954 def getTagMap(self):955 return tagmap.TagMap(956 { self.getTagSet(): self },957 { eoo.endOfOctets.getTagSet(): eoo.endOfOctets },958 self959 )960# XXX...

Full Screen

Full Screen

test_selectdatewidget.py

Source:test_selectdatewidget.py Github

copy

Full Screen

...442 self.assertEqual(443 w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'),444 '13-08-1899',445 )446 def test_format_value(self):447 valid_formats = [448 '2000-1-1', '2000-10-15', '2000-01-01',449 '2000-01-0', '2000-0-01', '2000-0-0',450 '0-01-01', '0-01-0', '0-0-01', '0-0-0',451 ]452 for value in valid_formats:453 year, month, day = (int(x) for x in value.split('-'))454 with self.subTest(value=value):455 self.assertEqual(self.widget.format_value(value), {'day': day, 'month': month, 'year': year})456 invalid_formats = [457 '2000-01-001', '2000-001-01', '2-01-01', '20-01-01', '200-01-01',458 '20000-01-01',459 ]460 for value in invalid_formats:461 with self.subTest(value=value):462 self.assertEqual(self.widget.format_value(value), {'day': None, 'month': None, 'year': None})463 def test_value_omitted_from_data(self):464 self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), True)465 self.assertIs(self.widget.value_omitted_from_data({'field_month': '12'}, {}, 'field'), False)466 self.assertIs(self.widget.value_omitted_from_data({'field_year': '2000'}, {}, 'field'), False)467 self.assertIs(self.widget.value_omitted_from_data({'field_day': '1'}, {}, 'field'), False)468 data = {'field_day': '1', 'field_month': '12', 'field_year': '2000'}469 self.assertIs(self.widget.value_omitted_from_data(data, {}, 'field'), False)470 @override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True)471 def test_years_rendered_without_separator(self):472 widget = SelectDateWidget(years=(2007,))473 self.check_html(widget, 'mydate', '', html=(474 """475 <select name="mydate_month" id="id_mydate_month">476 <option value="0">---</option>...

Full Screen

Full Screen

module_xml_grabber.py

Source:module_xml_grabber.py Github

copy

Full Screen

...24 if clean_files[value]['Division'] == 'IPM':25 clean_files[value]['Division'] = 'Industrial IPM'26 if clean_files[value]['Division'] == 'MOS_MOD':27 clean_files[value]['Division'] = 'MOSFET Modules'28 # clean_files = rename_value(clean_files,value,'Division','Old')29 clean_files = rename_section(clean_files, value, 'Vcc', 'vcc_value')30 clean_files = rename_section(clean_files, value, 'ThermalContactResistance', 'Module RTH DC')31 clean_files = rename_section(clean_files, value, 'RatedVoltage', 'Nameplate Voltage')32 clean_files = rename_section(clean_files, value, 'RatedCurrent', 'Nameplate Current')33 clean_files = rename_section(clean_files, value, 'BaseData', 'base_data_unknown')34 clean_files = rename_section(clean_files, value, 'Deprecation', 'deprecation_unknown')35 clean_files = rename_section(clean_files, value, 'ElementNumber', 'number_of_switches')36 clean_files = rename_section(clean_files, value, 'InterpolationDegree', 'interp_degree')37 clean_files = rename_section(clean_files, value, 'Lower', 'lower_unknown')38 clean_files = rename_section(clean_files, value, 'ModDate', 'mod_date')39 clean_files = rename_section(clean_files, value, 'ModUser', 'mod_user')40 clean_files = rename_section(clean_files, value, 'PathEn', 'path_en')41 clean_files = rename_section(clean_files, value, 'PathJa', 'path_ja')42 # clean_files = rename_section(clean_files, value, 'Priority', 'priority_unknown')...

Full Screen

Full Screen

fields.py

Source:fields.py Github

copy

Full Screen

1# Copyright 2013 Red Hat, Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may4# not use this file except in compliance with the License. You may obtain5# a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12# License for the specific language governing permissions and limitations13# under the License.14import abc15import datetime16import iso860117import netaddr18import six19from nova.i18n import _20from nova.network import model as network_model21from nova.openstack.common import timeutils22class KeyTypeError(TypeError):23 def __init__(self, expected, value):24 super(KeyTypeError, self).__init__(25 _('Key %(key)s must be of type %(expected)s not %(actual)s'26 ) % {'key': repr(value),27 'expected': expected.__name__,28 'actual': value.__class__.__name__,29 })30class ElementTypeError(TypeError):31 def __init__(self, expected, key, value):32 super(ElementTypeError, self).__init__(33 _('Element %(key)s:%(val)s must be of type %(expected)s'34 ' not %(actual)s'35 ) % {'key': key,36 'val': repr(value),37 'expected': expected,38 'actual': value.__class__.__name__,39 })40class AbstractFieldType(six.with_metaclass(abc.ABCMeta, object)):41 @abc.abstractmethod42 def coerce(self, obj, attr, value):43 """This is called to coerce (if possible) a value on assignment.44 This method should convert the value given into the designated type,45 or throw an exception if this is not possible.46 :param:obj: The NovaObject on which an attribute is being set47 :param:attr: The name of the attribute being set48 :param:value: The value being set49 :returns: A properly-typed value50 """51 pass52 @abc.abstractmethod53 def from_primitive(self, obj, attr, value):54 """This is called to deserialize a value.55 This method should deserialize a value from the form given by56 to_primitive() to the designated type.57 :param:obj: The NovaObject on which the value is to be set58 :param:attr: The name of the attribute which will hold the value59 :param:value: The serialized form of the value60 :returns: The natural form of the value61 """62 pass63 @abc.abstractmethod64 def to_primitive(self, obj, attr, value):65 """This is called to serialize a value.66 This method should serialize a value to the form expected by67 from_primitive().68 :param:obj: The NovaObject on which the value is set69 :param:attr: The name of the attribute holding the value70 :param:value: The natural form of the value71 :returns: The serialized form of the value72 """73 pass74 @abc.abstractmethod75 def describe(self):76 """Returns a string describing the type of the field."""77 pass78 @abc.abstractmethod79 def stringify(self, value):80 """Returns a short stringified version of a value."""81 pass82class FieldType(AbstractFieldType):83 @staticmethod84 def coerce(obj, attr, value):85 return value86 @staticmethod87 def from_primitive(obj, attr, value):88 return value89 @staticmethod90 def to_primitive(obj, attr, value):91 return value92 def describe(self):93 return self.__class__.__name__94 def stringify(self, value):95 return str(value)96class UnspecifiedDefault(object):97 pass98class Field(object):99 def __init__(self, field_type, nullable=False,100 default=UnspecifiedDefault, read_only=False):101 self._type = field_type102 self._nullable = nullable103 self._default = default104 self._read_only = read_only105 def __repr__(self):106 args = {107 'nullable': self._nullable,108 'default': self._default,109 }110 return '%s(%s)' % (self._type.__class__.__name__,111 ','.join(['%s=%s' % (k, v)112 for k, v in args.items()]))113 @property114 def nullable(self):115 return self._nullable116 @property117 def default(self):118 return self._default119 @property120 def read_only(self):121 return self._read_only122 def _null(self, obj, attr):123 if self.nullable:124 return None125 elif self._default != UnspecifiedDefault:126 # NOTE(danms): We coerce the default value each time the field127 # is set to None as our contract states that we'll let the type128 # examine the object and attribute name at that time.129 return self._type.coerce(obj, attr, self._default)130 else:131 raise ValueError(_("Field `%s' cannot be None") % attr)132 def coerce(self, obj, attr, value):133 """Coerce a value to a suitable type.134 This is called any time you set a value on an object, like:135 foo.myint = 1136 and is responsible for making sure that the value (1 here) is of137 the proper type, or can be sanely converted.138 This also handles the potentially nullable or defaultable139 nature of the field and calls the coerce() method on a140 FieldType to actually do the coercion.141 :param:obj: The object being acted upon142 :param:attr: The name of the attribute/field being set143 :param:value: The value being set144 :returns: The properly-typed value145 """146 if value is None:147 return self._null(obj, attr)148 else:149 return self._type.coerce(obj, attr, value)150 def from_primitive(self, obj, attr, value):151 """Deserialize a value from primitive form.152 This is responsible for deserializing a value from primitive153 into regular form. It calls the from_primitive() method on a154 FieldType to do the actual deserialization.155 :param:obj: The object being acted upon156 :param:attr: The name of the attribute/field being deserialized157 :param:value: The value to be deserialized158 :returns: The deserialized value159 """160 if value is None:161 return None162 else:163 return self._type.from_primitive(obj, attr, value)164 def to_primitive(self, obj, attr, value):165 """Serialize a value to primitive form.166 This is responsible for serializing a value to primitive167 form. It calls to_primitive() on a FieldType to do the actual168 serialization.169 :param:obj: The object being acted upon170 :param:attr: The name of the attribute/field being serialized171 :param:value: The value to be serialized172 :returns: The serialized value173 """174 if value is None:175 return None176 else:177 return self._type.to_primitive(obj, attr, value)178 def describe(self):179 """Return a short string describing the type of this field."""180 name = self._type.describe()181 prefix = self.nullable and 'Nullable' or ''182 return prefix + name183 def stringify(self, value):184 if value is None:185 return 'None'186 else:187 return self._type.stringify(value)188class String(FieldType):189 @staticmethod190 def coerce(obj, attr, value):191 # FIXME(danms): We should really try to avoid the need to do this192 if isinstance(value, (six.string_types, int, long, float,193 datetime.datetime)):194 return unicode(value)195 else:196 raise ValueError(_('A string is required here, not %s') %197 value.__class__.__name__)198 @staticmethod199 def stringify(value):200 return '\'%s\'' % value201class UUID(FieldType):202 @staticmethod203 def coerce(obj, attr, value):204 # FIXME(danms): We should actually verify the UUIDness here205 return str(value)206class Integer(FieldType):207 @staticmethod208 def coerce(obj, attr, value):209 return int(value)210class Float(FieldType):211 def coerce(self, obj, attr, value):212 return float(value)213class Boolean(FieldType):214 @staticmethod215 def coerce(obj, attr, value):216 return bool(value)217class DateTime(FieldType):218 @staticmethod219 def coerce(obj, attr, value):220 if isinstance(value, six.string_types):221 # NOTE(danms): Being tolerant of isotime strings here will help us222 # during our objects transition223 value = timeutils.parse_isotime(value)224 elif not isinstance(value, datetime.datetime):225 raise ValueError(_('A datetime.datetime is required here'))226 if value.utcoffset() is None:227 # NOTE(danms): Legacy objects from sqlalchemy are stored in UTC,228 # but are returned without a timezone attached.229 # As a transitional aid, assume a tz-naive object is in UTC.230 value = value.replace(tzinfo=iso8601.iso8601.Utc())231 return value232 def from_primitive(self, obj, attr, value):233 return self.coerce(obj, attr, timeutils.parse_isotime(value))234 @staticmethod235 def to_primitive(obj, attr, value):236 return timeutils.isotime(value)237 @staticmethod238 def stringify(value):239 return timeutils.isotime(value)240class IPAddress(FieldType):241 @staticmethod242 def coerce(obj, attr, value):243 try:244 return netaddr.IPAddress(value)245 except netaddr.AddrFormatError as e:246 raise ValueError(six.text_type(e))247 def from_primitive(self, obj, attr, value):248 return self.coerce(obj, attr, value)249 @staticmethod250 def to_primitive(obj, attr, value):251 return str(value)252class IPV4Address(IPAddress):253 @staticmethod254 def coerce(obj, attr, value):255 result = IPAddress.coerce(obj, attr, value)256 if result.version != 4:257 raise ValueError(_('Network "%s" is not valid') % value)258 return result259class IPV6Address(IPAddress):260 @staticmethod261 def coerce(obj, attr, value):262 result = IPAddress.coerce(obj, attr, value)263 if result.version != 6:264 raise ValueError(_('Network "%s" is not valid') % value)265 return result266class IPV4AndV6Address(IPAddress):267 @staticmethod268 def coerce(obj, attr, value):269 result = IPAddress.coerce(obj, attr, value)270 if result.version != 4 and result.version != 6:271 raise ValueError(_('Network "%s" is not valid') % value)272 return result273class IPNetwork(IPAddress):274 @staticmethod275 def coerce(obj, attr, value):276 try:277 return netaddr.IPNetwork(value)278 except netaddr.AddrFormatError as e:279 raise ValueError(six.text_type(e))280class IPV4Network(IPNetwork):281 @staticmethod282 def coerce(obj, attr, value):283 try:284 return netaddr.IPNetwork(value, version=4)285 except netaddr.AddrFormatError as e:286 raise ValueError(six.text_type(e))287class IPV6Network(IPNetwork):288 @staticmethod289 def coerce(obj, attr, value):290 try:291 return netaddr.IPNetwork(value, version=6)292 except netaddr.AddrFormatError as e:293 raise ValueError(six.text_type(e))294class CompoundFieldType(FieldType):295 def __init__(self, element_type, **field_args):296 self._element_type = Field(element_type, **field_args)297class List(CompoundFieldType):298 def coerce(self, obj, attr, value):299 if not isinstance(value, list):300 raise ValueError(_('A list is required here'))301 for index, element in enumerate(list(value)):302 value[index] = self._element_type.coerce(303 obj, '%s[%i]' % (attr, index), element)304 return value305 def to_primitive(self, obj, attr, value):306 return [self._element_type.to_primitive(obj, attr, x) for x in value]307 def from_primitive(self, obj, attr, value):308 return [self._element_type.from_primitive(obj, attr, x) for x in value]309 def stringify(self, value):310 return '[%s]' % (311 ','.join([self._element_type.stringify(x) for x in value]))312class Dict(CompoundFieldType):313 def coerce(self, obj, attr, value):314 if not isinstance(value, dict):315 raise ValueError(_('A dict is required here'))316 for key, element in value.items():317 if not isinstance(key, six.string_types):318 # NOTE(guohliu) In order to keep compatibility with python3319 # we need to use six.string_types rather than basestring here,320 # since six.string_types is a tuple, so we need to pass the321 # real type in.322 raise KeyTypeError(six.string_types[0], key)323 value[key] = self._element_type.coerce(324 obj, '%s["%s"]' % (attr, key), element)325 return value326 def to_primitive(self, obj, attr, value):327 primitive = {}328 for key, element in value.items():329 primitive[key] = self._element_type.to_primitive(330 obj, '%s["%s"]' % (attr, key), element)331 return primitive332 def from_primitive(self, obj, attr, value):333 concrete = {}334 for key, element in value.items():335 concrete[key] = self._element_type.from_primitive(336 obj, '%s["%s"]' % (attr, key), element)337 return concrete338 def stringify(self, value):339 return '{%s}' % (340 ','.join(['%s=%s' % (key, self._element_type.stringify(val))341 for key, val in sorted(value.items())]))342class Set(CompoundFieldType):343 def coerce(self, obj, attr, value):344 if not isinstance(value, set):345 raise ValueError(_('A set is required here'))346 coerced = set()347 for element in value:348 coerced.add(self._element_type.coerce(349 obj, '%s["%s"]' % (attr, element), element))350 return coerced351 def to_primitive(self, obj, attr, value):352 return tuple(353 self._element_type.to_primitive(obj, attr, x) for x in value)354 def from_primitive(self, obj, attr, value):355 return set([self._element_type.from_primitive(obj, attr, x)356 for x in value])357 def stringify(self, value):358 return 'set([%s])' % (359 ','.join([self._element_type.stringify(x) for x in value]))360class Object(FieldType):361 def __init__(self, obj_name, **kwargs):362 self._obj_name = obj_name363 super(Object, self).__init__(**kwargs)364 def coerce(self, obj, attr, value):365 try:366 obj_name = value.obj_name()367 except AttributeError:368 obj_name = ""369 if obj_name != self._obj_name:370 raise ValueError(_('An object of type %s is required here') %371 self._obj_name)372 return value373 @staticmethod374 def to_primitive(obj, attr, value):375 return value.obj_to_primitive()376 @staticmethod377 def from_primitive(obj, attr, value):378 # FIXME(danms): Avoid circular import from base.py379 from nova.objects import base as obj_base380 # NOTE (ndipanov): If they already got hydrated by the serializer, just381 # pass them back unchanged382 if isinstance(value, obj_base.NovaObject):383 return value384 return obj_base.NovaObject.obj_from_primitive(value, obj._context)385 def describe(self):386 return "Object<%s>" % self._obj_name387 def stringify(self, value):388 if 'uuid' in value.fields:389 ident = '(%s)' % (value.obj_attr_is_set('uuid') and value.uuid or390 'UNKNOWN')391 elif 'id' in value.fields:392 ident = '(%s)' % (value.obj_attr_is_set('id') and value.id or393 'UNKNOWN')394 else:395 ident = ''396 return '%s%s' % (self._obj_name, ident)397class NetworkModel(FieldType):398 @staticmethod399 def coerce(obj, attr, value):400 if isinstance(value, network_model.NetworkInfo):401 return value402 elif isinstance(value, six.string_types):403 # Hmm, do we need this?404 return network_model.NetworkInfo.hydrate(value)405 else:406 raise ValueError(_('A NetworkModel is required here'))407 @staticmethod408 def to_primitive(obj, attr, value):409 return value.json()410 @staticmethod411 def from_primitive(obj, attr, value):412 return network_model.NetworkInfo.hydrate(value)413 def stringify(self, value):414 return 'NetworkModel(%s)' % (415 ','.join([str(vif['id']) for vif in value]))416class AutoTypedField(Field):417 AUTO_TYPE = None418 def __init__(self, **kwargs):419 super(AutoTypedField, self).__init__(self.AUTO_TYPE, **kwargs)420class StringField(AutoTypedField):421 AUTO_TYPE = String()422class UUIDField(AutoTypedField):423 AUTO_TYPE = UUID()424class IntegerField(AutoTypedField):425 AUTO_TYPE = Integer()426class FloatField(AutoTypedField):427 AUTO_TYPE = Float()428class BooleanField(AutoTypedField):429 AUTO_TYPE = Boolean()430class DateTimeField(AutoTypedField):431 AUTO_TYPE = DateTime()432class IPAddressField(AutoTypedField):433 AUTO_TYPE = IPAddress()434class IPV4AddressField(AutoTypedField):435 AUTO_TYPE = IPV4Address()436class IPV6AddressField(AutoTypedField):437 AUTO_TYPE = IPV6Address()438class IPV4AndV6AddressField(AutoTypedField):439 AUTO_TYPE = IPV4AndV6Address()440class IPNetworkField(AutoTypedField):441 AUTO_TYPE = IPNetwork()442class IPV4NetworkField(AutoTypedField):443 AUTO_TYPE = IPV4Network()444class IPV6NetworkField(AutoTypedField):445 AUTO_TYPE = IPV6Network()446class DictOfStringsField(AutoTypedField):447 AUTO_TYPE = Dict(String())448class DictOfNullableStringsField(AutoTypedField):449 AUTO_TYPE = Dict(String(), nullable=True)450class ListOfStringsField(AutoTypedField):451 AUTO_TYPE = List(String())452class SetOfIntegersField(AutoTypedField):453 AUTO_TYPE = Set(Integer())454class ListOfDictOfNullableStringsField(AutoTypedField):455 AUTO_TYPE = List(Dict(String(), nullable=True))456class ObjectField(AutoTypedField):457 def __init__(self, objtype, **kwargs):458 self.AUTO_TYPE = Object(objtype)459 super(ObjectField, self).__init__(**kwargs)460class ListOfObjectsField(AutoTypedField):461 def __init__(self, objtype, **kwargs):462 self.AUTO_TYPE = List(Object(objtype))...

Full Screen

Full Screen

my_strategy_copy.py

Source:my_strategy_copy.py Github

copy

Full Screen

1# 将500的中文队名转为transfermkt的英文名2def is_between(value, low, up=float('inf')):3 if value >= low and value < up:4 return True5 else:6 return False7class My_strategy:8 def __init__(self):9 self.strategy_league = ['德甲', '英超', '法甲', '法乙', '英冠', '俄超', '比甲', '德乙', '乌超', '丹超', '英甲', '英乙', '西甲', '丹甲', '捷甲', '意乙', '西乙', '波甲', '芬超', '奥乙', '奥甲',10 '土超', '爱甲', '爱超', 'K1联赛', '挪超', '荷甲', '挪甲', 'K2联赛', 'J1联赛', '澳超', '中超', 'J2联赛', '瑞典超', '瑞典甲', '俄甲', '苏超', '瑞士超', '瑞士甲', '荷乙', '冰岛超',11 '葡超', '巴西甲', '墨超', '巴西乙', '葡甲', '阿甲']12 def get(self, league_name, value_ratio):13 if not league_name in self.strategy_league:14 return ''15 if league_name == '德甲':16 if is_between(value_ratio, 0.1, 0.3) or is_between(value_ratio, 0.6, 0.7):17 return 318 elif is_between(value_ratio, 5, 10):19 return 120 elif is_between(value_ratio, 0, 0.1):21 return 022 if league_name == '英超':23 if is_between(value_ratio, 0.5, 0.6) or is_between(value_ratio, 0.9, 1):24 return 325 elif is_between(value_ratio, 0.8, 0.9):26 return 127 elif is_between(value_ratio, 0, 0.1) or is_between(value_ratio, 1, 1.1) or is_between(value_ratio, 1.67, 2):28 return 029 if league_name == '法甲':30 if is_between(value_ratio, 0, 0.1):31 return 332 elif is_between(value_ratio, 0.7, 0.8) or is_between(value_ratio, 2.5, 3.33):33 return 034 if league_name == '法乙':35 if is_between(value_ratio, 1.43, 1.67):36 return 337 elif is_between(value_ratio, 0.2, 0.3):38 return 039 elif is_between(value_ratio, 0.1, 0.2):40 return 141 if league_name == '英冠':42 if is_between(value_ratio, 0.1, 0.3) or is_between(value_ratio, 10):43 return 344 if league_name == '俄超':45 if is_between(value_ratio, 0, 0.1) or is_between(value_ratio, 0.5, 0.6):46 return 047 elif is_between(value_ratio, 1, 1.1):48 return 349 elif is_between(value_ratio, 2, 2.5):50 return 151 if league_name == '比甲':52 if is_between(value_ratio, 2, 2.5):53 return 054 elif is_between(value_ratio, 0.2, 0.3):55 return 156 elif is_between(value_ratio, 0.8, 0.9):57 return 358 if league_name == '德乙':59 if is_between(value_ratio, 0.6, 0.7) or is_between(value_ratio, 1.67, 2.5):60 return 361 elif is_between(value_ratio, 0.7, 0.8):62 return 163 if league_name == '乌超':64 if is_between(value_ratio, 1.25, 1.43) or is_between(value_ratio, 3.33, 5):65 return 366 elif is_between(value_ratio, 0.6, 0.7) or is_between(value_ratio, 1.43, 1.67):67 return 168 elif is_between(value_ratio, 0.5, 0.6):69 return 070 if league_name == '丹超':71 if is_between(value_ratio, 5, 10):72 return 373 elif is_between(value_ratio, 0.9, 1):74 return 175 elif is_between(value_ratio, 0.1, 0.2) or is_between(value_ratio, 1.1, 1.25):76 return 077 if league_name == '英甲':78 if is_between(value_ratio, 0.2, 0.3):79 return 080 if league_name == '英乙':81 if is_between(value_ratio, 0, 0.1):82 return 083 if league_name == '西甲':84 if is_between(value_ratio, 0.1, 0.2):85 return 386 elif is_between(value_ratio, 0.2, 0.3):87 return 188 elif is_between(value_ratio, 1.67, 2):89 return 090 if league_name == '丹甲':91 if is_between(value_ratio, 0.3, 0.4):92 return 093 if league_name == '捷甲':94 if is_between(value_ratio, 0.4, 0.5):95 return 196 elif is_between(value_ratio, 5, 10):97 return 398 if league_name == '意乙':99 if is_between(value_ratio, 3.33, 10):100 return 3101 if league_name == '西乙':102 if is_between(value_ratio, 0.3, 0.4) or is_between(value_ratio, 5, 10):103 return 1104 elif is_between(value_ratio, 0.1, 0.2):105 return 0106 if league_name == '波甲':107 if is_between(value_ratio, 2.5, 3.33):108 return 0109 if league_name == '芬超':110 if is_between(value_ratio, 5, 10):111 return 3112 elif is_between(value_ratio, 1.43, 1.67):113 return 0114 if league_name == '奥乙':115 if is_between(value_ratio, 2.5, 3.33):116 return 3117 elif is_between(value_ratio, 0.6, 0.7):118 return 0119 if league_name == '奥甲':120 if is_between(value_ratio, 0.4, 0.5):121 return 3122 if league_name == '土超':123 if is_between(value_ratio, 2.5, 3.33):124 return 3125 if league_name == '爱甲':126 if is_between(value_ratio, 2.5, 3.33):127 return 3128 elif is_between(value_ratio, 0.9, 1):129 return 0130 if league_name == '爱超':131 if is_between(value_ratio, 10):132 return 3133 elif is_between(value_ratio, 0, 0.1):134 return 0135 if league_name == 'K1联赛':136 if is_between(value_ratio, 0, 0.1) or is_between(value_ratio, 0.4, 0.5) or is_between(value_ratio, 10):137 return 1138 elif is_between(value_ratio, 0.5, 0.6):139 return 0140 if league_name == '挪超':141 if is_between(value_ratio, 0.2, 0.3):142 return 0143 if league_name == '荷甲':144 if is_between(value_ratio, 0, 0.1):145 return 0146 if league_name == '挪甲':147 if is_between(value_ratio, 0, 0.1) or is_between(value_ratio, 1.1, 1.25):148 return 0149 if league_name == 'K2联赛':150 if is_between(value_ratio, 0.1, 0.3):151 return 3152 elif is_between(value_ratio, 1, 1.1):153 return 1154 if league_name == 'J1联赛':155 if is_between(value_ratio, 0.2, 0.4) or is_between(value_ratio, 1.1, 1.25):156 return 0157 if league_name == '澳超':158 if is_between(value_ratio, 1.67, 2):159 return 3160 elif is_between(value_ratio, 0.4, 0.5):161 return 0162 if league_name == '中超':163 if is_between(value_ratio, 1.1, 1.25):164 return 1165 if league_name == 'J2联赛':166 if is_between(value_ratio, 0.2, 0.3):167 return 0168 if league_name == '瑞典超':169 if is_between(value_ratio, 5, 10):170 return 3171 elif is_between(value_ratio, 1.67, 2):172 return 1173 elif is_between(value_ratio, 0.4, 0.5):174 return 0175 if league_name == '瑞典甲':176 if is_between(value_ratio, 10):177 return 3178 if league_name == '俄甲':179 if is_between(value_ratio, 0.2, 0.3) or is_between(value_ratio, 0.7, 0.8):180 return 0181 if league_name == '苏超':182 if is_between(value_ratio, 0.8, 1):183 return 0184 if league_name == '瑞士超':185 if is_between(value_ratio, 0.2, 0.3):186 return 1187 elif is_between(value_ratio, 2.5, 3.33):188 return 0189 if league_name == '瑞士甲':190 if is_between(value_ratio, 3.33, 5):191 return 3192 elif is_between(value_ratio, 0.2, 0.3):193 return 0194 if league_name == '荷乙':195 if is_between(value_ratio, 1.25, 1.43) or is_between(value_ratio, 2, 2.5):196 return 3197 elif is_between(value_ratio, 0.2, 0.3):198 return 0199 if league_name == '冰岛超':200 if is_between(value_ratio, 1, 1.1):201 return 1202 elif is_between(value_ratio, 10):203 return 3204 if league_name == '葡超':205 if is_between(value_ratio, 0.7, 0.8) or is_between(value_ratio, 1.1, 1.25):206 return 1207 elif is_between(value_ratio, 0.5, 0.6):208 return 0209 if league_name == '巴西甲':210 if is_between(value_ratio, 0, 0.1):211 return 0212 if league_name == '墨超':213 if is_between(value_ratio, 1.67, 2):214 return 1215 if league_name == '巴西乙':216 if is_between(value_ratio, 1.25, 1.43):217 return 1218 if league_name == '葡甲':219 if is_between(value_ratio, 0.2, 0.3) or is_between(value_ratio, 1.25, 1.43):220 return 0221 if league_name == '阿甲':222 if is_between(value_ratio, 1.1, 1.25):223 return 1224 elif is_between(value_ratio, 0.5, 0.6):225 return 0...

Full Screen

Full Screen

extra_types.py

Source:extra_types.py Github

copy

Full Screen

...55 VARIANTS = frozenset([messages.Variant.STRING])56 DEFAULT_VARIANT = messages.Variant.STRING57 type = datetime.date58def _ValidateJsonValue(json_value):59 entries = [(f, json_value.get_assigned_value(f.name))60 for f in json_value.all_fields()]61 assigned_entries = [(f, value)62 for f, value in entries if value is not None]63 if len(assigned_entries) != 1:64 raise exceptions.InvalidDataError(65 'Malformed JsonValue: %s' % json_value)66def _JsonValueToPythonValue(json_value):67 """Convert the given JsonValue to a json string."""68 util.Typecheck(json_value, JsonValue)69 _ValidateJsonValue(json_value)70 if json_value.is_null:71 return None72 entries = [(f, json_value.get_assigned_value(f.name))73 for f in json_value.all_fields()]74 assigned_entries = [(f, value)75 for f, value in entries if value is not None]76 field, value = assigned_entries[0]77 if not isinstance(field, messages.MessageField):78 return value79 elif field.message_type is JsonObject:80 return _JsonObjectToPythonValue(value)81 elif field.message_type is JsonArray:82 return _JsonArrayToPythonValue(value)83def _JsonObjectToPythonValue(json_value):84 util.Typecheck(json_value, JsonObject)85 return dict([(prop.key, _JsonValueToPythonValue(prop.value)) for prop86 in json_value.properties])...

Full Screen

Full Screen

converters.py

Source:converters.py Github

copy

Full Screen

1"""Adapters for converting to and from a type's value according to an2IConvertible protocol.3"""4from datetime import date, time5try:6 import decimal7 haveDecimal = True8except ImportError:9 haveDecimal = False10from zope.interface import implements11from gavo.imp.formal import iformal, validation12class _Adapter(object):13 def __init__(self, original):14 self.original = original15class NullConverter(_Adapter):16 implements( iformal.IStringConvertible )17 18 def fromType(self, value):19 if value is None:20 return None21 return value22 23 def toType(self, value):24 if value is None:25 return None26 return value27class NumberToStringConverter(_Adapter):28 implements( iformal.IStringConvertible )29 cast = None30 31 def fromType(self, value):32 if value is None:33 return None34 return str(value)35 36 def toType(self, value):37 if value is not None:38 value = value.strip()39 if not value:40 return None41 # "Cast" the value to the correct type. For some strange reason,42 # Python's decimal.Decimal type raises an ArithmeticError when it's43 # given a dodgy value.44 try:45 value = self.cast(value)46 except (ValueError, ArithmeticError):47 raise validation.FieldValidationError("Not a valid number")48 return value49 50 51class IntegerToStringConverter(NumberToStringConverter):52 cast = int53class FloatToStringConverter(NumberToStringConverter):54 cast = float55if haveDecimal:56 class DecimalToStringConverter(NumberToStringConverter):57 cast = decimal.Decimal58class BooleanToStringConverter(_Adapter):59 implements( iformal.IStringConvertible )60 61 def fromType(self, value):62 if value is None:63 return None64 if value:65 return 'True'66 return 'False'67 68 def toType(self, value):69 if value is not None:70 value = value.strip()71 if not value:72 return None73 if value not in ('True', 'False'):74 raise validation.FieldValidationError('%r should be either True or False'%value)75 return value == 'True'76 77 78class DateToStringConverter(_Adapter):79 implements( iformal.IStringConvertible )80 81 def fromType(self, value):82 if value is None:83 return None84 return value.isoformat()85 86 def toType(self, value):87 if value is not None:88 value = value.strip()89 if not value:90 return None91 return self.parseDate(value)92 93 def parseDate(self, value):94 try:95 y, m, d = [int(p) for p in value.split('-')]96 except ValueError:97 raise validation.FieldValidationError('Invalid date')98 try:99 value = date(y, m, d)100 except ValueError, e:101 raise validation.FieldValidationError('Invalid date: '+str(e))102 return value103class TimeToStringConverter(_Adapter):104 implements( iformal.IStringConvertible )105 106 def fromType(self, value):107 if value is None:108 return None109 if isinstance(value, basestring):110 return value111 return value.isoformat()112 113 def toType(self, value):114 if value is not None:115 value = value.strip()116 if not value:117 return None118 return self.parseTime(value)119 120 def parseTime(self, value):121 122 if '.' in value:123 value, ms = value.split('.')124 else:125 ms = 0126 127 try:128 parts = value.split(':') 129 if len(parts)<2 or len(parts)>3:130 raise ValueError()131 if len(parts) == 2:132 h, m = parts133 s = 0134 else:135 h, m, s = parts136 h, m, s, ms = int(h), int(m), int(s), int(ms)137 except:138 raise validation.FieldValidationError('Invalid time')139 140 try:141 value = time(h, m, s, ms)142 except ValueError, e:143 raise validation.FieldValidationError('Invalid time: '+str(e))144 145 return value146 147 148class DateToDateTupleConverter(_Adapter):149 implements( iformal.IDateTupleConvertible )150 151 def fromType(self, value):152 if value is None:153 return None, None, None154 return value.year, value.month, value.day155 156 def toType(self, value):157 if value is None:158 return None159 try:160 value = date(*value)161 except (TypeError, ValueError), e:162 raise validation.FieldValidationError('Invalid date: '+str(e))163 return value164 165class SequenceToStringConverter(_Adapter):166 implements( iformal.IStringConvertible)167 168 def fromType(self, value):169 if value is None:170 return None171 import cStringIO as StringIO172 import csv173 sf = StringIO.StringIO()174 writer = csv.writer(sf)175 writer.writerow(value)176 sf.seek(0,0)177 return sf.read().strip()178 179 180 def toType(self, value):181 if not value:182 return None183 import cStringIO as StringIO184 import csv185 186 sf = StringIO.StringIO()187 csvReader = csv.reader(sf)188 sf.write(value)189 sf.seek(0,0)...

Full Screen

Full Screen

data_compat.py

Source:data_compat.py Github

copy

Full Screen

...21from tensorboard.plugins.audio import metadata as audio_metadata22from tensorboard.plugins.image import metadata as image_metadata23from tensorboard.plugins.histogram import metadata as histogram_metadata24from tensorboard.plugins.scalar import metadata as scalar_metadata25def migrate_value(value):26 """Convert `value` to a new-style value, if necessary and possible.27 An "old-style" value is a value that uses any `value` field other than28 the `tensor` field. A "new-style" value is a value that uses the29 `tensor` field. TensorBoard continues to support old-style values on30 disk; this method converts them to new-style values so that further31 code need only deal with one data format.32 Arguments:33 value: A `tf.Summary.Value` object. This argument is not modified.34 Returns:35 If the `value` is an old-style value for which there is a new-style36 equivalent, the result is the new-style value. Otherwise---if the37 value is already new-style or does not yet have a new-style38 equivalent---the value will be returned unchanged.39 :type value: tf.Summary.Value40 :rtype: tf.Summary.Value41 """42 handler = {43 'histo': _migrate_histogram_value,44 'image': _migrate_image_value,45 'audio': _migrate_audio_value,46 'simple_value': _migrate_scalar_value,47 }.get(value.WhichOneof('value'))48 return handler(value) if handler else value49def _migrate_histogram_value(value):50 histogram_value = value.histo51 bucket_lefts = [histogram_value.min] + histogram_value.bucket_limit[:-1]52 bucket_rights = histogram_value.bucket_limit[:-1] + [histogram_value.max]53 bucket_counts = histogram_value.bucket54 buckets = np.array([bucket_lefts, bucket_rights, bucket_counts]).transpose()55 tensor_proto = tf.make_tensor_proto(buckets)56 summary_metadata = histogram_metadata.create_summary_metadata(57 display_name=value.metadata.display_name or value.tag,58 description=value.metadata.summary_description)59 return tf.Summary.Value(tag=value.tag,60 metadata=summary_metadata,61 tensor=tensor_proto)62def _migrate_image_value(value):63 image_value = value.image64 data = [tf.compat.as_bytes(str(image_value.width)),65 tf.compat.as_bytes(str(image_value.height)),66 tf.compat.as_bytes(image_value.encoded_image_string)]67 tensor_proto = tf.make_tensor_proto(data)68 summary_metadata = image_metadata.create_summary_metadata(69 display_name=value.metadata.display_name or value.tag,70 description=value.metadata.summary_description)71 return tf.Summary.Value(tag=value.tag,72 metadata=summary_metadata,73 tensor=tensor_proto)74def _migrate_audio_value(value):75 audio_value = value.audio76 data = [[audio_value.encoded_audio_string, b'']] # empty label77 tensor_proto = tf.make_tensor_proto(data)78 summary_metadata = audio_metadata.create_summary_metadata(79 display_name=value.metadata.display_name or value.tag,80 description=value.metadata.summary_description,81 encoding=audio_metadata.Encoding.Value('WAV'))82 return tf.Summary.Value(tag=value.tag,83 metadata=summary_metadata,84 tensor=tensor_proto)85def _migrate_scalar_value(value):86 scalar_value = value.simple_value87 tensor_proto = tf.make_tensor_proto(scalar_value)88 summary_metadata = scalar_metadata.create_summary_metadata(89 display_name=value.metadata.display_name or value.tag,90 description=value.metadata.summary_description)91 return tf.Summary.Value(tag=value.tag,92 metadata=summary_metadata,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const value = require('fast-check-monorepo');2console.log(value);3const value = require('fast-check-monorepo');4console.log(value);5const value = require('fast-check-monorepo');6console.log(value);7const value = require('fast-check-monorepo');8console.log(value);9const value = require('fast-check-monorepo');10console.log(value);11const value = require('fast-check-monorepo');12console.log(value);13const value = require('fast-check-monorepo');14console.log(value);15const value = require('fast-check-monorepo');16console.log(value);17const value = require('fast-check-monorepo');18console.log(value);19const value = require('fast-check-monorepo');20console.log(value);21const value = require('fast-check-monorepo');22console.log(value);23const value = require('fast-check-monorepo');24console.log(value);25const value = require('fast-check-monorepo');26console.log(value);27const value = require('fast-check-monorepo');28console.log(value);29const value = require('fast-check-mon

Full Screen

Using AI Code Generation

copy

Full Screen

1const { value } = require('fast-check-monorepo');2console.log(value);3const { value } = require('fast-check-monorepo');4console.log(value);5const { value } = require('fast-check-monorepo');6console.log(value);7const { value } = require('fast-check-monorepo');8console.log(value);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { value } = require("fast-check");2console.log(value);3const { value } = require("fast-check");4console.log(value);5const { value } = require("fast-check");6console.log(value);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { value } = require('@dubzzz/fast-check');2const { value } = require('fast-check');3const { value } = require('@dubzzz/fast-check');4const { value } = require('fast-check');5const { value } = require('@dubzzz/fast-check');6const { value } = require('fast-check');7const { value } = require('@dubzzz/fast-check');8const { value } = require('fast-check');9const { value } = require('@dubzzz/fast-check');10const { value } = require('fast-check');11const { value } = require('@dubzzz/fast-check');12const { value } = require('fast-check');13const { value } = require('@dubzzz/fast-check');14const { value } = require('fast-check');15const { value } = require('@dubzzz/fast-check');16const { value } = require('fast-check');17const { value } = require('@dubzzz/fast-check');18const { value } = require('fast-check');19const { value } = require('@dubzzz/fast

Full Screen

Using AI Code Generation

copy

Full Screen

1const { value } = require('fast-check-monorepo');2const { string } = require('fast-check-monorepo/lib/types/string');3const { number } = require('fast-check-monorepo/lib/types/number');4const { record } = require('fast-check-monorepo/lib/types/record');5const { tuple } = require('fast-check-monorepo/lib/types/tuple');6const { frequency } = require('fast-check-monorepo/lib/types/frequency');7const { fc } = require('fast-check-monorepo/lib/fast-check-default');8describe('test3', () => {9 it('should work', () => {10 const arb = frequency(11 { arbitrary: string(), weight: 1 },12 { arbitrary: number(), weight: 2 },13 { arbitrary: record({ a: string(), b: number() }), weight: 3 },14 { arbitrary: tuple(string(), number()), weight: 4 }15 );16 const v = value(arb, { seed: 42 });17 console.log(v);18 });19});20const { value } = require('fast-check-monorepo');21const { string } = require('fast-check-monorepo/lib/types/string');22const { number } = require('fast-check-monorepo/lib/types/number');23const { record } = require('fast-check-monorepo/lib/types/record');24const { tuple } = require('fast-check-monorepo/lib/types/tuple');25const { frequency } = require('fast-check-monorepo/lib/types/frequency');26const { fc } = require('fast-check-monorepo/lib/fast-check-default');27describe('test4', () => {28 it('should work', () => {29 const arb = frequency(30 { arbitrary: string(), weight: 1 },31 { arbitrary: number(), weight: 2 },32 { arbitrary: record({ a: string(), b: number() }), weight: 3 },33 { arbitrary: tuple(string(), number()), weight: 4 }34 );35 const v = value(arb, { seed: 42 });36 console.log(v);37 });38});39const { value } = require('fast-check-monorepo');40const { string } = require('fast-check-monore

Full Screen

Using AI Code Generation

copy

Full Screen

1var value = require('fast-check-monorepo').value;2var value = require('fast-check-monorepo').value;3var value = require('fast-check-monorepo').value;4var value = require('fast-check-monorepo').value;5var value = require('fast-check-monorepo').value;6var value = require('fast-check-monorepo').value;7var value = require('fast-check-monorepo').value;8var value = require('fast-check-monorepo').value;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { value } = require('fast-check-monorepo');2const { integer } = require('fast-check-monorepo/lib/arbitrary/IntegerArbitrary.js');3const { stringOf } = require('fast-check-monorepo/lib/arbitrary/StringArbitrary.js');4const { frequency } = require('fast-check-monorepo/lib/arbitrary/FrequencyArbitrary.js');5const { oneof } = require('fast-check-monorepo/lib/arbitrary/OneOfArbitrary.js');6const { record } = require('fast-check-monorepo/lib/arbitrary/RecordArbitrary.js');7const { tuple } = require('fast-check-monorepo/lib/arbitrary/TupleArbitrary.js');8const { option } = require('fast-check-monorepo/lib/arbitrary/OptionArbitrary.js');9const { array } = require('fast-check-monorepo/lib/arbitrary/ArrayArbitrary.js');10const { dictionary } = require('fast-check-monorepo/lib/arbitrary/DictionaryArbitrary.js');11const { set } = require('fast-check-monorepo/lib/arbitrary/SetArbitrary.js');12const { map } = require('fast-check-monorepo/lib/arbitrary/MapArbitrary.js');13const { date } = require('fast-check-monorepo/lib/arbitrary/DateArbitrary.js');14const { bigIntN } = require('fast-check-monorepo/lib/arbitrary/BigIntArbitrary.js');15const { bigUintN } = require('fast-check-monorepo/lib/arbitrary/BigIntArbitrary.js');16const { float } = require('fast-check-monorepo/lib/arbitrary/FloatArbitrary.js');17const { double } = require('fast-check-monorepo/lib/arbitrary/DoubleArbitrary.js');18const { char } = require('fast-check-monorepo/lib/arbitrary/CharacterArbitrary.js');19const { fullUnicode } = require('fast-check-monorepo/lib/arbitrary/FullUnicodeArbitrary.js');20const { unicode } = require('fast-check-monorepo/lib/arbitrary/UnicodeArbitrary.js');21const { ascii } = require('fast-check-monorepo/lib/arbitrary/AsciiArbitrary.js');22const { base64 } = require('fast-check-monorepo/lib/arbitrary/Base64Arbitrary.js');23const { base64String } = require('fast-check-monorepo/lib/arbitrary/Base64StringArbitrary.js');24const { hexa } = require('fast-check-monore

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2console.log(fc.value());3const fc = require('fast-check');4console.log(fc.value());5console.log(require.cache);6{ '/Users/username/Downloads/require-cache/test1.js': Module { id: '/Users/username/Downloads/require-cache/test1.js', path: '/Users/username/Downloads/require-cache', exports: {}, parent: null, filename: '/Users/username/Downloads/require-cache/test1.js', loaded: false, children: [], paths: [ '/Users/username/Downloads/require-cache/node_modules', '/Users/username/Downloads/node_modules', '/Users/username/node_modules', '/Users/node_modules', '/node_modules' ] }, '/Users/username/Downloads/require-cache/test2.js': Module { id: '/Users/username/Downloads/require-cache/test2.js', path: '/Users/username/Downloads/require-cache', exports: {}, parent: null, filename: '/Users/username/Downloads/require-cache/test2.js', loaded: false, children: [], paths: [ '/Users/username/Downloads/require-cache/node_modules', '/Users/username/Downloads/node_modules', '/Users/username/node_modules', '/Users/node_modules', '/node_modules' ] }, '/Users/username/Downloads/require-cache/test3.js': Module { id: '/Users/username/Downloads/require-cache/test3.js', path: '/Users/username/Downloads/require-cache', exports: {}, parent: null, filename: '/Users/username/Downloads/require-cache/test3.js', loaded:

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fast-check-monorepo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful