partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
verilogTypeOfSig
Check if is register or wire
hwt/serializer/verilog/utils.py
def verilogTypeOfSig(signalItem): """ Check if is register or wire """ driver_cnt = len(signalItem.drivers) if signalItem._const or driver_cnt > 1 or\ arr_any(signalItem.drivers, _isEventDependentDriver): return SIGNAL_TYPE.REG else: if driver_cnt == 1: d = signalItem.drivers[0] if not isinstance(d, (Assignment, PortItem)): return SIGNAL_TYPE.REG return SIGNAL_TYPE.WIRE
def verilogTypeOfSig(signalItem): """ Check if is register or wire """ driver_cnt = len(signalItem.drivers) if signalItem._const or driver_cnt > 1 or\ arr_any(signalItem.drivers, _isEventDependentDriver): return SIGNAL_TYPE.REG else: if driver_cnt == 1: d = signalItem.drivers[0] if not isinstance(d, (Assignment, PortItem)): return SIGNAL_TYPE.REG return SIGNAL_TYPE.WIRE
[ "Check", "if", "is", "register", "or", "wire" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/verilog/utils.py#L16-L30
[ "def", "verilogTypeOfSig", "(", "signalItem", ")", ":", "driver_cnt", "=", "len", "(", "signalItem", ".", "drivers", ")", "if", "signalItem", ".", "_const", "or", "driver_cnt", ">", "1", "or", "arr_any", "(", "signalItem", ".", "drivers", ",", "_isEventDependentDriver", ")", ":", "return", "SIGNAL_TYPE", ".", "REG", "else", ":", "if", "driver_cnt", "==", "1", ":", "d", "=", "signalItem", ".", "drivers", "[", "0", "]", "if", "not", "isinstance", "(", "d", ",", "(", "Assignment", ",", "PortItem", ")", ")", ":", "return", "SIGNAL_TYPE", ".", "REG", "return", "SIGNAL_TYPE", ".", "WIRE" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.toHdlConversion
:param top: object which is represenation of design :param topName: name which should be used for ipcore :param saveTo: path of directory where generated files should be stored :return: list of file namens in correct compile order
hwt/serializer/ip_packager.py
def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]: """ :param top: object which is represenation of design :param topName: name which should be used for ipcore :param saveTo: path of directory where generated files should be stored :return: list of file namens in correct compile order """ return toRtl(top, saveTo=saveTo, name=topName, serializer=self.serializer, targetPlatform=self.targetPlatform)
def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]: """ :param top: object which is represenation of design :param topName: name which should be used for ipcore :param saveTo: path of directory where generated files should be stored :return: list of file namens in correct compile order """ return toRtl(top, saveTo=saveTo, name=topName, serializer=self.serializer, targetPlatform=self.targetPlatform)
[ ":", "param", "top", ":", "object", "which", "is", "represenation", "of", "design", ":", "param", "topName", ":", "name", "which", "should", "be", "used", "for", "ipcore", ":", "param", "saveTo", ":", "path", "of", "directory", "where", "generated", "files", "should", "be", "stored" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L64-L77
[ "def", "toHdlConversion", "(", "self", ",", "top", ",", "topName", ":", "str", ",", "saveTo", ":", "str", ")", "->", "List", "[", "str", "]", ":", "return", "toRtl", "(", "top", ",", "saveTo", "=", "saveTo", ",", "name", "=", "topName", ",", "serializer", "=", "self", ".", "serializer", ",", "targetPlatform", "=", "self", ".", "targetPlatform", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.serializeType
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Can not seraialize hdl type %r into" "ipcore format" % (hdlType)) return VhdlSerializer.HdlType(hdlType, VhdlSerializer.getBaseContext())
def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Can not seraialize hdl type %r into" "ipcore format" % (hdlType)) return VhdlSerializer.HdlType(hdlType, VhdlSerializer.getBaseContext())
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L132-L142
[ "def", "serializeType", "(", "self", ",", "hdlType", ":", "HdlType", ")", "->", "str", ":", "def", "createTmpVar", "(", "suggestedName", ",", "dtype", ")", ":", "raise", "NotImplementedError", "(", "\"Can not seraialize hdl type %r into\"", "\"ipcore format\"", "%", "(", "hdlType", ")", ")", "return", "VhdlSerializer", ".", "HdlType", "(", "hdlType", ",", "VhdlSerializer", ".", "getBaseContext", "(", ")", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.getVectorFromType
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]: """ :see: doc of method on parent class """ if dtype == BIT: return False elif isinstance(dtype, Bits): return [evalParam(dtype.width) - 1, hInt(0)]
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]: """ :see: doc of method on parent class """ if dtype == BIT: return False elif isinstance(dtype, Bits): return [evalParam(dtype.width) - 1, hInt(0)]
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L145-L152
[ "def", "getVectorFromType", "(", "self", ",", "dtype", ")", "->", "Union", "[", "bool", ",", "None", ",", "Tuple", "[", "int", ",", "int", "]", "]", ":", "if", "dtype", "==", "BIT", ":", "return", "False", "elif", "isinstance", "(", "dtype", ",", "Bits", ")", ":", "return", "[", "evalParam", "(", "dtype", ".", "width", ")", "-", "1", ",", "hInt", "(", "0", ")", "]" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.getExprVal
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def getExprVal(self, val, do_eval=False): """ :see: doc of method on parent class """ ctx = VhdlSerializer.getBaseContext() def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Width value can not be converted do ipcore format (%r)", val) ctx.createTmpVarFn = createTmpVar if do_eval: val = val.staticEval() val = VivadoTclExpressionSerializer.asHdl(val, ctx) return val
def getExprVal(self, val, do_eval=False): """ :see: doc of method on parent class """ ctx = VhdlSerializer.getBaseContext() def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Width value can not be converted do ipcore format (%r)", val) ctx.createTmpVarFn = createTmpVar if do_eval: val = val.staticEval() val = VivadoTclExpressionSerializer.asHdl(val, ctx) return val
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L183-L198
[ "def", "getExprVal", "(", "self", ",", "val", ",", "do_eval", "=", "False", ")", ":", "ctx", "=", "VhdlSerializer", ".", "getBaseContext", "(", ")", "def", "createTmpVar", "(", "suggestedName", ",", "dtype", ")", ":", "raise", "NotImplementedError", "(", "\"Width value can not be converted do ipcore format (%r)\"", ",", "val", ")", "ctx", ".", "createTmpVarFn", "=", "createTmpVar", "if", "do_eval", ":", "val", "=", "val", ".", "staticEval", "(", ")", "val", "=", "VivadoTclExpressionSerializer", ".", "asHdl", "(", "val", ",", "ctx", ")", "return", "val" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.getTypeWidth
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]: """ :see: doc of method on parent class """ width = dtype.width if isinstance(width, int): widthStr = str(width) else: widthStr = self.getExprVal(width, do_eval=do_eval) return width, widthStr, False
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]: """ :see: doc of method on parent class """ width = dtype.width if isinstance(width, int): widthStr = str(width) else: widthStr = self.getExprVal(width, do_eval=do_eval) return width, widthStr, False
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L201-L211
[ "def", "getTypeWidth", "(", "self", ",", "dtype", ":", "HdlType", ",", "do_eval", "=", "False", ")", "->", "Tuple", "[", "int", ",", "Union", "[", "int", ",", "RtlSignal", "]", ",", "bool", "]", ":", "width", "=", "dtype", ".", "width", "if", "isinstance", "(", "width", ",", "int", ")", ":", "widthStr", "=", "str", "(", "width", ")", "else", ":", "widthStr", "=", "self", ".", "getExprVal", "(", "width", ",", "do_eval", "=", "do_eval", ")", "return", "width", ",", "widthStr", ",", "False" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.getObjDebugName
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str: """ :see: doc of method on parent class """ return obj._getFullName()
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str: """ :see: doc of method on parent class """ return obj._getFullName()
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L214-L218
[ "def", "getObjDebugName", "(", "self", ",", "obj", ":", "Union", "[", "Interface", ",", "Unit", ",", "Param", "]", ")", "->", "str", ":", "return", "obj", ".", "_getFullName", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
IpPackager.serialzeValueToTCL
:see: doc of method on parent class
hwt/serializer/ip_packager.py
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: """ :see: doc of method on parent class """ if isinstance(val, int): val = hInt(val) if do_eval: val = val.staticEval() if isinstance(val, RtlSignalBase): ctx = VivadoTclExpressionSerializer.getBaseContext() tclVal = VivadoTclExpressionSerializer.asHdl(val, ctx) tclValVal = VivadoTclExpressionSerializer.asHdl( val.staticEval()) return tclVal, tclValVal, False else: tclVal = VivadoTclExpressionSerializer.asHdl(val, None) return tclVal, tclVal, True
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: """ :see: doc of method on parent class """ if isinstance(val, int): val = hInt(val) if do_eval: val = val.staticEval() if isinstance(val, RtlSignalBase): ctx = VivadoTclExpressionSerializer.getBaseContext() tclVal = VivadoTclExpressionSerializer.asHdl(val, ctx) tclValVal = VivadoTclExpressionSerializer.asHdl( val.staticEval()) return tclVal, tclValVal, False else: tclVal = VivadoTclExpressionSerializer.asHdl(val, None) return tclVal, tclVal, True
[ ":", "see", ":", "doc", "of", "method", "on", "parent", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/ip_packager.py#L221-L239
[ "def", "serialzeValueToTCL", "(", "self", ",", "val", ",", "do_eval", "=", "False", ")", "->", "Tuple", "[", "str", ",", "str", ",", "bool", "]", ":", "if", "isinstance", "(", "val", ",", "int", ")", ":", "val", "=", "hInt", "(", "val", ")", "if", "do_eval", ":", "val", "=", "val", ".", "staticEval", "(", ")", "if", "isinstance", "(", "val", ",", "RtlSignalBase", ")", ":", "ctx", "=", "VivadoTclExpressionSerializer", ".", "getBaseContext", "(", ")", "tclVal", "=", "VivadoTclExpressionSerializer", ".", "asHdl", "(", "val", ",", "ctx", ")", "tclValVal", "=", "VivadoTclExpressionSerializer", ".", "asHdl", "(", "val", ".", "staticEval", "(", ")", ")", "return", "tclVal", ",", "tclValVal", ",", "False", "else", ":", "tclVal", "=", "VivadoTclExpressionSerializer", ".", "asHdl", "(", "val", ",", "None", ")", "return", "tclVal", ",", "tclVal", ",", "True" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
nameAvailabilityCheck
Check if not redefining property on obj
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def nameAvailabilityCheck(obj, propName, prop): """ Check if not redefining property on obj """ if getattr(obj, propName, None) is not None: raise IntfLvlConfErr("%r already has property %s old:%s new:%s" % (obj, propName, repr(getattr(obj, propName)), prop))
def nameAvailabilityCheck(obj, propName, prop): """ Check if not redefining property on obj """ if getattr(obj, propName, None) is not None: raise IntfLvlConfErr("%r already has property %s old:%s new:%s" % (obj, propName, repr(getattr(obj, propName)), prop))
[ "Check", "if", "not", "redefining", "property", "on", "obj" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L11-L17
[ "def", "nameAvailabilityCheck", "(", "obj", ",", "propName", ",", "prop", ")", ":", "if", "getattr", "(", "obj", ",", "propName", ",", "None", ")", "is", "not", "None", ":", "raise", "IntfLvlConfErr", "(", "\"%r already has property %s old:%s new:%s\"", "%", "(", "obj", ",", "propName", ",", "repr", "(", "getattr", "(", "obj", ",", "propName", ")", ")", ",", "prop", ")", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._registerParameter
Register Param object on interface level object
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _registerParameter(self, pName, parameter) -> None: """ Register Param object on interface level object """ nameAvailabilityCheck(self, pName, parameter) # resolve name in this scope try: hasName = parameter._name is not None except AttributeError: hasName = False if not hasName: parameter._name = pName # add name in this scope parameter._registerScope(pName, self) if parameter.hasGenericName: parameter.name = pName if parameter._parent is None: parameter._parent = self self._params.append(parameter)
def _registerParameter(self, pName, parameter) -> None: """ Register Param object on interface level object """ nameAvailabilityCheck(self, pName, parameter) # resolve name in this scope try: hasName = parameter._name is not None except AttributeError: hasName = False if not hasName: parameter._name = pName # add name in this scope parameter._registerScope(pName, self) if parameter.hasGenericName: parameter.name = pName if parameter._parent is None: parameter._parent = self self._params.append(parameter)
[ "Register", "Param", "object", "on", "interface", "level", "object" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L143-L164
[ "def", "_registerParameter", "(", "self", ",", "pName", ",", "parameter", ")", "->", "None", ":", "nameAvailabilityCheck", "(", "self", ",", "pName", ",", "parameter", ")", "# resolve name in this scope", "try", ":", "hasName", "=", "parameter", ".", "_name", "is", "not", "None", "except", "AttributeError", ":", "hasName", "=", "False", "if", "not", "hasName", ":", "parameter", ".", "_name", "=", "pName", "# add name in this scope", "parameter", ".", "_registerScope", "(", "pName", ",", "self", ")", "if", "parameter", ".", "hasGenericName", ":", "parameter", ".", "name", "=", "pName", "if", "parameter", ".", "_parent", "is", "None", ":", "parameter", ".", "_parent", "=", "self", "self", ".", "_params", ".", "append", "(", "parameter", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._paramsShared
Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with "self" there :param exclude: params which should not be shared :param prefix: prefix which should be added to name of child parameters before parameter name matching
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _paramsShared(self, exclude=None, prefix="") -> MakeParamsShared: """ Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with "self" there :param exclude: params which should not be shared :param prefix: prefix which should be added to name of child parameters before parameter name matching """ return MakeParamsShared(self, exclude=exclude, prefix=prefix)
def _paramsShared(self, exclude=None, prefix="") -> MakeParamsShared: """ Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with "self" there :param exclude: params which should not be shared :param prefix: prefix which should be added to name of child parameters before parameter name matching """ return MakeParamsShared(self, exclude=exclude, prefix=prefix)
[ "Auto", "-", "propagate", "params", "by", "name", "to", "child", "components", "and", "interfaces", "Usage", ":" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L166-L180
[ "def", "_paramsShared", "(", "self", ",", "exclude", "=", "None", ",", "prefix", "=", "\"\"", ")", "->", "MakeParamsShared", ":", "return", "MakeParamsShared", "(", "self", ",", "exclude", "=", "exclude", ",", "prefix", "=", "prefix", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._make_association
Associate this object with specified clk/rst
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _make_association(self, clk=None, rst=None) -> None: """ Associate this object with specified clk/rst """ if clk is not None: assert self._associatedClk is None self._associatedClk = clk if rst is not None: assert self._associatedRst is None self._associatedRst = rst
def _make_association(self, clk=None, rst=None) -> None: """ Associate this object with specified clk/rst """ if clk is not None: assert self._associatedClk is None self._associatedClk = clk if rst is not None: assert self._associatedRst is None self._associatedRst = rst
[ "Associate", "this", "object", "with", "specified", "clk", "/", "rst" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L182-L192
[ "def", "_make_association", "(", "self", ",", "clk", "=", "None", ",", "rst", "=", "None", ")", "->", "None", ":", "if", "clk", "is", "not", "None", ":", "assert", "self", ".", "_associatedClk", "is", "None", "self", ".", "_associatedClk", "=", "clk", "if", "rst", "is", "not", "None", ":", "assert", "self", ".", "_associatedRst", "is", "None", "self", ".", "_associatedRst", "=", "rst" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._updateParamsFrom
Update all parameters which are defined on self from otherObj :param otherObj: other object which Param instances should be updated :param updater: updater function(self, myParameter, onOtherParameterName, otherParameter) :param exclude: iterable of parameter on otherObj object which should be excluded :param prefix: prefix which should be added to name of paramters of this object before matching parameter name on parent
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None: """ Update all parameters which are defined on self from otherObj :param otherObj: other object which Param instances should be updated :param updater: updater function(self, myParameter, onOtherParameterName, otherParameter) :param exclude: iterable of parameter on otherObj object which should be excluded :param prefix: prefix which should be added to name of paramters of this object before matching parameter name on parent """ excluded = set() if exclude is not None: exclude = set(exclude) for myP in self._params: pPName = prefix + myP._scopes[self][1] try: otherP = getattr(otherObj, pPName) if not isinstance(otherP, Param): continue except AttributeError: continue if exclude and otherP in exclude: excluded.add(otherP) continue updater(self, myP, otherP) if exclude is not None: # assert that what should be excluded really exists assert excluded == exclude
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None: """ Update all parameters which are defined on self from otherObj :param otherObj: other object which Param instances should be updated :param updater: updater function(self, myParameter, onOtherParameterName, otherParameter) :param exclude: iterable of parameter on otherObj object which should be excluded :param prefix: prefix which should be added to name of paramters of this object before matching parameter name on parent """ excluded = set() if exclude is not None: exclude = set(exclude) for myP in self._params: pPName = prefix + myP._scopes[self][1] try: otherP = getattr(otherObj, pPName) if not isinstance(otherP, Param): continue except AttributeError: continue if exclude and otherP in exclude: excluded.add(otherP) continue updater(self, myP, otherP) if exclude is not None: # assert that what should be excluded really exists assert excluded == exclude
[ "Update", "all", "parameters", "which", "are", "defined", "on", "self", "from", "otherObj" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L213-L243
[ "def", "_updateParamsFrom", "(", "self", ",", "otherObj", ":", "\"PropDeclrCollector\"", ",", "updater", ",", "exclude", ":", "set", ",", "prefix", ":", "str", ")", "->", "None", ":", "excluded", "=", "set", "(", ")", "if", "exclude", "is", "not", "None", ":", "exclude", "=", "set", "(", "exclude", ")", "for", "myP", "in", "self", ".", "_params", ":", "pPName", "=", "prefix", "+", "myP", ".", "_scopes", "[", "self", "]", "[", "1", "]", "try", ":", "otherP", "=", "getattr", "(", "otherObj", ",", "pPName", ")", "if", "not", "isinstance", "(", "otherP", ",", "Param", ")", ":", "continue", "except", "AttributeError", ":", "continue", "if", "exclude", "and", "otherP", "in", "exclude", ":", "excluded", ".", "add", "(", "otherP", ")", "continue", "updater", "(", "self", ",", "myP", ",", "otherP", ")", "if", "exclude", "is", "not", "None", ":", "# assert that what should be excluded really exists", "assert", "excluded", "==", "exclude" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._registerUnit
Register unit object on interface level object
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _registerUnit(self, uName, unit): """ Register unit object on interface level object """ nameAvailabilityCheck(self, uName, unit) assert unit._parent is None unit._parent = self unit._name = uName self._units.append(unit)
def _registerUnit(self, uName, unit): """ Register unit object on interface level object """ nameAvailabilityCheck(self, uName, unit) assert unit._parent is None unit._parent = self unit._name = uName self._units.append(unit)
[ "Register", "unit", "object", "on", "interface", "level", "object" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L247-L255
[ "def", "_registerUnit", "(", "self", ",", "uName", ",", "unit", ")", ":", "nameAvailabilityCheck", "(", "self", ",", "uName", ",", "unit", ")", "assert", "unit", ".", "_parent", "is", "None", "unit", ".", "_parent", "=", "self", "unit", ".", "_name", "=", "uName", "self", ".", "_units", ".", "append", "(", "unit", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._registerInterface
Register interface object on interface level object
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _registerInterface(self, iName, intf, isPrivate=False): """ Register interface object on interface level object """ nameAvailabilityCheck(self, iName, intf) assert intf._parent is None intf._parent = self intf._name = iName intf._ctx = self._ctx if isPrivate: self._private_interfaces.append(intf) intf._isExtern = False else: self._interfaces.append(intf) intf._isExtern = True
def _registerInterface(self, iName, intf, isPrivate=False): """ Register interface object on interface level object """ nameAvailabilityCheck(self, iName, intf) assert intf._parent is None intf._parent = self intf._name = iName intf._ctx = self._ctx if isPrivate: self._private_interfaces.append(intf) intf._isExtern = False else: self._interfaces.append(intf) intf._isExtern = True
[ "Register", "interface", "object", "on", "interface", "level", "object" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L258-L273
[ "def", "_registerInterface", "(", "self", ",", "iName", ",", "intf", ",", "isPrivate", "=", "False", ")", ":", "nameAvailabilityCheck", "(", "self", ",", "iName", ",", "intf", ")", "assert", "intf", ".", "_parent", "is", "None", "intf", ".", "_parent", "=", "self", "intf", ".", "_name", "=", "iName", "intf", ".", "_ctx", "=", "self", ".", "_ctx", "if", "isPrivate", ":", "self", ".", "_private_interfaces", ".", "append", "(", "intf", ")", "intf", ".", "_isExtern", "=", "False", "else", ":", "self", ".", "_interfaces", ".", "append", "(", "intf", ")", "intf", ".", "_isExtern", "=", "True" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._registerArray
Register array of items on interface level object
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _registerArray(self, name, items): """ Register array of items on interface level object """ items._parent = self items._name = name for i, item in enumerate(items): setattr(self, "%s_%d" % (name, i), item)
def _registerArray(self, name, items): """ Register array of items on interface level object """ items._parent = self items._name = name for i, item in enumerate(items): setattr(self, "%s_%d" % (name, i), item)
[ "Register", "array", "of", "items", "on", "interface", "level", "object" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L289-L296
[ "def", "_registerArray", "(", "self", ",", "name", ",", "items", ")", ":", "items", ".", "_parent", "=", "self", "items", ".", "_name", "=", "name", "for", "i", ",", "item", "in", "enumerate", "(", "items", ")", ":", "setattr", "(", "self", ",", "\"%s_%d\"", "%", "(", "name", ",", "i", ")", ",", "item", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PropDeclrCollector._registerUnitInImpl
:attention: unit has to be parametrized before it is registered (some components can change interface by parametrization)
hwt/synthesizer/interfaceLevel/propDeclrCollector.py
def _registerUnitInImpl(self, uName, u): """ :attention: unit has to be parametrized before it is registered (some components can change interface by parametrization) """ self._registerUnit(uName, u) u._loadDeclarations() self._lazyLoaded.extend(u._toRtl(self._targetPlatform)) u._signalsForMyEntity(self._ctx, "sig_" + uName)
def _registerUnitInImpl(self, uName, u): """ :attention: unit has to be parametrized before it is registered (some components can change interface by parametrization) """ self._registerUnit(uName, u) u._loadDeclarations() self._lazyLoaded.extend(u._toRtl(self._targetPlatform)) u._signalsForMyEntity(self._ctx, "sig_" + uName)
[ ":", "attention", ":", "unit", "has", "to", "be", "parametrized", "before", "it", "is", "registered", "(", "some", "components", "can", "change", "interface", "by", "parametrization", ")" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/interfaceLevel/propDeclrCollector.py#L306-L314
[ "def", "_registerUnitInImpl", "(", "self", ",", "uName", ",", "u", ")", ":", "self", ".", "_registerUnit", "(", "uName", ",", "u", ")", "u", ".", "_loadDeclarations", "(", ")", "self", ".", "_lazyLoaded", ".", "extend", "(", "u", ".", "_toRtl", "(", "self", ".", "_targetPlatform", ")", ")", "u", ".", "_signalsForMyEntity", "(", "self", ".", "_ctx", ",", "\"sig_\"", "+", "uName", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
RtlSignal.singleDriver
Returns a first driver if signal has only one driver.
hwt/synthesizer/rtlLevel/rtlSignal.py
def singleDriver(self): """ Returns a first driver if signal has only one driver. """ # [TODO] no driver exception drv_cnt = len(self.drivers) if not drv_cnt: raise NoDriverErr(self) elif drv_cnt != 1: raise MultipleDriversErr(self) return self.drivers[0]
def singleDriver(self): """ Returns a first driver if signal has only one driver. """ # [TODO] no driver exception drv_cnt = len(self.drivers) if not drv_cnt: raise NoDriverErr(self) elif drv_cnt != 1: raise MultipleDriversErr(self) return self.drivers[0]
[ "Returns", "a", "first", "driver", "if", "signal", "has", "only", "one", "driver", "." ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/rtlLevel/rtlSignal.py#L106-L117
[ "def", "singleDriver", "(", "self", ")", ":", "# [TODO] no driver exception", "drv_cnt", "=", "len", "(", "self", ".", "drivers", ")", "if", "not", "drv_cnt", ":", "raise", "NoDriverErr", "(", "self", ")", "elif", "drv_cnt", "!=", "1", ":", "raise", "MultipleDriversErr", "(", "self", ")", "return", "self", ".", "drivers", "[", "0", "]" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
Operator.registerSignals
Register potential signals to drivers/endpoints
hwt/hdl/operator.py
def registerSignals(self, outputs=[]): """ Register potential signals to drivers/endpoints """ for o in self.operands: if isinstance(o, RtlSignalBase): if o in outputs: o.drivers.append(self) else: o.endpoints.append(self) elif isinstance(o, Value): pass else: raise NotImplementedError( "Operator operands can be" " only signal or values got:%r" % (o))
def registerSignals(self, outputs=[]): """ Register potential signals to drivers/endpoints """ for o in self.operands: if isinstance(o, RtlSignalBase): if o in outputs: o.drivers.append(self) else: o.endpoints.append(self) elif isinstance(o, Value): pass else: raise NotImplementedError( "Operator operands can be" " only signal or values got:%r" % (o))
[ "Register", "potential", "signals", "to", "drivers", "/", "endpoints" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/operator.py#L44-L59
[ "def", "registerSignals", "(", "self", ",", "outputs", "=", "[", "]", ")", ":", "for", "o", "in", "self", ".", "operands", ":", "if", "isinstance", "(", "o", ",", "RtlSignalBase", ")", ":", "if", "o", "in", "outputs", ":", "o", ".", "drivers", ".", "append", "(", "self", ")", "else", ":", "o", ".", "endpoints", ".", "append", "(", "self", ")", "elif", "isinstance", "(", "o", ",", "Value", ")", ":", "pass", "else", ":", "raise", "NotImplementedError", "(", "\"Operator operands can be\"", "\" only signal or values got:%r\"", "%", "(", "o", ")", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
Operator.staticEval
Recursively statistically evaluate result of this operator
hwt/hdl/operator.py
def staticEval(self): """ Recursively statistically evaluate result of this operator """ for o in self.operands: o.staticEval() self.result._val = self.evalFn()
def staticEval(self): """ Recursively statistically evaluate result of this operator """ for o in self.operands: o.staticEval() self.result._val = self.evalFn()
[ "Recursively", "statistically", "evaluate", "result", "of", "this", "operator" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/operator.py#L62-L68
[ "def", "staticEval", "(", "self", ")", ":", "for", "o", "in", "self", ".", "operands", ":", "o", ".", "staticEval", "(", ")", "self", ".", "result", ".", "_val", "=", "self", ".", "evalFn", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
Operator.withRes
Create operator with result signal :ivar resT: data type of result signal :ivar outputs: iterable of singnals which are outputs from this operator
hwt/hdl/operator.py
def withRes(opDef, operands, resT, outputs=[]): """ Create operator with result signal :ivar resT: data type of result signal :ivar outputs: iterable of singnals which are outputs from this operator """ op = Operator(opDef, operands) out = RtlSignal(getCtxFromOps(operands), None, resT) out._const = arr_all(op.operands, isConst) out.drivers.append(op) out.origin = op op.result = out op.registerSignals(outputs) if out._const: out.staticEval() return out
def withRes(opDef, operands, resT, outputs=[]): """ Create operator with result signal :ivar resT: data type of result signal :ivar outputs: iterable of singnals which are outputs from this operator """ op = Operator(opDef, operands) out = RtlSignal(getCtxFromOps(operands), None, resT) out._const = arr_all(op.operands, isConst) out.drivers.append(op) out.origin = op op.result = out op.registerSignals(outputs) if out._const: out.staticEval() return out
[ "Create", "operator", "with", "result", "signal" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/operator.py#L110-L127
[ "def", "withRes", "(", "opDef", ",", "operands", ",", "resT", ",", "outputs", "=", "[", "]", ")", ":", "op", "=", "Operator", "(", "opDef", ",", "operands", ")", "out", "=", "RtlSignal", "(", "getCtxFromOps", "(", "operands", ")", ",", "None", ",", "resT", ")", "out", ".", "_const", "=", "arr_all", "(", "op", ".", "operands", ",", "isConst", ")", "out", ".", "drivers", ".", "append", "(", "op", ")", "out", ".", "origin", "=", "op", "op", ".", "result", "=", "out", "op", ".", "registerSignals", "(", "outputs", ")", "if", "out", ".", "_const", ":", "out", ".", "staticEval", "(", ")", "return", "out" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
SerializerCtx.withIndent
Create copy of this context with increased indent
hwt/serializer/generic/context.py
def withIndent(self, indent=1): """ Create copy of this context with increased indent """ ctx = copy(self) ctx.indent += indent return ctx
def withIndent(self, indent=1): """ Create copy of this context with increased indent """ ctx = copy(self) ctx.indent += indent return ctx
[ "Create", "copy", "of", "this", "context", "with", "increased", "indent" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/generic/context.py#L32-L38
[ "def", "withIndent", "(", "self", ",", "indent", "=", "1", ")", ":", "ctx", "=", "copy", "(", "self", ")", "ctx", ".", "indent", "+=", "indent", "return", "ctx" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_tryConnect
Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver.
hwt/interfaces/utils.py
def _tryConnect(src, unit, intfName): """ Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver. """ try: dst = getattr(unit, intfName) except AttributeError: return if not dst._sig.drivers: connect(src, dst)
def _tryConnect(src, unit, intfName): """ Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver. """ try: dst = getattr(unit, intfName) except AttributeError: return if not dst._sig.drivers: connect(src, dst)
[ "Try", "connect", "src", "to", "interface", "of", "specified", "name", "on", "unit", ".", "Ignore", "if", "interface", "is", "not", "present", "or", "if", "it", "already", "has", "driver", "." ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L21-L31
[ "def", "_tryConnect", "(", "src", ",", "unit", ",", "intfName", ")", ":", "try", ":", "dst", "=", "getattr", "(", "unit", ",", "intfName", ")", "except", "AttributeError", ":", "return", "if", "not", "dst", ".", "_sig", ".", "drivers", ":", "connect", "(", "src", ",", "dst", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
propagateClk
Propagate "clk" clock signal to all subcomponents
hwt/interfaces/utils.py
def propagateClk(obj): """ Propagate "clk" clock signal to all subcomponents """ clk = obj.clk for u in obj._units: _tryConnect(clk, u, 'clk')
def propagateClk(obj): """ Propagate "clk" clock signal to all subcomponents """ clk = obj.clk for u in obj._units: _tryConnect(clk, u, 'clk')
[ "Propagate", "clk", "clock", "signal", "to", "all", "subcomponents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L34-L40
[ "def", "propagateClk", "(", "obj", ")", ":", "clk", "=", "obj", ".", "clk", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "clk", ",", "u", ",", "'clk'", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
propagateClkRstn
Propagate "clk" clock and negative reset "rst_n" signal to all subcomponents
hwt/interfaces/utils.py
def propagateClkRstn(obj): """ Propagate "clk" clock and negative reset "rst_n" signal to all subcomponents """ clk = obj.clk rst_n = obj.rst_n for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
def propagateClkRstn(obj): """ Propagate "clk" clock and negative reset "rst_n" signal to all subcomponents """ clk = obj.clk rst_n = obj.rst_n for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
[ "Propagate", "clk", "clock", "and", "negative", "reset", "rst_n", "signal", "to", "all", "subcomponents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L43-L54
[ "def", "propagateClkRstn", "(", "obj", ")", ":", "clk", "=", "obj", ".", "clk", "rst_n", "=", "obj", ".", "rst_n", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "clk", ",", "u", ",", "'clk'", ")", "_tryConnect", "(", "rst_n", ",", "u", ",", "'rst_n'", ")", "_tryConnect", "(", "~", "rst_n", ",", "u", ",", "'rst'", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
propagateClkRst
Propagate "clk" clock and reset "rst" signal to all subcomponents
hwt/interfaces/utils.py
def propagateClkRst(obj): """ Propagate "clk" clock and reset "rst" signal to all subcomponents """ clk = obj.clk rst = obj.rst for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
def propagateClkRst(obj): """ Propagate "clk" clock and reset "rst" signal to all subcomponents """ clk = obj.clk rst = obj.rst for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
[ "Propagate", "clk", "clock", "and", "reset", "rst", "signal", "to", "all", "subcomponents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L57-L67
[ "def", "propagateClkRst", "(", "obj", ")", ":", "clk", "=", "obj", ".", "clk", "rst", "=", "obj", ".", "rst", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "clk", ",", "u", ",", "'clk'", ")", "_tryConnect", "(", "~", "rst", ",", "u", ",", "'rst_n'", ")", "_tryConnect", "(", "rst", ",", "u", ",", "'rst'", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
propagateRstn
Propagate negative reset "rst_n" signal to all subcomponents
hwt/interfaces/utils.py
def propagateRstn(obj): """ Propagate negative reset "rst_n" signal to all subcomponents """ rst_n = obj.rst_n for u in obj._units: _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
def propagateRstn(obj): """ Propagate negative reset "rst_n" signal to all subcomponents """ rst_n = obj.rst_n for u in obj._units: _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
[ "Propagate", "negative", "reset", "rst_n", "signal", "to", "all", "subcomponents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L70-L79
[ "def", "propagateRstn", "(", "obj", ")", ":", "rst_n", "=", "obj", ".", "rst_n", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "rst_n", ",", "u", ",", "'rst_n'", ")", "_tryConnect", "(", "~", "rst_n", ",", "u", ",", "'rst'", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
propagateRst
Propagate reset "rst" signal to all subcomponents
hwt/interfaces/utils.py
def propagateRst(obj): """ Propagate reset "rst" signal to all subcomponents """ rst = obj.rst for u in obj._units: _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
def propagateRst(obj): """ Propagate reset "rst" signal to all subcomponents """ rst = obj.rst for u in obj._units: _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
[ "Propagate", "reset", "rst", "signal", "to", "all", "subcomponents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/utils.py#L82-L91
[ "def", "propagateRst", "(", "obj", ")", ":", "rst", "=", "obj", ".", "rst", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "~", "rst", ",", "u", ",", "'rst_n'", ")", "_tryConnect", "(", "rst", ",", "u", ",", "'rst'", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
fitTo_t
Slice signal "what" to fit in "where" or arithmetically (for signed by MSB / unsigned, vector with 0) extend "what" to same width as "where" little-endian impl.
hwt/synthesizer/vectorUtils.py
def fitTo_t(what: Union[RtlSignal, Value], where_t: HdlType, extend: bool=True, shrink: bool=True): """ Slice signal "what" to fit in "where" or arithmetically (for signed by MSB / unsigned, vector with 0) extend "what" to same width as "where" little-endian impl. """ whatWidth = what._dtype.bit_length() toWidth = where_t.bit_length() if toWidth == whatWidth: return what elif toWidth < whatWidth: # slice if not shrink: raise BitWidthErr() return what[toWidth:] else: if not extend: raise BitWidthErr() w = toWidth - whatWidth if what._dtype.signed: # signed extension msb = what[whatWidth - 1] ext = reduce(lambda a, b: a._concat(b), [msb for _ in range(w)]) else: # 0 extend ext = vec(0, w) return ext._concat(what)
def fitTo_t(what: Union[RtlSignal, Value], where_t: HdlType, extend: bool=True, shrink: bool=True): """ Slice signal "what" to fit in "where" or arithmetically (for signed by MSB / unsigned, vector with 0) extend "what" to same width as "where" little-endian impl. """ whatWidth = what._dtype.bit_length() toWidth = where_t.bit_length() if toWidth == whatWidth: return what elif toWidth < whatWidth: # slice if not shrink: raise BitWidthErr() return what[toWidth:] else: if not extend: raise BitWidthErr() w = toWidth - whatWidth if what._dtype.signed: # signed extension msb = what[whatWidth - 1] ext = reduce(lambda a, b: a._concat(b), [msb for _ in range(w)]) else: # 0 extend ext = vec(0, w) return ext._concat(what)
[ "Slice", "signal", "what", "to", "fit", "in", "where", "or", "arithmetically", "(", "for", "signed", "by", "MSB", "/", "unsigned", "vector", "with", "0", ")", "extend", "what", "to", "same", "width", "as", "where" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/vectorUtils.py#L20-L55
[ "def", "fitTo_t", "(", "what", ":", "Union", "[", "RtlSignal", ",", "Value", "]", ",", "where_t", ":", "HdlType", ",", "extend", ":", "bool", "=", "True", ",", "shrink", ":", "bool", "=", "True", ")", ":", "whatWidth", "=", "what", ".", "_dtype", ".", "bit_length", "(", ")", "toWidth", "=", "where_t", ".", "bit_length", "(", ")", "if", "toWidth", "==", "whatWidth", ":", "return", "what", "elif", "toWidth", "<", "whatWidth", ":", "# slice", "if", "not", "shrink", ":", "raise", "BitWidthErr", "(", ")", "return", "what", "[", "toWidth", ":", "]", "else", ":", "if", "not", "extend", ":", "raise", "BitWidthErr", "(", ")", "w", "=", "toWidth", "-", "whatWidth", "if", "what", ".", "_dtype", ".", "signed", ":", "# signed extension", "msb", "=", "what", "[", "whatWidth", "-", "1", "]", "ext", "=", "reduce", "(", "lambda", "a", ",", "b", ":", "a", ".", "_concat", "(", "b", ")", ",", "[", "msb", "for", "_", "in", "range", "(", "w", ")", "]", ")", "else", ":", "# 0 extend", "ext", "=", "vec", "(", "0", ",", "w", ")", "return", "ext", ".", "_concat", "(", "what", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
iterBits
Iterate over bits in vector :param sigOrVal: signal or value to iterate over :param bitsInOne: number of bits in one part :param skipPadding: if true padding is skipped in dense types
hwt/synthesizer/vectorUtils.py
def iterBits(sigOrVal: Union[RtlSignal, Value], bitsInOne: int=1, skipPadding: bool=True, fillup: bool=False): """ Iterate over bits in vector :param sigOrVal: signal or value to iterate over :param bitsInOne: number of bits in one part :param skipPadding: if true padding is skipped in dense types """ bw = BitWalker(sigOrVal, skipPadding, fillup) for _ in range(ceil(sigOrVal._dtype.bit_length() / bitsInOne)): yield bw.get(bitsInOne) bw.assertIsOnEnd()
def iterBits(sigOrVal: Union[RtlSignal, Value], bitsInOne: int=1, skipPadding: bool=True, fillup: bool=False): """ Iterate over bits in vector :param sigOrVal: signal or value to iterate over :param bitsInOne: number of bits in one part :param skipPadding: if true padding is skipped in dense types """ bw = BitWalker(sigOrVal, skipPadding, fillup) for _ in range(ceil(sigOrVal._dtype.bit_length() / bitsInOne)): yield bw.get(bitsInOne) bw.assertIsOnEnd()
[ "Iterate", "over", "bits", "in", "vector" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/vectorUtils.py#L179-L192
[ "def", "iterBits", "(", "sigOrVal", ":", "Union", "[", "RtlSignal", ",", "Value", "]", ",", "bitsInOne", ":", "int", "=", "1", ",", "skipPadding", ":", "bool", "=", "True", ",", "fillup", ":", "bool", "=", "False", ")", ":", "bw", "=", "BitWalker", "(", "sigOrVal", ",", "skipPadding", ",", "fillup", ")", "for", "_", "in", "range", "(", "ceil", "(", "sigOrVal", ".", "_dtype", ".", "bit_length", "(", ")", "/", "bitsInOne", ")", ")", ":", "yield", "bw", ".", "get", "(", "bitsInOne", ")", "bw", ".", "assertIsOnEnd", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
BitWalker._get
:param numberOfBits: number of bits to get from actual possition :param doCollect: if False output is not collected just iterator moves in structure
hwt/synthesizer/vectorUtils.py
def _get(self, numberOfBits: int, doCollect: bool): """ :param numberOfBits: number of bits to get from actual possition :param doCollect: if False output is not collected just iterator moves in structure """ if not isinstance(numberOfBits, int): numberOfBits = int(numberOfBits) while self.actuallyHave < numberOfBits: # accumulate while not has enought try: f = next(self.it) except StopIteration: if self.fillup and self.actual is not None: break else: raise NotEnoughtBitsErr() thisFieldLen = f._dtype.bit_length() if self.actual is None: if not doCollect and thisFieldLen <= numberOfBits: numberOfBits -= thisFieldLen else: self.actual = f self.actuallyHave = thisFieldLen else: if not doCollect and self.actuallyHave < numberOfBits: self.actuallyHave = thisFieldLen self.actual = f else: self.actuallyHave += thisFieldLen self.actual = f._concat(self.actual) # slice out from actual actual = self.actual actualOffset = self.actualOffset if self.actuallyHave < numberOfBits: assert self.fillup if doCollect: t = self.actual._dtype fillupW = numberOfBits - self.actuallyHave padding_t = Bits(fillupW, signed=t.signed, negated=t.negated) padding = padding_t.fromPy(None) actual = padding._concat(actual) self.actuallyHave = 0 # update about what was taken self.actuallyHave -= numberOfBits self.actualOffset += numberOfBits if self.actuallyHave == 0: self.actual = None self.actualOffset = 0 if doCollect: if numberOfBits == 1: return actual[actualOffset] else: return actual[(actualOffset + numberOfBits):actualOffset]
def _get(self, numberOfBits: int, doCollect: bool): """ :param numberOfBits: number of bits to get from actual possition :param doCollect: if False output is not collected just iterator moves in structure """ if not isinstance(numberOfBits, int): numberOfBits = int(numberOfBits) while self.actuallyHave < numberOfBits: # accumulate while not has enought try: f = next(self.it) except StopIteration: if self.fillup and self.actual is not None: break else: raise NotEnoughtBitsErr() thisFieldLen = f._dtype.bit_length() if self.actual is None: if not doCollect and thisFieldLen <= numberOfBits: numberOfBits -= thisFieldLen else: self.actual = f self.actuallyHave = thisFieldLen else: if not doCollect and self.actuallyHave < numberOfBits: self.actuallyHave = thisFieldLen self.actual = f else: self.actuallyHave += thisFieldLen self.actual = f._concat(self.actual) # slice out from actual actual = self.actual actualOffset = self.actualOffset if self.actuallyHave < numberOfBits: assert self.fillup if doCollect: t = self.actual._dtype fillupW = numberOfBits - self.actuallyHave padding_t = Bits(fillupW, signed=t.signed, negated=t.negated) padding = padding_t.fromPy(None) actual = padding._concat(actual) self.actuallyHave = 0 # update about what was taken self.actuallyHave -= numberOfBits self.actualOffset += numberOfBits if self.actuallyHave == 0: self.actual = None self.actualOffset = 0 if doCollect: if numberOfBits == 1: return actual[actualOffset] else: return actual[(actualOffset + numberOfBits):actualOffset]
[ ":", "param", "numberOfBits", ":", "number", "of", "bits", "to", "get", "from", "actual", "possition", ":", "param", "doCollect", ":", "if", "False", "output", "is", "not", "collected", "just", "iterator", "moves", "in", "structure" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/vectorUtils.py#L91-L150
[ "def", "_get", "(", "self", ",", "numberOfBits", ":", "int", ",", "doCollect", ":", "bool", ")", ":", "if", "not", "isinstance", "(", "numberOfBits", ",", "int", ")", ":", "numberOfBits", "=", "int", "(", "numberOfBits", ")", "while", "self", ".", "actuallyHave", "<", "numberOfBits", ":", "# accumulate while not has enought", "try", ":", "f", "=", "next", "(", "self", ".", "it", ")", "except", "StopIteration", ":", "if", "self", ".", "fillup", "and", "self", ".", "actual", "is", "not", "None", ":", "break", "else", ":", "raise", "NotEnoughtBitsErr", "(", ")", "thisFieldLen", "=", "f", ".", "_dtype", ".", "bit_length", "(", ")", "if", "self", ".", "actual", "is", "None", ":", "if", "not", "doCollect", "and", "thisFieldLen", "<=", "numberOfBits", ":", "numberOfBits", "-=", "thisFieldLen", "else", ":", "self", ".", "actual", "=", "f", "self", ".", "actuallyHave", "=", "thisFieldLen", "else", ":", "if", "not", "doCollect", "and", "self", ".", "actuallyHave", "<", "numberOfBits", ":", "self", ".", "actuallyHave", "=", "thisFieldLen", "self", ".", "actual", "=", "f", "else", ":", "self", ".", "actuallyHave", "+=", "thisFieldLen", "self", ".", "actual", "=", "f", ".", "_concat", "(", "self", ".", "actual", ")", "# slice out from actual", "actual", "=", "self", ".", "actual", "actualOffset", "=", "self", ".", "actualOffset", "if", "self", ".", "actuallyHave", "<", "numberOfBits", ":", "assert", "self", ".", "fillup", "if", "doCollect", ":", "t", "=", "self", ".", "actual", ".", "_dtype", "fillupW", "=", "numberOfBits", "-", "self", ".", "actuallyHave", "padding_t", "=", "Bits", "(", "fillupW", ",", "signed", "=", "t", ".", "signed", ",", "negated", "=", "t", ".", "negated", ")", "padding", "=", "padding_t", ".", "fromPy", "(", "None", ")", "actual", "=", "padding", ".", "_concat", "(", "actual", ")", "self", ".", "actuallyHave", "=", "0", "# update about what was taken", "self", ".", "actuallyHave", "-=", "numberOfBits", "self", ".", "actualOffset", "+=", "numberOfBits", "if", "self", ".", "actuallyHave", "==", "0", ":", "self", ".", "actual", "=", "None", "self", ".", "actualOffset", "=", "0", "if", "doCollect", ":", "if", "numberOfBits", "==", "1", ":", "return", "actual", "[", "actualOffset", "]", "else", ":", "return", "actual", "[", "(", "actualOffset", "+", "numberOfBits", ")", ":", "actualOffset", "]" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
BitWalker.get
:param numberOfBits: number of bits to get from actual possition :return: chunk of bits of specified size (instance of Value or RtlSignal)
hwt/synthesizer/vectorUtils.py
def get(self, numberOfBits: int) -> Union[RtlSignal, Value]: """ :param numberOfBits: number of bits to get from actual possition :return: chunk of bits of specified size (instance of Value or RtlSignal) """ return self._get(numberOfBits, True)
def get(self, numberOfBits: int) -> Union[RtlSignal, Value]: """ :param numberOfBits: number of bits to get from actual possition :return: chunk of bits of specified size (instance of Value or RtlSignal) """ return self._get(numberOfBits, True)
[ ":", "param", "numberOfBits", ":", "number", "of", "bits", "to", "get", "from", "actual", "possition", ":", "return", ":", "chunk", "of", "bits", "of", "specified", "size", "(", "instance", "of", "Value", "or", "RtlSignal", ")" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/vectorUtils.py#L152-L157
[ "def", "get", "(", "self", ",", "numberOfBits", ":", "int", ")", "->", "Union", "[", "RtlSignal", ",", "Value", "]", ":", "return", "self", ".", "_get", "(", "numberOfBits", ",", "True", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_serializeExclude_eval
Always decide not to serialize obj :param priv: private data for this function first unit of this class :return: tuple (do serialize this object, next priv)
hwt/serializer/mode.py
def _serializeExclude_eval(parentUnit, obj, isDeclaration, priv): """ Always decide not to serialize obj :param priv: private data for this function first unit of this class :return: tuple (do serialize this object, next priv) """ if isDeclaration: # prepare entity which will not be serialized prepareEntity(obj, parentUnit.__class__.__name__, priv) if priv is None: priv = parentUnit return False, priv
def _serializeExclude_eval(parentUnit, obj, isDeclaration, priv): """ Always decide not to serialize obj :param priv: private data for this function first unit of this class :return: tuple (do serialize this object, next priv) """ if isDeclaration: # prepare entity which will not be serialized prepareEntity(obj, parentUnit.__class__.__name__, priv) if priv is None: priv = parentUnit return False, priv
[ "Always", "decide", "not", "to", "serialize", "obj" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/mode.py#L80-L94
[ "def", "_serializeExclude_eval", "(", "parentUnit", ",", "obj", ",", "isDeclaration", ",", "priv", ")", ":", "if", "isDeclaration", ":", "# prepare entity which will not be serialized", "prepareEntity", "(", "obj", ",", "parentUnit", ".", "__class__", ".", "__name__", ",", "priv", ")", "if", "priv", "is", "None", ":", "priv", "=", "parentUnit", "return", "False", ",", "priv" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_serializeOnce_eval
Decide to serialize only first obj of it's class :param priv: private data for this function (first object with class == obj.__class__) :return: tuple (do serialize this object, next priv) where priv is private data for this function (first object with class == obj.__class__)
hwt/serializer/mode.py
def _serializeOnce_eval(parentUnit, obj, isDeclaration, priv): """ Decide to serialize only first obj of it's class :param priv: private data for this function (first object with class == obj.__class__) :return: tuple (do serialize this object, next priv) where priv is private data for this function (first object with class == obj.__class__) """ clsName = parentUnit.__class__.__name__ if isDeclaration: obj.name = clsName if priv is None: priv = parentUnit elif isDeclaration: # prepare entity which will not be serialized prepareEntity(obj, clsName, parentUnit) serialize = priv is parentUnit return serialize, priv
def _serializeOnce_eval(parentUnit, obj, isDeclaration, priv): """ Decide to serialize only first obj of it's class :param priv: private data for this function (first object with class == obj.__class__) :return: tuple (do serialize this object, next priv) where priv is private data for this function (first object with class == obj.__class__) """ clsName = parentUnit.__class__.__name__ if isDeclaration: obj.name = clsName if priv is None: priv = parentUnit elif isDeclaration: # prepare entity which will not be serialized prepareEntity(obj, clsName, parentUnit) serialize = priv is parentUnit return serialize, priv
[ "Decide", "to", "serialize", "only", "first", "obj", "of", "it", "s", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/mode.py#L98-L122
[ "def", "_serializeOnce_eval", "(", "parentUnit", ",", "obj", ",", "isDeclaration", ",", "priv", ")", ":", "clsName", "=", "parentUnit", ".", "__class__", ".", "__name__", "if", "isDeclaration", ":", "obj", ".", "name", "=", "clsName", "if", "priv", "is", "None", ":", "priv", "=", "parentUnit", "elif", "isDeclaration", ":", "# prepare entity which will not be serialized", "prepareEntity", "(", "obj", ",", "clsName", ",", "parentUnit", ")", "serialize", "=", "priv", "is", "parentUnit", "return", "serialize", ",", "priv" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_serializeParamsUniq_eval
Decide to serialize only objs with uniq parameters and class :param priv: private data for this function ({frozen_params: obj}) :return: tuple (do serialize this object, next priv)
hwt/serializer/mode.py
def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv): """ Decide to serialize only objs with uniq parameters and class :param priv: private data for this function ({frozen_params: obj}) :return: tuple (do serialize this object, next priv) """ params = paramsToValTuple(parentUnit) if priv is None: priv = {} if isDeclaration: try: prevUnit = priv[params] except KeyError: priv[params] = parentUnit return True, priv prepareEntity(obj, prevUnit._entity.name, prevUnit) return False, priv return priv[params] is parentUnit, priv
def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv): """ Decide to serialize only objs with uniq parameters and class :param priv: private data for this function ({frozen_params: obj}) :return: tuple (do serialize this object, next priv) """ params = paramsToValTuple(parentUnit) if priv is None: priv = {} if isDeclaration: try: prevUnit = priv[params] except KeyError: priv[params] = parentUnit return True, priv prepareEntity(obj, prevUnit._entity.name, prevUnit) return False, priv return priv[params] is parentUnit, priv
[ "Decide", "to", "serialize", "only", "objs", "with", "uniq", "parameters", "and", "class" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/mode.py#L126-L151
[ "def", "_serializeParamsUniq_eval", "(", "parentUnit", ",", "obj", ",", "isDeclaration", ",", "priv", ")", ":", "params", "=", "paramsToValTuple", "(", "parentUnit", ")", "if", "priv", "is", "None", ":", "priv", "=", "{", "}", "if", "isDeclaration", ":", "try", ":", "prevUnit", "=", "priv", "[", "params", "]", "except", "KeyError", ":", "priv", "[", "params", "]", "=", "parentUnit", "return", "True", ",", "priv", "prepareEntity", "(", "obj", ",", "prevUnit", ".", "_entity", ".", "name", ",", "prevUnit", ")", "return", "False", ",", "priv", "return", "priv", "[", "params", "]", "is", "parentUnit", ",", "priv" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HObjList._getFullName
get all name hierarchy separated by '.'
hwt/synthesizer/hObjList.py
def _getFullName(self): """get all name hierarchy separated by '.' """ name = "" tmp = self while isinstance(tmp, (InterfaceBase, HObjList)): if hasattr(tmp, "_name"): n = tmp._name else: n = '' if name == '': name = n else: name = n + '.' + name if hasattr(tmp, "_parent"): tmp = tmp._parent else: tmp = None return name
def _getFullName(self): """get all name hierarchy separated by '.' """ name = "" tmp = self while isinstance(tmp, (InterfaceBase, HObjList)): if hasattr(tmp, "_name"): n = tmp._name else: n = '' if name == '': name = n else: name = n + '.' + name if hasattr(tmp, "_parent"): tmp = tmp._parent else: tmp = None return name
[ "get", "all", "name", "hierarchy", "separated", "by", "." ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/hObjList.py#L25-L42
[ "def", "_getFullName", "(", "self", ")", ":", "name", "=", "\"\"", "tmp", "=", "self", "while", "isinstance", "(", "tmp", ",", "(", "InterfaceBase", ",", "HObjList", ")", ")", ":", "if", "hasattr", "(", "tmp", ",", "\"_name\"", ")", ":", "n", "=", "tmp", ".", "_name", "else", ":", "n", "=", "''", "if", "name", "==", "''", ":", "name", "=", "n", "else", ":", "name", "=", "n", "+", "'.'", "+", "name", "if", "hasattr", "(", "tmp", ",", "\"_parent\"", ")", ":", "tmp", "=", "tmp", ".", "_parent", "else", ":", "tmp", "=", "None", "return", "name" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HObjList._make_association
Delegate _make_association on items :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._make_association`
hwt/synthesizer/hObjList.py
def _make_association(self, *args, **kwargs): """ Delegate _make_association on items :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._make_association` """ for o in self: o._make_association(*args, **kwargs)
def _make_association(self, *args, **kwargs): """ Delegate _make_association on items :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._make_association` """ for o in self: o._make_association(*args, **kwargs)
[ "Delegate", "_make_association", "on", "items" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/hObjList.py#L44-L51
[ "def", "_make_association", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "o", "in", "self", ":", "o", ".", "_make_association", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HObjList._updateParamsFrom
:note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom`
hwt/synthesizer/hObjList.py
def _updateParamsFrom(self, *args, **kwargs): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ for o in self: o._updateParamsFrom(*args, **kwargs)
def _updateParamsFrom(self, *args, **kwargs): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ for o in self: o._updateParamsFrom(*args, **kwargs)
[ ":", "note", ":", "doc", "in", ":", "func", ":", "~hwt", ".", "synthesizer", ".", "interfaceLevel", ".", "propDeclCollector", ".", "_updateParamsFrom" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/hObjList.py#L53-L58
[ "def", "_updateParamsFrom", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "o", "in", "self", ":", "o", ".", "_updateParamsFrom", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
simPrepare
Create simulation model and connect it with interfaces of original unit and decorate it with agents :param unit: interface level unit which you wont prepare for simulation :param modelCls: class of rtl simulation model to run simulation on, if is None rtl sim model will be generated from unit :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (if is None sim model will be constructed only in memory) :param onAfterToRtl: callback fn(unit, modelCls) which will be called after unit will be synthesised to rtl :return: tuple (fully loaded unit with connected sim model, connected simulation model, simulation processes of agents )
hwt/simulator/shortcuts.py
def simPrepare(unit: Unit, modelCls: Optional[SimModel]=None, targetPlatform=DummyPlatform(), dumpModelIn: str=None, onAfterToRtl=None): """ Create simulation model and connect it with interfaces of original unit and decorate it with agents :param unit: interface level unit which you wont prepare for simulation :param modelCls: class of rtl simulation model to run simulation on, if is None rtl sim model will be generated from unit :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (if is None sim model will be constructed only in memory) :param onAfterToRtl: callback fn(unit, modelCls) which will be called after unit will be synthesised to rtl :return: tuple (fully loaded unit with connected sim model, connected simulation model, simulation processes of agents ) """ if modelCls is None: modelCls = toSimModel( unit, targetPlatform=targetPlatform, dumpModelIn=dumpModelIn) else: # to instantiate hierarchy of unit toSimModel(unit) if onAfterToRtl: onAfterToRtl(unit, modelCls) reconnectUnitSignalsToModel(unit, modelCls) model = modelCls() procs = autoAddAgents(unit) return unit, model, procs
def simPrepare(unit: Unit, modelCls: Optional[SimModel]=None, targetPlatform=DummyPlatform(), dumpModelIn: str=None, onAfterToRtl=None): """ Create simulation model and connect it with interfaces of original unit and decorate it with agents :param unit: interface level unit which you wont prepare for simulation :param modelCls: class of rtl simulation model to run simulation on, if is None rtl sim model will be generated from unit :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (if is None sim model will be constructed only in memory) :param onAfterToRtl: callback fn(unit, modelCls) which will be called after unit will be synthesised to rtl :return: tuple (fully loaded unit with connected sim model, connected simulation model, simulation processes of agents ) """ if modelCls is None: modelCls = toSimModel( unit, targetPlatform=targetPlatform, dumpModelIn=dumpModelIn) else: # to instantiate hierarchy of unit toSimModel(unit) if onAfterToRtl: onAfterToRtl(unit, modelCls) reconnectUnitSignalsToModel(unit, modelCls) model = modelCls() procs = autoAddAgents(unit) return unit, model, procs
[ "Create", "simulation", "model", "and", "connect", "it", "with", "interfaces", "of", "original", "unit", "and", "decorate", "it", "with", "agents" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L21-L55
[ "def", "simPrepare", "(", "unit", ":", "Unit", ",", "modelCls", ":", "Optional", "[", "SimModel", "]", "=", "None", ",", "targetPlatform", "=", "DummyPlatform", "(", ")", ",", "dumpModelIn", ":", "str", "=", "None", ",", "onAfterToRtl", "=", "None", ")", ":", "if", "modelCls", "is", "None", ":", "modelCls", "=", "toSimModel", "(", "unit", ",", "targetPlatform", "=", "targetPlatform", ",", "dumpModelIn", "=", "dumpModelIn", ")", "else", ":", "# to instantiate hierarchy of unit", "toSimModel", "(", "unit", ")", "if", "onAfterToRtl", ":", "onAfterToRtl", "(", "unit", ",", "modelCls", ")", "reconnectUnitSignalsToModel", "(", "unit", ",", "modelCls", ")", "model", "=", "modelCls", "(", ")", "procs", "=", "autoAddAgents", "(", "unit", ")", "return", "unit", ",", "model", ",", "procs" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
toSimModel
Create a simulation model for unit :param unit: interface level unit which you wont prepare for simulation :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (otherwise sim model will be constructed only in memory)
hwt/simulator/shortcuts.py
def toSimModel(unit, targetPlatform=DummyPlatform(), dumpModelIn=None): """ Create a simulation model for unit :param unit: interface level unit which you wont prepare for simulation :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (otherwise sim model will be constructed only in memory) """ sim_code = toRtl(unit, targetPlatform=targetPlatform, saveTo=dumpModelIn, serializer=SimModelSerializer) if dumpModelIn is not None: d = os.path.join(os.getcwd(), dumpModelIn) dInPath = d in sys.path if not dInPath: sys.path.insert(0, d) if unit._name in sys.modules: del sys.modules[unit._name] simModule = importlib.import_module(unit._name) if not dInPath: sys.path.remove(d) else: simModule = ModuleType('simModule') # python supports only ~100 opened brackets # it exceded it throws MemoryError: s_push: parser stack overflow exec(sim_code, simModule.__dict__) return simModule.__dict__[unit._name]
def toSimModel(unit, targetPlatform=DummyPlatform(), dumpModelIn=None): """ Create a simulation model for unit :param unit: interface level unit which you wont prepare for simulation :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files (otherwise sim model will be constructed only in memory) """ sim_code = toRtl(unit, targetPlatform=targetPlatform, saveTo=dumpModelIn, serializer=SimModelSerializer) if dumpModelIn is not None: d = os.path.join(os.getcwd(), dumpModelIn) dInPath = d in sys.path if not dInPath: sys.path.insert(0, d) if unit._name in sys.modules: del sys.modules[unit._name] simModule = importlib.import_module(unit._name) if not dInPath: sys.path.remove(d) else: simModule = ModuleType('simModule') # python supports only ~100 opened brackets # it exceded it throws MemoryError: s_push: parser stack overflow exec(sim_code, simModule.__dict__) return simModule.__dict__[unit._name]
[ "Create", "a", "simulation", "model", "for", "unit" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L58-L88
[ "def", "toSimModel", "(", "unit", ",", "targetPlatform", "=", "DummyPlatform", "(", ")", ",", "dumpModelIn", "=", "None", ")", ":", "sim_code", "=", "toRtl", "(", "unit", ",", "targetPlatform", "=", "targetPlatform", ",", "saveTo", "=", "dumpModelIn", ",", "serializer", "=", "SimModelSerializer", ")", "if", "dumpModelIn", "is", "not", "None", ":", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "dumpModelIn", ")", "dInPath", "=", "d", "in", "sys", ".", "path", "if", "not", "dInPath", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "d", ")", "if", "unit", ".", "_name", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "unit", ".", "_name", "]", "simModule", "=", "importlib", ".", "import_module", "(", "unit", ".", "_name", ")", "if", "not", "dInPath", ":", "sys", ".", "path", ".", "remove", "(", "d", ")", "else", ":", "simModule", "=", "ModuleType", "(", "'simModule'", ")", "# python supports only ~100 opened brackets", "# it exceded it throws MemoryError: s_push: parser stack overflow", "exec", "(", "sim_code", ",", "simModule", ".", "__dict__", ")", "return", "simModule", ".", "__dict__", "[", "unit", ".", "_name", "]" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
reconnectUnitSignalsToModel
Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication :param synthesisedUnitOrIntf: interface where should be signals replaced from signals from modelCls :param modelCls: simulation model form where signals for synthesisedUnitOrIntf should be taken
hwt/simulator/shortcuts.py
def reconnectUnitSignalsToModel(synthesisedUnitOrIntf, modelCls): """ Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication :param synthesisedUnitOrIntf: interface where should be signals replaced from signals from modelCls :param modelCls: simulation model form where signals for synthesisedUnitOrIntf should be taken """ obj = synthesisedUnitOrIntf subInterfaces = obj._interfaces if subInterfaces: for intf in subInterfaces: # proxies are destroyed on original interfaces and only proxies on # array items will remain reconnectUnitSignalsToModel(intf, modelCls) else: # reconnect signal from model s = synthesisedUnitOrIntf s._sigInside = getattr(modelCls, s._sigInside.name)
def reconnectUnitSignalsToModel(synthesisedUnitOrIntf, modelCls): """ Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication :param synthesisedUnitOrIntf: interface where should be signals replaced from signals from modelCls :param modelCls: simulation model form where signals for synthesisedUnitOrIntf should be taken """ obj = synthesisedUnitOrIntf subInterfaces = obj._interfaces if subInterfaces: for intf in subInterfaces: # proxies are destroyed on original interfaces and only proxies on # array items will remain reconnectUnitSignalsToModel(intf, modelCls) else: # reconnect signal from model s = synthesisedUnitOrIntf s._sigInside = getattr(modelCls, s._sigInside.name)
[ "Reconnect", "model", "signals", "to", "unit", "to", "run", "simulation", "with", "simulation", "model", "but", "use", "original", "unit", "interfaces", "for", "communication" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L92-L114
[ "def", "reconnectUnitSignalsToModel", "(", "synthesisedUnitOrIntf", ",", "modelCls", ")", ":", "obj", "=", "synthesisedUnitOrIntf", "subInterfaces", "=", "obj", ".", "_interfaces", "if", "subInterfaces", ":", "for", "intf", "in", "subInterfaces", ":", "# proxies are destroyed on original interfaces and only proxies on", "# array items will remain", "reconnectUnitSignalsToModel", "(", "intf", ",", "modelCls", ")", "else", ":", "# reconnect signal from model", "s", "=", "synthesisedUnitOrIntf", "s", ".", "_sigInside", "=", "getattr", "(", "modelCls", ",", "s", ".", "_sigInside", ".", "name", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
simUnitVcd
Syntax sugar If outputFile is string try to open it as file :return: hdl simulator object
hwt/simulator/shortcuts.py
def simUnitVcd(simModel, stimulFunctions, outputFile=sys.stdout, until=100 * Time.ns): """ Syntax sugar If outputFile is string try to open it as file :return: hdl simulator object """ assert isinstance(simModel, SimModel), \ "Class of SimModel is required (got %r)" % (simModel) if isinstance(outputFile, str): d = os.path.dirname(outputFile) if d: os.makedirs(d, exist_ok=True) with open(outputFile, 'w') as f: return _simUnitVcd(simModel, stimulFunctions, f, until) else: return _simUnitVcd(simModel, stimulFunctions, outputFile, until)
def simUnitVcd(simModel, stimulFunctions, outputFile=sys.stdout, until=100 * Time.ns): """ Syntax sugar If outputFile is string try to open it as file :return: hdl simulator object """ assert isinstance(simModel, SimModel), \ "Class of SimModel is required (got %r)" % (simModel) if isinstance(outputFile, str): d = os.path.dirname(outputFile) if d: os.makedirs(d, exist_ok=True) with open(outputFile, 'w') as f: return _simUnitVcd(simModel, stimulFunctions, f, until) else: return _simUnitVcd(simModel, stimulFunctions, outputFile, until)
[ "Syntax", "sugar", "If", "outputFile", "is", "string", "try", "to", "open", "it", "as", "file" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L117-L136
[ "def", "simUnitVcd", "(", "simModel", ",", "stimulFunctions", ",", "outputFile", "=", "sys", ".", "stdout", ",", "until", "=", "100", "*", "Time", ".", "ns", ")", ":", "assert", "isinstance", "(", "simModel", ",", "SimModel", ")", ",", "\"Class of SimModel is required (got %r)\"", "%", "(", "simModel", ")", "if", "isinstance", "(", "outputFile", ",", "str", ")", ":", "d", "=", "os", ".", "path", ".", "dirname", "(", "outputFile", ")", "if", "d", ":", "os", ".", "makedirs", "(", "d", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "outputFile", ",", "'w'", ")", "as", "f", ":", "return", "_simUnitVcd", "(", "simModel", ",", "stimulFunctions", ",", "f", ",", "until", ")", "else", ":", "return", "_simUnitVcd", "(", "simModel", ",", "stimulFunctions", ",", "outputFile", ",", "until", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_simUnitVcd
:param unit: interface level unit to simulate :param stimulFunctions: iterable of function(env) (simpy environment) which are driving the simulation :param outputFile: file where vcd will be dumped :param time: endtime of simulation, time units are defined in HdlSimulator :return: hdl simulator object
hwt/simulator/shortcuts.py
def _simUnitVcd(simModel, stimulFunctions, outputFile, until): """ :param unit: interface level unit to simulate :param stimulFunctions: iterable of function(env) (simpy environment) which are driving the simulation :param outputFile: file where vcd will be dumped :param time: endtime of simulation, time units are defined in HdlSimulator :return: hdl simulator object """ sim = HdlSimulator() # configure simulator to log in vcd sim.config = VcdHdlSimConfig(outputFile) # run simulation, stimul processes are register after initial # initialization sim.simUnit(simModel, until=until, extraProcesses=stimulFunctions) return sim
def _simUnitVcd(simModel, stimulFunctions, outputFile, until): """ :param unit: interface level unit to simulate :param stimulFunctions: iterable of function(env) (simpy environment) which are driving the simulation :param outputFile: file where vcd will be dumped :param time: endtime of simulation, time units are defined in HdlSimulator :return: hdl simulator object """ sim = HdlSimulator() # configure simulator to log in vcd sim.config = VcdHdlSimConfig(outputFile) # run simulation, stimul processes are register after initial # initialization sim.simUnit(simModel, until=until, extraProcesses=stimulFunctions) return sim
[ ":", "param", "unit", ":", "interface", "level", "unit", "to", "simulate", ":", "param", "stimulFunctions", ":", "iterable", "of", "function", "(", "env", ")", "(", "simpy", "environment", ")", "which", "are", "driving", "the", "simulation", ":", "param", "outputFile", ":", "file", "where", "vcd", "will", "be", "dumped", ":", "param", "time", ":", "endtime", "of", "simulation", "time", "units", "are", "defined", "in", "HdlSimulator", ":", "return", ":", "hdl", "simulator", "object" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L140-L157
[ "def", "_simUnitVcd", "(", "simModel", ",", "stimulFunctions", ",", "outputFile", ",", "until", ")", ":", "sim", "=", "HdlSimulator", "(", ")", "# configure simulator to log in vcd", "sim", ".", "config", "=", "VcdHdlSimConfig", "(", "outputFile", ")", "# run simulation, stimul processes are register after initial", "# initialization", "sim", ".", "simUnit", "(", "simModel", ",", "until", "=", "until", ",", "extraProcesses", "=", "stimulFunctions", ")", "return", "sim" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
oscilate
Oscillative simulation driver for your signal (usually used as clk generator)
hwt/simulator/shortcuts.py
def oscilate(sig, period=10 * Time.ns, initWait=0): """ Oscillative simulation driver for your signal (usually used as clk generator) """ def oscillateStimul(s): s.write(False, sig) halfPeriod = period / 2 yield s.wait(initWait) while True: yield s.wait(halfPeriod) s.write(True, sig) yield s.wait(halfPeriod) s.write(False, sig) return oscillateStimul
def oscilate(sig, period=10 * Time.ns, initWait=0): """ Oscillative simulation driver for your signal (usually used as clk generator) """ def oscillateStimul(s): s.write(False, sig) halfPeriod = period / 2 yield s.wait(initWait) while True: yield s.wait(halfPeriod) s.write(True, sig) yield s.wait(halfPeriod) s.write(False, sig) return oscillateStimul
[ "Oscillative", "simulation", "driver", "for", "your", "signal", "(", "usually", "used", "as", "clk", "generator", ")" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/shortcuts.py#L233-L249
[ "def", "oscilate", "(", "sig", ",", "period", "=", "10", "*", "Time", ".", "ns", ",", "initWait", "=", "0", ")", ":", "def", "oscillateStimul", "(", "s", ")", ":", "s", ".", "write", "(", "False", ",", "sig", ")", "halfPeriod", "=", "period", "/", "2", "yield", "s", ".", "wait", "(", "initWait", ")", "while", "True", ":", "yield", "s", ".", "wait", "(", "halfPeriod", ")", "s", ".", "write", "(", "True", ",", "sig", ")", "yield", "s", ".", "wait", "(", "halfPeriod", ")", "s", ".", "write", "(", "False", ",", "sig", ")", "return", "oscillateStimul" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
TristateAgent.onTWriteCallback__init
Process for injecting of this callback loop into simulator
hwt/interfaces/agents/tristate.py
def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) self.intf.t._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable) self.intf.o._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable)
def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) self.intf.t._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable) self.intf.o._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable)
[ "Process", "for", "injecting", "of", "this", "callback", "loop", "into", "simulator" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/interfaces/agents/tristate.py#L71-L81
[ "def", "onTWriteCallback__init", "(", "self", ",", "sim", ")", ":", "yield", "from", "self", ".", "onTWriteCallback", "(", "sim", ")", "self", ".", "intf", ".", "t", ".", "_sigInside", ".", "registerWriteCallback", "(", "self", ".", "onTWriteCallback", ",", "self", ".", "getEnable", ")", "self", ".", "intf", ".", "o", ".", "_sigInside", ".", "registerWriteCallback", "(", "self", ".", "onTWriteCallback", ",", "self", ".", "getEnable", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PortItem.connectSig
Connect to port item on subunit
hwt/hdl/portItem.py
def connectSig(self, signal): """ Connect to port item on subunit """ if self.direction == DIRECTION.IN: if self.src is not None: raise HwtSyntaxError( "Port %s is already associated with %r" % (self.name, self.src)) self.src = signal signal.endpoints.append(self) elif self.direction == DIRECTION.OUT: if self.dst is not None: raise HwtSyntaxError( "Port %s is already associated with %r" % (self.name, self.dst)) self.dst = signal signal.drivers.append(self) else: raise NotImplementedError(self) signal.hidden = False signal.ctx.subUnits.add(self.unit)
def connectSig(self, signal): """ Connect to port item on subunit """ if self.direction == DIRECTION.IN: if self.src is not None: raise HwtSyntaxError( "Port %s is already associated with %r" % (self.name, self.src)) self.src = signal signal.endpoints.append(self) elif self.direction == DIRECTION.OUT: if self.dst is not None: raise HwtSyntaxError( "Port %s is already associated with %r" % (self.name, self.dst)) self.dst = signal signal.drivers.append(self) else: raise NotImplementedError(self) signal.hidden = False signal.ctx.subUnits.add(self.unit)
[ "Connect", "to", "port", "item", "on", "subunit" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/portItem.py#L20-L44
[ "def", "connectSig", "(", "self", ",", "signal", ")", ":", "if", "self", ".", "direction", "==", "DIRECTION", ".", "IN", ":", "if", "self", ".", "src", "is", "not", "None", ":", "raise", "HwtSyntaxError", "(", "\"Port %s is already associated with %r\"", "%", "(", "self", ".", "name", ",", "self", ".", "src", ")", ")", "self", ".", "src", "=", "signal", "signal", ".", "endpoints", ".", "append", "(", "self", ")", "elif", "self", ".", "direction", "==", "DIRECTION", ".", "OUT", ":", "if", "self", ".", "dst", "is", "not", "None", ":", "raise", "HwtSyntaxError", "(", "\"Port %s is already associated with %r\"", "%", "(", "self", ".", "name", ",", "self", ".", "dst", ")", ")", "self", ".", "dst", "=", "signal", "signal", ".", "drivers", ".", "append", "(", "self", ")", "else", ":", "raise", "NotImplementedError", "(", "self", ")", "signal", ".", "hidden", "=", "False", "signal", ".", "ctx", ".", "subUnits", ".", "add", "(", "self", ".", "unit", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PortItem.registerInternSig
Connect internal signal to port item, this connection is used by simulator and only output port items will be connected
hwt/hdl/portItem.py
def registerInternSig(self, signal): """ Connect internal signal to port item, this connection is used by simulator and only output port items will be connected """ if self.direction == DIRECTION.OUT: if self.src is not None: raise HwtSyntaxError( "Port %s is already associated with %s" % (self.name, str(self.src))) self.src = signal elif self.direction == DIRECTION.IN: if self.dst is not None: raise HwtSyntaxError( "Port %s is already associated with %s" % (self.name, str(self.dst))) self.dst = signal else: raise NotImplementedError(self.direction)
def registerInternSig(self, signal): """ Connect internal signal to port item, this connection is used by simulator and only output port items will be connected """ if self.direction == DIRECTION.OUT: if self.src is not None: raise HwtSyntaxError( "Port %s is already associated with %s" % (self.name, str(self.src))) self.src = signal elif self.direction == DIRECTION.IN: if self.dst is not None: raise HwtSyntaxError( "Port %s is already associated with %s" % (self.name, str(self.dst))) self.dst = signal else: raise NotImplementedError(self.direction)
[ "Connect", "internal", "signal", "to", "port", "item", "this", "connection", "is", "used", "by", "simulator", "and", "only", "output", "port", "items", "will", "be", "connected" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/portItem.py#L47-L68
[ "def", "registerInternSig", "(", "self", ",", "signal", ")", ":", "if", "self", ".", "direction", "==", "DIRECTION", ".", "OUT", ":", "if", "self", ".", "src", "is", "not", "None", ":", "raise", "HwtSyntaxError", "(", "\"Port %s is already associated with %s\"", "%", "(", "self", ".", "name", ",", "str", "(", "self", ".", "src", ")", ")", ")", "self", ".", "src", "=", "signal", "elif", "self", ".", "direction", "==", "DIRECTION", ".", "IN", ":", "if", "self", ".", "dst", "is", "not", "None", ":", "raise", "HwtSyntaxError", "(", "\"Port %s is already associated with %s\"", "%", "(", "self", ".", "name", ",", "str", "(", "self", ".", "dst", ")", ")", ")", "self", ".", "dst", "=", "signal", "else", ":", "raise", "NotImplementedError", "(", "self", ".", "direction", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PortItem.connectInternSig
connet signal from internal side of of this component to this port
hwt/hdl/portItem.py
def connectInternSig(self): """ connet signal from internal side of of this component to this port """ d = self.direction if d == DIRECTION.OUT: self.src.endpoints.append(self) elif d == DIRECTION.IN or d == DIRECTION.INOUT: self.dst.drivers.append(self) else: raise NotImplementedError(d)
def connectInternSig(self): """ connet signal from internal side of of this component to this port """ d = self.direction if d == DIRECTION.OUT: self.src.endpoints.append(self) elif d == DIRECTION.IN or d == DIRECTION.INOUT: self.dst.drivers.append(self) else: raise NotImplementedError(d)
[ "connet", "signal", "from", "internal", "side", "of", "of", "this", "component", "to", "this", "port" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/portItem.py#L71-L81
[ "def", "connectInternSig", "(", "self", ")", ":", "d", "=", "self", ".", "direction", "if", "d", "==", "DIRECTION", ".", "OUT", ":", "self", ".", "src", ".", "endpoints", ".", "append", "(", "self", ")", "elif", "d", "==", "DIRECTION", ".", "IN", "or", "d", "==", "DIRECTION", ".", "INOUT", ":", "self", ".", "dst", ".", "drivers", ".", "append", "(", "self", ")", "else", ":", "raise", "NotImplementedError", "(", "d", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
PortItem.getInternSig
return signal inside unit which has this port
hwt/hdl/portItem.py
def getInternSig(self): """ return signal inside unit which has this port """ d = self.direction if d == DIRECTION.IN: return self.dst elif d == DIRECTION.OUT: return self.src else: raise NotImplementedError(d)
def getInternSig(self): """ return signal inside unit which has this port """ d = self.direction if d == DIRECTION.IN: return self.dst elif d == DIRECTION.OUT: return self.src else: raise NotImplementedError(d)
[ "return", "signal", "inside", "unit", "which", "has", "this", "port" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/portItem.py#L84-L94
[ "def", "getInternSig", "(", "self", ")", ":", "d", "=", "self", ".", "direction", "if", "d", "==", "DIRECTION", ".", "IN", ":", "return", "self", ".", "dst", "elif", "d", "==", "DIRECTION", ".", "OUT", ":", "return", "self", ".", "src", "else", ":", "raise", "NotImplementedError", "(", "d", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
isEvDependentOn
Check if hdl process has event depenency on signal
hwt/simulator/hdlSimulator.py
def isEvDependentOn(sig, process) -> bool: """ Check if hdl process has event depenency on signal """ if sig is None: return False return process in sig.simFallingSensProcs\ or process in sig.simRisingSensProcs
def isEvDependentOn(sig, process) -> bool: """ Check if hdl process has event depenency on signal """ if sig is None: return False return process in sig.simFallingSensProcs\ or process in sig.simRisingSensProcs
[ "Check", "if", "hdl", "process", "has", "event", "depenency", "on", "signal" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L15-L23
[ "def", "isEvDependentOn", "(", "sig", ",", "process", ")", "->", "bool", ":", "if", "sig", "is", "None", ":", "return", "False", "return", "process", "in", "sig", ".", "simFallingSensProcs", "or", "process", "in", "sig", ".", "simRisingSensProcs" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._add_process
Schedule process on actual time with specified priority
hwt/simulator/hdlSimulator.py
def _add_process(self, proc, priority) -> None: """ Schedule process on actual time with specified priority """ self._events.push(self.now, priority, proc)
def _add_process(self, proc, priority) -> None: """ Schedule process on actual time with specified priority """ self._events.push(self.now, priority, proc)
[ "Schedule", "process", "on", "actual", "time", "with", "specified", "priority" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L217-L221
[ "def", "_add_process", "(", "self", ",", "proc", ",", "priority", ")", "->", "None", ":", "self", ".", "_events", ".", "push", "(", "self", ".", "now", ",", "priority", ",", "proc", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._addHdlProcToRun
Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process
hwt/simulator/hdlSimulator.py
def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process """ # first process in time has to plan executing of apply values on the # end of this time if not self._applyValPlaned: # (apply on end of this time to minimalize process reevaluation) self._scheduleApplyValues() if isEvDependentOn(trigger, proc): if self.now == 0: return # pass event dependent on startup self._seqProcsToRun.append(proc) else: self._combProcsToRun.append(proc)
def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process """ # first process in time has to plan executing of apply values on the # end of this time if not self._applyValPlaned: # (apply on end of this time to minimalize process reevaluation) self._scheduleApplyValues() if isEvDependentOn(trigger, proc): if self.now == 0: return # pass event dependent on startup self._seqProcsToRun.append(proc) else: self._combProcsToRun.append(proc)
[ "Add", "hdl", "process", "to", "execution", "queue" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L237-L255
[ "def", "_addHdlProcToRun", "(", "self", ",", "trigger", ":", "SimSignal", ",", "proc", ")", "->", "None", ":", "# first process in time has to plan executing of apply values on the", "# end of this time", "if", "not", "self", ".", "_applyValPlaned", ":", "# (apply on end of this time to minimalize process reevaluation)", "self", ".", "_scheduleApplyValues", "(", ")", "if", "isEvDependentOn", "(", "trigger", ",", "proc", ")", ":", "if", "self", ".", "now", "==", "0", ":", "return", "# pass event dependent on startup", "self", ".", "_seqProcsToRun", ".", "append", "(", "proc", ")", "else", ":", "self", ".", "_combProcsToRun", ".", "append", "(", "proc", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._initUnitSignals
* Inject default values to simulation * Instantiate IOs for every process
hwt/simulator/hdlSimulator.py
def _initUnitSignals(self, unit: Unit) -> None: """ * Inject default values to simulation * Instantiate IOs for every process """ # set initial value to all signals and propagate it for s in unit._ctx.signals: if s.defVal.vldMask: v = s.defVal.clone() s.simUpdateVal(self, mkUpdater(v, False)) for u in unit._units: self._initUnitSignals(u) for p in unit._processes: self._addHdlProcToRun(None, p) for p, outputs in unit._outputs.items(): # name has to be explicit because it may be possible that signal # with has this name was replaced by signal from parent/child containerNames = list(map(lambda x: x[0], outputs)) class SpecificIoContainer(IoContainer): __slots__ = containerNames self._outputContainers[p] = SpecificIoContainer(outputs)
def _initUnitSignals(self, unit: Unit) -> None: """ * Inject default values to simulation * Instantiate IOs for every process """ # set initial value to all signals and propagate it for s in unit._ctx.signals: if s.defVal.vldMask: v = s.defVal.clone() s.simUpdateVal(self, mkUpdater(v, False)) for u in unit._units: self._initUnitSignals(u) for p in unit._processes: self._addHdlProcToRun(None, p) for p, outputs in unit._outputs.items(): # name has to be explicit because it may be possible that signal # with has this name was replaced by signal from parent/child containerNames = list(map(lambda x: x[0], outputs)) class SpecificIoContainer(IoContainer): __slots__ = containerNames self._outputContainers[p] = SpecificIoContainer(outputs)
[ "*", "Inject", "default", "values", "to", "simulation" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L258-L284
[ "def", "_initUnitSignals", "(", "self", ",", "unit", ":", "Unit", ")", "->", "None", ":", "# set initial value to all signals and propagate it", "for", "s", "in", "unit", ".", "_ctx", ".", "signals", ":", "if", "s", ".", "defVal", ".", "vldMask", ":", "v", "=", "s", ".", "defVal", ".", "clone", "(", ")", "s", ".", "simUpdateVal", "(", "self", ",", "mkUpdater", "(", "v", ",", "False", ")", ")", "for", "u", "in", "unit", ".", "_units", ":", "self", ".", "_initUnitSignals", "(", "u", ")", "for", "p", "in", "unit", ".", "_processes", ":", "self", ".", "_addHdlProcToRun", "(", "None", ",", "p", ")", "for", "p", ",", "outputs", "in", "unit", ".", "_outputs", ".", "items", "(", ")", ":", "# name has to be explicit because it may be possible that signal", "# with has this name was replaced by signal from parent/child", "containerNames", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "outputs", ")", ")", "class", "SpecificIoContainer", "(", "IoContainer", ")", ":", "__slots__", "=", "containerNames", "self", ".", "_outputContainers", "[", "p", "]", "=", "SpecificIoContainer", "(", "outputs", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._scheduleCombUpdateDoneEv
Schedule combUpdateDoneEv event to let agents know that current delta step is ending and values from combinational logic are stable
hwt/simulator/hdlSimulator.py
def _scheduleCombUpdateDoneEv(self) -> Event: """ Schedule combUpdateDoneEv event to let agents know that current delta step is ending and values from combinational logic are stable """ assert not self._combUpdateDonePlaned, self.now cud = Event(self) cud.process_to_wake.append(self.__deleteCombUpdateDoneEv()) self._add_process(cud, PRIORITY_AGENTS_UPDATE_DONE) self._combUpdateDonePlaned = True self.combUpdateDoneEv = cud return cud
def _scheduleCombUpdateDoneEv(self) -> Event: """ Schedule combUpdateDoneEv event to let agents know that current delta step is ending and values from combinational logic are stable """ assert not self._combUpdateDonePlaned, self.now cud = Event(self) cud.process_to_wake.append(self.__deleteCombUpdateDoneEv()) self._add_process(cud, PRIORITY_AGENTS_UPDATE_DONE) self._combUpdateDonePlaned = True self.combUpdateDoneEv = cud return cud
[ "Schedule", "combUpdateDoneEv", "event", "to", "let", "agents", "know", "that", "current", "delta", "step", "is", "ending", "and", "values", "from", "combinational", "logic", "are", "stable" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L296-L307
[ "def", "_scheduleCombUpdateDoneEv", "(", "self", ")", "->", "Event", ":", "assert", "not", "self", ".", "_combUpdateDonePlaned", ",", "self", ".", "now", "cud", "=", "Event", "(", "self", ")", "cud", ".", "process_to_wake", ".", "append", "(", "self", ".", "__deleteCombUpdateDoneEv", "(", ")", ")", "self", ".", "_add_process", "(", "cud", ",", "PRIORITY_AGENTS_UPDATE_DONE", ")", "self", ".", "_combUpdateDonePlaned", "=", "True", "self", ".", "combUpdateDoneEv", "=", "cud", "return", "cud" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._scheduleApplyValues
Apply stashed values to signals
hwt/simulator/hdlSimulator.py
def _scheduleApplyValues(self) -> None: """ Apply stashed values to signals """ assert not self._applyValPlaned, self.now self._add_process(self._applyValues(), PRIORITY_APPLY_COMB) self._applyValPlaned = True if self._runSeqProcessesPlaned: # if runSeqProcesses is already scheduled return assert not self._seqProcsToRun and not self._runSeqProcessesPlaned, self.now self._add_process(self._runSeqProcesses(), PRIORITY_APPLY_SEQ) self._runSeqProcessesPlaned = True
def _scheduleApplyValues(self) -> None: """ Apply stashed values to signals """ assert not self._applyValPlaned, self.now self._add_process(self._applyValues(), PRIORITY_APPLY_COMB) self._applyValPlaned = True if self._runSeqProcessesPlaned: # if runSeqProcesses is already scheduled return assert not self._seqProcsToRun and not self._runSeqProcessesPlaned, self.now self._add_process(self._runSeqProcesses(), PRIORITY_APPLY_SEQ) self._runSeqProcessesPlaned = True
[ "Apply", "stashed", "values", "to", "signals" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L310-L324
[ "def", "_scheduleApplyValues", "(", "self", ")", "->", "None", ":", "assert", "not", "self", ".", "_applyValPlaned", ",", "self", ".", "now", "self", ".", "_add_process", "(", "self", ".", "_applyValues", "(", ")", ",", "PRIORITY_APPLY_COMB", ")", "self", ".", "_applyValPlaned", "=", "True", "if", "self", ".", "_runSeqProcessesPlaned", ":", "# if runSeqProcesses is already scheduled", "return", "assert", "not", "self", ".", "_seqProcsToRun", "and", "not", "self", ".", "_runSeqProcessesPlaned", ",", "self", ".", "now", "self", ".", "_add_process", "(", "self", ".", "_runSeqProcesses", "(", ")", ",", "PRIORITY_APPLY_SEQ", ")", "self", ".", "_runSeqProcessesPlaned", "=", "True" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._conflictResolveStrategy
This functions resolves write conflicts for signal :param actionSet: set of actions made by process
hwt/simulator/hdlSimulator.py
def _conflictResolveStrategy(self, newValue: set)\ -> Tuple[Callable[[Value], bool], bool]: """ This functions resolves write conflicts for signal :param actionSet: set of actions made by process """ invalidate = False resLen = len(newValue) if resLen == 3: # update for item in array val, indexes, isEvDependent = newValue return (mkArrayUpdater(val, indexes, invalidate), isEvDependent) else: # update for simple signal val, isEvDependent = newValue return (mkUpdater(val, invalidate), isEvDependent)
def _conflictResolveStrategy(self, newValue: set)\ -> Tuple[Callable[[Value], bool], bool]: """ This functions resolves write conflicts for signal :param actionSet: set of actions made by process """ invalidate = False resLen = len(newValue) if resLen == 3: # update for item in array val, indexes, isEvDependent = newValue return (mkArrayUpdater(val, indexes, invalidate), isEvDependent) else: # update for simple signal val, isEvDependent = newValue return (mkUpdater(val, invalidate), isEvDependent)
[ "This", "functions", "resolves", "write", "conflicts", "for", "signal" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L327-L344
[ "def", "_conflictResolveStrategy", "(", "self", ",", "newValue", ":", "set", ")", "->", "Tuple", "[", "Callable", "[", "[", "Value", "]", ",", "bool", "]", ",", "bool", "]", ":", "invalidate", "=", "False", "resLen", "=", "len", "(", "newValue", ")", "if", "resLen", "==", "3", ":", "# update for item in array", "val", ",", "indexes", ",", "isEvDependent", "=", "newValue", "return", "(", "mkArrayUpdater", "(", "val", ",", "indexes", ",", "invalidate", ")", ",", "isEvDependent", ")", "else", ":", "# update for simple signal", "val", ",", "isEvDependent", "=", "newValue", "return", "(", "mkUpdater", "(", "val", ",", "invalidate", ")", ",", "isEvDependent", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._runCombProcesses
Delta step for combinational processes
hwt/simulator/hdlSimulator.py
def _runCombProcesses(self) -> None: """ Delta step for combinational processes """ for proc in self._combProcsToRun: cont = self._outputContainers[proc] proc(self, cont) for sigName, sig in cont._all_signals: newVal = getattr(cont, sigName) if newVal is not None: res = self._conflictResolveStrategy(newVal) # prepare update updater, isEvDependent = res self._valuesToApply.append( (sig, updater, isEvDependent, proc)) setattr(cont, sigName, None) # else value is latched self._combProcsToRun = UniqList()
def _runCombProcesses(self) -> None: """ Delta step for combinational processes """ for proc in self._combProcsToRun: cont = self._outputContainers[proc] proc(self, cont) for sigName, sig in cont._all_signals: newVal = getattr(cont, sigName) if newVal is not None: res = self._conflictResolveStrategy(newVal) # prepare update updater, isEvDependent = res self._valuesToApply.append( (sig, updater, isEvDependent, proc)) setattr(cont, sigName, None) # else value is latched self._combProcsToRun = UniqList()
[ "Delta", "step", "for", "combinational", "processes" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L347-L365
[ "def", "_runCombProcesses", "(", "self", ")", "->", "None", ":", "for", "proc", "in", "self", ".", "_combProcsToRun", ":", "cont", "=", "self", ".", "_outputContainers", "[", "proc", "]", "proc", "(", "self", ",", "cont", ")", "for", "sigName", ",", "sig", "in", "cont", ".", "_all_signals", ":", "newVal", "=", "getattr", "(", "cont", ",", "sigName", ")", "if", "newVal", "is", "not", "None", ":", "res", "=", "self", ".", "_conflictResolveStrategy", "(", "newVal", ")", "# prepare update", "updater", ",", "isEvDependent", "=", "res", "self", ".", "_valuesToApply", ".", "append", "(", "(", "sig", ",", "updater", ",", "isEvDependent", ",", "proc", ")", ")", "setattr", "(", "cont", ",", "sigName", ",", "None", ")", "# else value is latched", "self", ".", "_combProcsToRun", "=", "UniqList", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._runSeqProcesses
Delta step for event dependent processes
hwt/simulator/hdlSimulator.py
def _runSeqProcesses(self) -> Generator[None, None, None]: """ Delta step for event dependent processes """ updates = [] for proc in self._seqProcsToRun: try: outContainer = self._outputContainers[proc] except KeyError: # processes does not have to have outputs outContainer = None proc(self, outContainer) if outContainer is not None: updates.append(outContainer) self._seqProcsToRun = UniqList() self._runSeqProcessesPlaned = False for cont in updates: for sigName, sig in cont._all_signals: newVal = getattr(cont, sigName) if newVal is not None: v = self._conflictResolveStrategy(newVal) updater, _ = v sig.simUpdateVal(self, updater) setattr(cont, sigName, None) return yield
def _runSeqProcesses(self) -> Generator[None, None, None]: """ Delta step for event dependent processes """ updates = [] for proc in self._seqProcsToRun: try: outContainer = self._outputContainers[proc] except KeyError: # processes does not have to have outputs outContainer = None proc(self, outContainer) if outContainer is not None: updates.append(outContainer) self._seqProcsToRun = UniqList() self._runSeqProcessesPlaned = False for cont in updates: for sigName, sig in cont._all_signals: newVal = getattr(cont, sigName) if newVal is not None: v = self._conflictResolveStrategy(newVal) updater, _ = v sig.simUpdateVal(self, updater) setattr(cont, sigName, None) return yield
[ "Delta", "step", "for", "event", "dependent", "processes" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L368-L397
[ "def", "_runSeqProcesses", "(", "self", ")", "->", "Generator", "[", "None", ",", "None", ",", "None", "]", ":", "updates", "=", "[", "]", "for", "proc", "in", "self", ".", "_seqProcsToRun", ":", "try", ":", "outContainer", "=", "self", ".", "_outputContainers", "[", "proc", "]", "except", "KeyError", ":", "# processes does not have to have outputs", "outContainer", "=", "None", "proc", "(", "self", ",", "outContainer", ")", "if", "outContainer", "is", "not", "None", ":", "updates", ".", "append", "(", "outContainer", ")", "self", ".", "_seqProcsToRun", "=", "UniqList", "(", ")", "self", ".", "_runSeqProcessesPlaned", "=", "False", "for", "cont", "in", "updates", ":", "for", "sigName", ",", "sig", "in", "cont", ".", "_all_signals", ":", "newVal", "=", "getattr", "(", "cont", ",", "sigName", ")", "if", "newVal", "is", "not", "None", ":", "v", "=", "self", ".", "_conflictResolveStrategy", "(", "newVal", ")", "updater", ",", "_", "=", "v", "sig", ".", "simUpdateVal", "(", "self", ",", "updater", ")", "setattr", "(", "cont", ",", "sigName", ",", "None", ")", "return", "yield" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator._applyValues
Perform delta step by writing stacked values to signals
hwt/simulator/hdlSimulator.py
def _applyValues(self) -> Generator[None, None, None]: """ Perform delta step by writing stacked values to signals """ va = self._valuesToApply self._applyValPlaned = False # log if there are items to log lav = self.config.logApplyingValues if va and lav: lav(self, va) self._valuesToApply = [] # apply values to signals, values can overwrite each other # but each signal should be driven by only one process and # it should resolve value collision addSp = self._seqProcsToRun.append for s, vUpdater, isEventDependent, comesFrom in va: if isEventDependent: # now=0 and this was process initialization or async reg addSp(comesFrom) else: # regular combinational process s.simUpdateVal(self, vUpdater) self._runCombProcesses() # processes triggered from simUpdateVal can add new values if self._valuesToApply and not self._applyValPlaned: self._scheduleApplyValues() return yield
def _applyValues(self) -> Generator[None, None, None]: """ Perform delta step by writing stacked values to signals """ va = self._valuesToApply self._applyValPlaned = False # log if there are items to log lav = self.config.logApplyingValues if va and lav: lav(self, va) self._valuesToApply = [] # apply values to signals, values can overwrite each other # but each signal should be driven by only one process and # it should resolve value collision addSp = self._seqProcsToRun.append for s, vUpdater, isEventDependent, comesFrom in va: if isEventDependent: # now=0 and this was process initialization or async reg addSp(comesFrom) else: # regular combinational process s.simUpdateVal(self, vUpdater) self._runCombProcesses() # processes triggered from simUpdateVal can add new values if self._valuesToApply and not self._applyValPlaned: self._scheduleApplyValues() return yield
[ "Perform", "delta", "step", "by", "writing", "stacked", "values", "to", "signals" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L400-L432
[ "def", "_applyValues", "(", "self", ")", "->", "Generator", "[", "None", ",", "None", ",", "None", "]", ":", "va", "=", "self", ".", "_valuesToApply", "self", ".", "_applyValPlaned", "=", "False", "# log if there are items to log", "lav", "=", "self", ".", "config", ".", "logApplyingValues", "if", "va", "and", "lav", ":", "lav", "(", "self", ",", "va", ")", "self", ".", "_valuesToApply", "=", "[", "]", "# apply values to signals, values can overwrite each other", "# but each signal should be driven by only one process and", "# it should resolve value collision", "addSp", "=", "self", ".", "_seqProcsToRun", ".", "append", "for", "s", ",", "vUpdater", ",", "isEventDependent", ",", "comesFrom", "in", "va", ":", "if", "isEventDependent", ":", "# now=0 and this was process initialization or async reg", "addSp", "(", "comesFrom", ")", "else", ":", "# regular combinational process", "s", ".", "simUpdateVal", "(", "self", ",", "vUpdater", ")", "self", ".", "_runCombProcesses", "(", ")", "# processes triggered from simUpdateVal can add new values", "if", "self", ".", "_valuesToApply", "and", "not", "self", ".", "_applyValPlaned", ":", "self", ".", "_scheduleApplyValues", "(", ")", "return", "yield" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator.read
Read value from signal or interface
hwt/simulator/hdlSimulator.py
def read(self, sig) -> Value: """ Read value from signal or interface """ try: v = sig._val except AttributeError: v = sig._sigInside._val return v.clone()
def read(self, sig) -> Value: """ Read value from signal or interface """ try: v = sig._val except AttributeError: v = sig._sigInside._val return v.clone()
[ "Read", "value", "from", "signal", "or", "interface" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L434-L443
[ "def", "read", "(", "self", ",", "sig", ")", "->", "Value", ":", "try", ":", "v", "=", "sig", ".", "_val", "except", "AttributeError", ":", "v", "=", "sig", ".", "_sigInside", ".", "_val", "return", "v", ".", "clone", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator.write
Write value to signal or interface.
hwt/simulator/hdlSimulator.py
def write(self, val, sig: SimSignal)-> None: """ Write value to signal or interface. """ # get target RtlSignal try: simSensProcs = sig.simSensProcs except AttributeError: sig = sig._sigInside simSensProcs = sig.simSensProcs # type cast of input value t = sig._dtype if isinstance(val, Value): v = val.clone() v = v._auto_cast(t) else: v = t.fromPy(val) # can not update value in signal directly due singnal proxies sig.simUpdateVal(self, lambda curentV: ( valueHasChanged(curentV, v), v)) if not self._applyValPlaned: if not (simSensProcs or sig.simRisingSensProcs or sig.simFallingSensProcs): # signal value was changed but there are no sensitive processes # to it because of this _applyValues is never planed # and should be self._scheduleApplyValues() elif (sig._writeCallbacks or sig._writeCallbacksToEn): # signal write did not caused any change on any other signal # but there are still simulation agets waiting on # updateComplete event self._scheduleApplyValues()
def write(self, val, sig: SimSignal)-> None: """ Write value to signal or interface. """ # get target RtlSignal try: simSensProcs = sig.simSensProcs except AttributeError: sig = sig._sigInside simSensProcs = sig.simSensProcs # type cast of input value t = sig._dtype if isinstance(val, Value): v = val.clone() v = v._auto_cast(t) else: v = t.fromPy(val) # can not update value in signal directly due singnal proxies sig.simUpdateVal(self, lambda curentV: ( valueHasChanged(curentV, v), v)) if not self._applyValPlaned: if not (simSensProcs or sig.simRisingSensProcs or sig.simFallingSensProcs): # signal value was changed but there are no sensitive processes # to it because of this _applyValues is never planed # and should be self._scheduleApplyValues() elif (sig._writeCallbacks or sig._writeCallbacksToEn): # signal write did not caused any change on any other signal # but there are still simulation agets waiting on # updateComplete event self._scheduleApplyValues()
[ "Write", "value", "to", "signal", "or", "interface", "." ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L445-L482
[ "def", "write", "(", "self", ",", "val", ",", "sig", ":", "SimSignal", ")", "->", "None", ":", "# get target RtlSignal", "try", ":", "simSensProcs", "=", "sig", ".", "simSensProcs", "except", "AttributeError", ":", "sig", "=", "sig", ".", "_sigInside", "simSensProcs", "=", "sig", ".", "simSensProcs", "# type cast of input value", "t", "=", "sig", ".", "_dtype", "if", "isinstance", "(", "val", ",", "Value", ")", ":", "v", "=", "val", ".", "clone", "(", ")", "v", "=", "v", ".", "_auto_cast", "(", "t", ")", "else", ":", "v", "=", "t", ".", "fromPy", "(", "val", ")", "# can not update value in signal directly due singnal proxies", "sig", ".", "simUpdateVal", "(", "self", ",", "lambda", "curentV", ":", "(", "valueHasChanged", "(", "curentV", ",", "v", ")", ",", "v", ")", ")", "if", "not", "self", ".", "_applyValPlaned", ":", "if", "not", "(", "simSensProcs", "or", "sig", ".", "simRisingSensProcs", "or", "sig", ".", "simFallingSensProcs", ")", ":", "# signal value was changed but there are no sensitive processes", "# to it because of this _applyValues is never planed", "# and should be", "self", ".", "_scheduleApplyValues", "(", ")", "elif", "(", "sig", ".", "_writeCallbacks", "or", "sig", ".", "_writeCallbacksToEn", ")", ":", "# signal write did not caused any change on any other signal", "# but there are still simulation agets waiting on", "# updateComplete event", "self", ".", "_scheduleApplyValues", "(", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator.run
Run simulation until specified time :note: can be used to run simulation again after it ends from time when it ends
hwt/simulator/hdlSimulator.py
def run(self, until: float) -> None: """ Run simulation until specified time :note: can be used to run simulation again after it ends from time when it ends """ assert until > self.now events = self._events schedule = events.push next_event = events.pop # add handle to stop simulation schedule(until, PRIORITY_URGENT, raise_StopSimulation(self)) try: # for all events while True: nextTime, priority, process = next_event() self.now = nextTime # process is python generator or Event if isinstance(process, Event): process = iter(process) # run process or activate processes dependent on Event while True: try: ev = next(process) except StopIteration: break # if process requires waiting put it back in queue if isinstance(ev, Wait): # nextTime is self.now schedule(nextTime + ev.time, priority, process) break elif isinstance(ev, Event): # process going to wait for event # if ev.process_to_wake is None event was already # destroyed ev.process_to_wake.append(process) break else: # else this process spoted new process # and it has to be put in queue schedule(nextTime, priority, ev) except StopSimumulation: return
def run(self, until: float) -> None: """ Run simulation until specified time :note: can be used to run simulation again after it ends from time when it ends """ assert until > self.now events = self._events schedule = events.push next_event = events.pop # add handle to stop simulation schedule(until, PRIORITY_URGENT, raise_StopSimulation(self)) try: # for all events while True: nextTime, priority, process = next_event() self.now = nextTime # process is python generator or Event if isinstance(process, Event): process = iter(process) # run process or activate processes dependent on Event while True: try: ev = next(process) except StopIteration: break # if process requires waiting put it back in queue if isinstance(ev, Wait): # nextTime is self.now schedule(nextTime + ev.time, priority, process) break elif isinstance(ev, Event): # process going to wait for event # if ev.process_to_wake is None event was already # destroyed ev.process_to_wake.append(process) break else: # else this process spoted new process # and it has to be put in queue schedule(nextTime, priority, ev) except StopSimumulation: return
[ "Run", "simulation", "until", "specified", "time", ":", "note", ":", "can", "be", "used", "to", "run", "simulation", "again", "after", "it", "ends", "from", "time", "when", "it", "ends" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L484-L530
[ "def", "run", "(", "self", ",", "until", ":", "float", ")", "->", "None", ":", "assert", "until", ">", "self", ".", "now", "events", "=", "self", ".", "_events", "schedule", "=", "events", ".", "push", "next_event", "=", "events", ".", "pop", "# add handle to stop simulation", "schedule", "(", "until", ",", "PRIORITY_URGENT", ",", "raise_StopSimulation", "(", "self", ")", ")", "try", ":", "# for all events", "while", "True", ":", "nextTime", ",", "priority", ",", "process", "=", "next_event", "(", ")", "self", ".", "now", "=", "nextTime", "# process is python generator or Event", "if", "isinstance", "(", "process", ",", "Event", ")", ":", "process", "=", "iter", "(", "process", ")", "# run process or activate processes dependent on Event", "while", "True", ":", "try", ":", "ev", "=", "next", "(", "process", ")", "except", "StopIteration", ":", "break", "# if process requires waiting put it back in queue", "if", "isinstance", "(", "ev", ",", "Wait", ")", ":", "# nextTime is self.now", "schedule", "(", "nextTime", "+", "ev", ".", "time", ",", "priority", ",", "process", ")", "break", "elif", "isinstance", "(", "ev", ",", "Event", ")", ":", "# process going to wait for event", "# if ev.process_to_wake is None event was already", "# destroyed", "ev", ".", "process_to_wake", ".", "append", "(", "process", ")", "break", "else", ":", "# else this process spoted new process", "# and it has to be put in queue", "schedule", "(", "nextTime", ",", "priority", ",", "ev", ")", "except", "StopSimumulation", ":", "return" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator.add_process
Add process to events with default priority on current time
hwt/simulator/hdlSimulator.py
def add_process(self, proc) -> None: """ Add process to events with default priority on current time """ self._events.push(self.now, PRIORITY_NORMAL, proc)
def add_process(self, proc) -> None: """ Add process to events with default priority on current time """ self._events.push(self.now, PRIORITY_NORMAL, proc)
[ "Add", "process", "to", "events", "with", "default", "priority", "on", "current", "time" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L532-L536
[ "def", "add_process", "(", "self", ",", "proc", ")", "->", "None", ":", "self", ".", "_events", ".", "push", "(", "self", ".", "now", ",", "PRIORITY_NORMAL", ",", "proc", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
HdlSimulator.simUnit
Run simulation for Unit instance
hwt/simulator/hdlSimulator.py
def simUnit(self, synthesisedUnit: Unit, until: float, extraProcesses=[]): """ Run simulation for Unit instance """ beforeSim = self.config.beforeSim if beforeSim is not None: beforeSim(self, synthesisedUnit) add_proc = self.add_process for p in extraProcesses: add_proc(p(self)) self._initUnitSignals(synthesisedUnit) self.run(until)
def simUnit(self, synthesisedUnit: Unit, until: float, extraProcesses=[]): """ Run simulation for Unit instance """ beforeSim = self.config.beforeSim if beforeSim is not None: beforeSim(self, synthesisedUnit) add_proc = self.add_process for p in extraProcesses: add_proc(p(self)) self._initUnitSignals(synthesisedUnit) self.run(until)
[ "Run", "simulation", "for", "Unit", "instance" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L538-L551
[ "def", "simUnit", "(", "self", ",", "synthesisedUnit", ":", "Unit", ",", "until", ":", "float", ",", "extraProcesses", "=", "[", "]", ")", ":", "beforeSim", "=", "self", ".", "config", ".", "beforeSim", "if", "beforeSim", "is", "not", "None", ":", "beforeSim", "(", "self", ",", "synthesisedUnit", ")", "add_proc", "=", "self", ".", "add_process", "for", "p", "in", "extraProcesses", ":", "add_proc", "(", "p", "(", "self", ")", ")", "self", ".", "_initUnitSignals", "(", "synthesisedUnit", ")", "self", ".", "run", "(", "until", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
_mkOp
Function to create variadic operator function :param fn: function to perform binary operation
hwt/code_utils.py
def _mkOp(fn): """ Function to create variadic operator function :param fn: function to perform binary operation """ def op(*operands, key=None) -> RtlSignalBase: """ :param operands: variadic parameter of input uperands :param key: optional function applied on every operand before processing """ assert operands, operands top = None if key is not None: operands = map(key, operands) for s in operands: if top is None: top = s else: top = fn(top, s) return top return op
def _mkOp(fn): """ Function to create variadic operator function :param fn: function to perform binary operation """ def op(*operands, key=None) -> RtlSignalBase: """ :param operands: variadic parameter of input uperands :param key: optional function applied on every operand before processing """ assert operands, operands top = None if key is not None: operands = map(key, operands) for s in operands: if top is None: top = s else: top = fn(top, s) return top return op
[ "Function", "to", "create", "variadic", "operator", "function" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/code_utils.py#L38-L62
[ "def", "_mkOp", "(", "fn", ")", ":", "def", "op", "(", "*", "operands", ",", "key", "=", "None", ")", "->", "RtlSignalBase", ":", "\"\"\"\n :param operands: variadic parameter of input uperands\n :param key: optional function applied on every operand\n before processing\n \"\"\"", "assert", "operands", ",", "operands", "top", "=", "None", "if", "key", "is", "not", "None", ":", "operands", "=", "map", "(", "key", ",", "operands", ")", "for", "s", "in", "operands", ":", "if", "top", "is", "None", ":", "top", "=", "s", "else", ":", "top", "=", "fn", "(", "top", ",", "s", ")", "return", "top", "return", "op" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
systemCTypeOfSig
Check if is register or wire
hwt/serializer/systemC/utils.py
def systemCTypeOfSig(signalItem): """ Check if is register or wire """ if signalItem._const or\ arr_any(signalItem.drivers, lambda d: isinstance(d, HdlStatement) and d._now_is_event_dependent): return SIGNAL_TYPE.REG else: return SIGNAL_TYPE.WIRE
def systemCTypeOfSig(signalItem): """ Check if is register or wire """ if signalItem._const or\ arr_any(signalItem.drivers, lambda d: isinstance(d, HdlStatement) and d._now_is_event_dependent): return SIGNAL_TYPE.REG else: return SIGNAL_TYPE.WIRE
[ "Check", "if", "is", "register", "or", "wire" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/systemC/utils.py#L6-L17
[ "def", "systemCTypeOfSig", "(", "signalItem", ")", ":", "if", "signalItem", ".", "_const", "or", "arr_any", "(", "signalItem", ".", "drivers", ",", "lambda", "d", ":", "isinstance", "(", "d", ",", "HdlStatement", ")", "and", "d", ".", "_now_is_event_dependent", ")", ":", "return", "SIGNAL_TYPE", ".", "REG", "else", ":", "return", "SIGNAL_TYPE", ".", "WIRE" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
ternaryOpsToIf
Convert all ternary operators to IfContainers
hwt/serializer/vhdl/statements.py
def ternaryOpsToIf(statements): """Convert all ternary operators to IfContainers""" stms = [] for st in statements: if isinstance(st, Assignment): try: if not isinstance(st.src, RtlSignalBase): raise DoesNotContainsTernary() d = st.src.singleDriver() if not isinstance(d, Operator) or d.operator != AllOps.TERNARY: raise DoesNotContainsTernary() else: ops = d.operands ifc = IfContainer(ops[0], [Assignment(ops[1], st.dst)], [Assignment(ops[2], st.dst)] ) stms.append(ifc) continue except (MultipleDriversErr, DoesNotContainsTernary): pass except NoDriverErr: assert (hasattr(st.src, "_interface") and st.src._interface is not None)\ or st.src.defVal.vldMask, st.src stms.append(st) return stms
def ternaryOpsToIf(statements): """Convert all ternary operators to IfContainers""" stms = [] for st in statements: if isinstance(st, Assignment): try: if not isinstance(st.src, RtlSignalBase): raise DoesNotContainsTernary() d = st.src.singleDriver() if not isinstance(d, Operator) or d.operator != AllOps.TERNARY: raise DoesNotContainsTernary() else: ops = d.operands ifc = IfContainer(ops[0], [Assignment(ops[1], st.dst)], [Assignment(ops[2], st.dst)] ) stms.append(ifc) continue except (MultipleDriversErr, DoesNotContainsTernary): pass except NoDriverErr: assert (hasattr(st.src, "_interface") and st.src._interface is not None)\ or st.src.defVal.vldMask, st.src stms.append(st) return stms
[ "Convert", "all", "ternary", "operators", "to", "IfContainers" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/vhdl/statements.py#L30-L59
[ "def", "ternaryOpsToIf", "(", "statements", ")", ":", "stms", "=", "[", "]", "for", "st", "in", "statements", ":", "if", "isinstance", "(", "st", ",", "Assignment", ")", ":", "try", ":", "if", "not", "isinstance", "(", "st", ".", "src", ",", "RtlSignalBase", ")", ":", "raise", "DoesNotContainsTernary", "(", ")", "d", "=", "st", ".", "src", ".", "singleDriver", "(", ")", "if", "not", "isinstance", "(", "d", ",", "Operator", ")", "or", "d", ".", "operator", "!=", "AllOps", ".", "TERNARY", ":", "raise", "DoesNotContainsTernary", "(", ")", "else", ":", "ops", "=", "d", ".", "operands", "ifc", "=", "IfContainer", "(", "ops", "[", "0", "]", ",", "[", "Assignment", "(", "ops", "[", "1", "]", ",", "st", ".", "dst", ")", "]", ",", "[", "Assignment", "(", "ops", "[", "2", "]", ",", "st", ".", "dst", ")", "]", ")", "stms", ".", "append", "(", "ifc", ")", "continue", "except", "(", "MultipleDriversErr", ",", "DoesNotContainsTernary", ")", ":", "pass", "except", "NoDriverErr", ":", "assert", "(", "hasattr", "(", "st", ".", "src", ",", "\"_interface\"", ")", "and", "st", ".", "src", ".", "_interface", "is", "not", "None", ")", "or", "st", ".", "src", ".", "defVal", ".", "vldMask", ",", "st", ".", "src", "stms", ".", "append", "(", "st", ")", "return", "stms" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
VhdlSerializer_statements.HWProcess
Serialize HWProcess objects as VHDL :param scope: name scope to prevent name collisions
hwt/serializer/vhdl/statements.py
def HWProcess(cls, proc, ctx): """ Serialize HWProcess objects as VHDL :param scope: name scope to prevent name collisions """ body = proc.statements extraVars = [] extraVarsSerialized = [] hasToBeVhdlProcess = arr_any(body, lambda x: isinstance(x, (IfContainer, SwitchContainer, WhileContainer, WaitStm))) sensitivityList = sorted( map(lambda s: cls.sensitivityListItem(s, ctx), proc.sensitivityList)) if hasToBeVhdlProcess: childCtx = ctx.withIndent() else: childCtx = copy(ctx) def createTmpVarFn(suggestedName, dtype): s = RtlSignal(None, None, dtype, virtualOnly=True) s.name = ctx.scope.checkedName(suggestedName, s) s.hidden = False serializedS = cls.SignalItem(s, childCtx, declaration=True) extraVars.append(s) extraVarsSerialized.append(serializedS) return s childCtx.createTmpVarFn = createTmpVarFn statemets = [cls.asHdl(s, childCtx) for s in body] proc.name = ctx.scope.checkedName(proc.name, proc) extraVarsInit = [] for s in extraVars: if isinstance(s.defVal, RtlSignalBase) or s.defVal.vldMask: a = Assignment(s.defVal, s, virtualOnly=True) extraVarsInit.append(cls.Assignment(a, childCtx)) else: assert s.drivers, s for d in s.drivers: extraVarsInit.append(cls.asHdl(d, childCtx)) _hasToBeVhdlProcess = hasToBeVhdlProcess hasToBeVhdlProcess = extraVars or hasToBeVhdlProcess if hasToBeVhdlProcess and not _hasToBeVhdlProcess: # add indent because we did not added it before because we did not # know t oneIndent = getIndent(1) statemets = list(map(lambda x: oneIndent + x, statemets)) return cls.processTmpl.render( indent=getIndent(ctx.indent), name=proc.name, hasToBeVhdlProcess=hasToBeVhdlProcess, extraVars=extraVarsSerialized, sensitivityList=", ".join(sensitivityList), statements=extraVarsInit + statemets )
def HWProcess(cls, proc, ctx): """ Serialize HWProcess objects as VHDL :param scope: name scope to prevent name collisions """ body = proc.statements extraVars = [] extraVarsSerialized = [] hasToBeVhdlProcess = arr_any(body, lambda x: isinstance(x, (IfContainer, SwitchContainer, WhileContainer, WaitStm))) sensitivityList = sorted( map(lambda s: cls.sensitivityListItem(s, ctx), proc.sensitivityList)) if hasToBeVhdlProcess: childCtx = ctx.withIndent() else: childCtx = copy(ctx) def createTmpVarFn(suggestedName, dtype): s = RtlSignal(None, None, dtype, virtualOnly=True) s.name = ctx.scope.checkedName(suggestedName, s) s.hidden = False serializedS = cls.SignalItem(s, childCtx, declaration=True) extraVars.append(s) extraVarsSerialized.append(serializedS) return s childCtx.createTmpVarFn = createTmpVarFn statemets = [cls.asHdl(s, childCtx) for s in body] proc.name = ctx.scope.checkedName(proc.name, proc) extraVarsInit = [] for s in extraVars: if isinstance(s.defVal, RtlSignalBase) or s.defVal.vldMask: a = Assignment(s.defVal, s, virtualOnly=True) extraVarsInit.append(cls.Assignment(a, childCtx)) else: assert s.drivers, s for d in s.drivers: extraVarsInit.append(cls.asHdl(d, childCtx)) _hasToBeVhdlProcess = hasToBeVhdlProcess hasToBeVhdlProcess = extraVars or hasToBeVhdlProcess if hasToBeVhdlProcess and not _hasToBeVhdlProcess: # add indent because we did not added it before because we did not # know t oneIndent = getIndent(1) statemets = list(map(lambda x: oneIndent + x, statemets)) return cls.processTmpl.render( indent=getIndent(ctx.indent), name=proc.name, hasToBeVhdlProcess=hasToBeVhdlProcess, extraVars=extraVarsSerialized, sensitivityList=", ".join(sensitivityList), statements=extraVarsInit + statemets )
[ "Serialize", "HWProcess", "objects", "as", "VHDL" ]
Nic30/hwt
python
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/vhdl/statements.py#L109-L175
[ "def", "HWProcess", "(", "cls", ",", "proc", ",", "ctx", ")", ":", "body", "=", "proc", ".", "statements", "extraVars", "=", "[", "]", "extraVarsSerialized", "=", "[", "]", "hasToBeVhdlProcess", "=", "arr_any", "(", "body", ",", "lambda", "x", ":", "isinstance", "(", "x", ",", "(", "IfContainer", ",", "SwitchContainer", ",", "WhileContainer", ",", "WaitStm", ")", ")", ")", "sensitivityList", "=", "sorted", "(", "map", "(", "lambda", "s", ":", "cls", ".", "sensitivityListItem", "(", "s", ",", "ctx", ")", ",", "proc", ".", "sensitivityList", ")", ")", "if", "hasToBeVhdlProcess", ":", "childCtx", "=", "ctx", ".", "withIndent", "(", ")", "else", ":", "childCtx", "=", "copy", "(", "ctx", ")", "def", "createTmpVarFn", "(", "suggestedName", ",", "dtype", ")", ":", "s", "=", "RtlSignal", "(", "None", ",", "None", ",", "dtype", ",", "virtualOnly", "=", "True", ")", "s", ".", "name", "=", "ctx", ".", "scope", ".", "checkedName", "(", "suggestedName", ",", "s", ")", "s", ".", "hidden", "=", "False", "serializedS", "=", "cls", ".", "SignalItem", "(", "s", ",", "childCtx", ",", "declaration", "=", "True", ")", "extraVars", ".", "append", "(", "s", ")", "extraVarsSerialized", ".", "append", "(", "serializedS", ")", "return", "s", "childCtx", ".", "createTmpVarFn", "=", "createTmpVarFn", "statemets", "=", "[", "cls", ".", "asHdl", "(", "s", ",", "childCtx", ")", "for", "s", "in", "body", "]", "proc", ".", "name", "=", "ctx", ".", "scope", ".", "checkedName", "(", "proc", ".", "name", ",", "proc", ")", "extraVarsInit", "=", "[", "]", "for", "s", "in", "extraVars", ":", "if", "isinstance", "(", "s", ".", "defVal", ",", "RtlSignalBase", ")", "or", "s", ".", "defVal", ".", "vldMask", ":", "a", "=", "Assignment", "(", "s", ".", "defVal", ",", "s", ",", "virtualOnly", "=", "True", ")", "extraVarsInit", ".", "append", "(", "cls", ".", "Assignment", "(", "a", ",", "childCtx", ")", ")", "else", ":", "assert", "s", ".", "drivers", ",", "s", "for", "d", "in", "s", ".", "drivers", ":", "extraVarsInit", ".", "append", "(", "cls", ".", "asHdl", "(", "d", ",", "childCtx", ")", ")", "_hasToBeVhdlProcess", "=", "hasToBeVhdlProcess", "hasToBeVhdlProcess", "=", "extraVars", "or", "hasToBeVhdlProcess", "if", "hasToBeVhdlProcess", "and", "not", "_hasToBeVhdlProcess", ":", "# add indent because we did not added it before because we did not", "# know t", "oneIndent", "=", "getIndent", "(", "1", ")", "statemets", "=", "list", "(", "map", "(", "lambda", "x", ":", "oneIndent", "+", "x", ",", "statemets", ")", ")", "return", "cls", ".", "processTmpl", ".", "render", "(", "indent", "=", "getIndent", "(", "ctx", ".", "indent", ")", ",", "name", "=", "proc", ".", "name", ",", "hasToBeVhdlProcess", "=", "hasToBeVhdlProcess", ",", "extraVars", "=", "extraVarsSerialized", ",", "sensitivityList", "=", "\", \"", ".", "join", "(", "sensitivityList", ")", ",", "statements", "=", "extraVarsInit", "+", "statemets", ")" ]
8cbb399e326da3b22c233b98188a9d08dec057e6
test
hash_distance
Compute the hamming distance between two hashes
photohash/photohash.py
def hash_distance(left_hash, right_hash): """Compute the hamming distance between two hashes""" if len(left_hash) != len(right_hash): raise ValueError('Hamming distance requires two strings of equal length') return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(left_hash, right_hash)))
def hash_distance(left_hash, right_hash): """Compute the hamming distance between two hashes""" if len(left_hash) != len(right_hash): raise ValueError('Hamming distance requires two strings of equal length') return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(left_hash, right_hash)))
[ "Compute", "the", "hamming", "distance", "between", "two", "hashes" ]
bunchesofdonald/photohash
python
https://github.com/bunchesofdonald/photohash/blob/1839a37a884e8c31cb94e661bd76f8125b0dfcb6/photohash/photohash.py#L6-L11
[ "def", "hash_distance", "(", "left_hash", ",", "right_hash", ")", ":", "if", "len", "(", "left_hash", ")", "!=", "len", "(", "right_hash", ")", ":", "raise", "ValueError", "(", "'Hamming distance requires two strings of equal length'", ")", "return", "sum", "(", "map", "(", "lambda", "x", ":", "0", "if", "x", "[", "0", "]", "==", "x", "[", "1", "]", "else", "1", ",", "zip", "(", "left_hash", ",", "right_hash", ")", ")", ")" ]
1839a37a884e8c31cb94e661bd76f8125b0dfcb6
test
average_hash
Compute the average hash of the given image.
photohash/photohash.py
def average_hash(image_path, hash_size=8): """ Compute the average hash of the given image. """ with open(image_path, 'rb') as f: # Open the image, resize it and convert it to black & white. image = Image.open(f).resize((hash_size, hash_size), Image.ANTIALIAS).convert('L') pixels = list(image.getdata()) avg = sum(pixels) / len(pixels) # Compute the hash based on each pixels value compared to the average. bits = "".join(map(lambda pixel: '1' if pixel > avg else '0', pixels)) hashformat = "0{hashlength}x".format(hashlength=hash_size ** 2 // 4) return int(bits, 2).__format__(hashformat)
def average_hash(image_path, hash_size=8): """ Compute the average hash of the given image. """ with open(image_path, 'rb') as f: # Open the image, resize it and convert it to black & white. image = Image.open(f).resize((hash_size, hash_size), Image.ANTIALIAS).convert('L') pixels = list(image.getdata()) avg = sum(pixels) / len(pixels) # Compute the hash based on each pixels value compared to the average. bits = "".join(map(lambda pixel: '1' if pixel > avg else '0', pixels)) hashformat = "0{hashlength}x".format(hashlength=hash_size ** 2 // 4) return int(bits, 2).__format__(hashformat)
[ "Compute", "the", "average", "hash", "of", "the", "given", "image", "." ]
bunchesofdonald/photohash
python
https://github.com/bunchesofdonald/photohash/blob/1839a37a884e8c31cb94e661bd76f8125b0dfcb6/photohash/photohash.py#L22-L34
[ "def", "average_hash", "(", "image_path", ",", "hash_size", "=", "8", ")", ":", "with", "open", "(", "image_path", ",", "'rb'", ")", "as", "f", ":", "# Open the image, resize it and convert it to black & white.", "image", "=", "Image", ".", "open", "(", "f", ")", ".", "resize", "(", "(", "hash_size", ",", "hash_size", ")", ",", "Image", ".", "ANTIALIAS", ")", ".", "convert", "(", "'L'", ")", "pixels", "=", "list", "(", "image", ".", "getdata", "(", ")", ")", "avg", "=", "sum", "(", "pixels", ")", "/", "len", "(", "pixels", ")", "# Compute the hash based on each pixels value compared to the average.", "bits", "=", "\"\"", ".", "join", "(", "map", "(", "lambda", "pixel", ":", "'1'", "if", "pixel", ">", "avg", "else", "'0'", ",", "pixels", ")", ")", "hashformat", "=", "\"0{hashlength}x\"", ".", "format", "(", "hashlength", "=", "hash_size", "**", "2", "//", "4", ")", "return", "int", "(", "bits", ",", "2", ")", ".", "__format__", "(", "hashformat", ")" ]
1839a37a884e8c31cb94e661bd76f8125b0dfcb6
test
distance
Compute the hamming distance between two images
photohash/photohash.py
def distance(image_path, other_image_path): """ Compute the hamming distance between two images""" image_hash = average_hash(image_path) other_image_hash = average_hash(other_image_path) return hash_distance(image_hash, other_image_hash)
def distance(image_path, other_image_path): """ Compute the hamming distance between two images""" image_hash = average_hash(image_path) other_image_hash = average_hash(other_image_path) return hash_distance(image_hash, other_image_hash)
[ "Compute", "the", "hamming", "distance", "between", "two", "images" ]
bunchesofdonald/photohash
python
https://github.com/bunchesofdonald/photohash/blob/1839a37a884e8c31cb94e661bd76f8125b0dfcb6/photohash/photohash.py#L37-L42
[ "def", "distance", "(", "image_path", ",", "other_image_path", ")", ":", "image_hash", "=", "average_hash", "(", "image_path", ")", "other_image_hash", "=", "average_hash", "(", "other_image_path", ")", "return", "hash_distance", "(", "image_hash", ",", "other_image_hash", ")" ]
1839a37a884e8c31cb94e661bd76f8125b0dfcb6
test
setup_platform
Set up the Vizio media player platform.
custom_components/vizio/media_player.py
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vizio media player platform.""" host = config.get(CONF_HOST) token = config.get(CONF_ACCESS_TOKEN) name = config.get(CONF_NAME) volume_step = config.get(CONF_VOLUME_STEP) device_type = config.get(CONF_DEVICE_CLASS) device = VizioDevice(host, token, name, volume_step, device_type) if device.validate_setup() is False: _LOGGER.error("Failed to set up Vizio platform, " "please check if host and API key are correct") return elif (token is None or token == "") and device_type == "tv": _LOGGER.error("Failed to set up Vizio platform, " "if device_class is 'tv' then an auth_token needs " "to be provided, otherwise if device_class is " "'soundbar' then add the right device_class to config") return if config.get(CONF_SUPPRESS_WARNING): from requests.packages import urllib3 _LOGGER.warning("InsecureRequestWarning is disabled " "because of Vizio platform configuration") urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) add_entities([device], True)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vizio media player platform.""" host = config.get(CONF_HOST) token = config.get(CONF_ACCESS_TOKEN) name = config.get(CONF_NAME) volume_step = config.get(CONF_VOLUME_STEP) device_type = config.get(CONF_DEVICE_CLASS) device = VizioDevice(host, token, name, volume_step, device_type) if device.validate_setup() is False: _LOGGER.error("Failed to set up Vizio platform, " "please check if host and API key are correct") return elif (token is None or token == "") and device_type == "tv": _LOGGER.error("Failed to set up Vizio platform, " "if device_class is 'tv' then an auth_token needs " "to be provided, otherwise if device_class is " "'soundbar' then add the right device_class to config") return if config.get(CONF_SUPPRESS_WARNING): from requests.packages import urllib3 _LOGGER.warning("InsecureRequestWarning is disabled " "because of Vizio platform configuration") urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) add_entities([device], True)
[ "Set", "up", "the", "Vizio", "media", "player", "platform", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L87-L111
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "host", "=", "config", ".", "get", "(", "CONF_HOST", ")", "token", "=", "config", ".", "get", "(", "CONF_ACCESS_TOKEN", ")", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "volume_step", "=", "config", ".", "get", "(", "CONF_VOLUME_STEP", ")", "device_type", "=", "config", ".", "get", "(", "CONF_DEVICE_CLASS", ")", "device", "=", "VizioDevice", "(", "host", ",", "token", ",", "name", ",", "volume_step", ",", "device_type", ")", "if", "device", ".", "validate_setup", "(", ")", "is", "False", ":", "_LOGGER", ".", "error", "(", "\"Failed to set up Vizio platform, \"", "\"please check if host and API key are correct\"", ")", "return", "elif", "(", "token", "is", "None", "or", "token", "==", "\"\"", ")", "and", "device_type", "==", "\"tv\"", ":", "_LOGGER", ".", "error", "(", "\"Failed to set up Vizio platform, \"", "\"if device_class is 'tv' then an auth_token needs \"", "\"to be provided, otherwise if device_class is \"", "\"'soundbar' then add the right device_class to config\"", ")", "return", "if", "config", ".", "get", "(", "CONF_SUPPRESS_WARNING", ")", ":", "from", "requests", ".", "packages", "import", "urllib3", "_LOGGER", ".", "warning", "(", "\"InsecureRequestWarning is disabled \"", "\"because of Vizio platform configuration\"", ")", "urllib3", ".", "disable_warnings", "(", "urllib3", ".", "exceptions", ".", "InsecureRequestWarning", ")", "add_entities", "(", "[", "device", "]", ",", "True", ")" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
VizioDevice.update
Retrieve latest state of the device.
custom_components/vizio/media_player.py
def update(self): """Retrieve latest state of the device.""" is_on = self._device.get_power_state() if is_on: self._state = STATE_ON volume = self._device.get_current_volume() if volume is not None: self._volume_level = float(volume) / self._max_volume input_ = self._device.get_current_input() if input_ is not None: self._current_input = input_.meta_name inputs = self._device.get_inputs() if inputs is not None: self._available_inputs = [input_.name for input_ in inputs] else: if is_on is None: self._state = None else: self._state = STATE_OFF self._volume_level = None self._current_input = None self._available_inputs = None
def update(self): """Retrieve latest state of the device.""" is_on = self._device.get_power_state() if is_on: self._state = STATE_ON volume = self._device.get_current_volume() if volume is not None: self._volume_level = float(volume) / self._max_volume input_ = self._device.get_current_input() if input_ is not None: self._current_input = input_.meta_name inputs = self._device.get_inputs() if inputs is not None: self._available_inputs = [input_.name for input_ in inputs] else: if is_on is None: self._state = None else: self._state = STATE_OFF self._volume_level = None self._current_input = None self._available_inputs = None
[ "Retrieve", "latest", "state", "of", "the", "device", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L134-L161
[ "def", "update", "(", "self", ")", ":", "is_on", "=", "self", ".", "_device", ".", "get_power_state", "(", ")", "if", "is_on", ":", "self", ".", "_state", "=", "STATE_ON", "volume", "=", "self", ".", "_device", ".", "get_current_volume", "(", ")", "if", "volume", "is", "not", "None", ":", "self", ".", "_volume_level", "=", "float", "(", "volume", ")", "/", "self", ".", "_max_volume", "input_", "=", "self", ".", "_device", ".", "get_current_input", "(", ")", "if", "input_", "is", "not", "None", ":", "self", ".", "_current_input", "=", "input_", ".", "meta_name", "inputs", "=", "self", ".", "_device", ".", "get_inputs", "(", ")", "if", "inputs", "is", "not", "None", ":", "self", ".", "_available_inputs", "=", "[", "input_", ".", "name", "for", "input_", "in", "inputs", "]", "else", ":", "if", "is_on", "is", "None", ":", "self", ".", "_state", "=", "None", "else", ":", "self", ".", "_state", "=", "STATE_OFF", "self", ".", "_volume_level", "=", "None", "self", ".", "_current_input", "=", "None", "self", ".", "_available_inputs", "=", "None" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
VizioDevice.mute_volume
Mute the volume.
custom_components/vizio/media_player.py
def mute_volume(self, mute): """Mute the volume.""" if mute: self._device.mute_on() else: self._device.mute_off()
def mute_volume(self, mute): """Mute the volume.""" if mute: self._device.mute_on() else: self._device.mute_off()
[ "Mute", "the", "volume", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L201-L206
[ "def", "mute_volume", "(", "self", ",", "mute", ")", ":", "if", "mute", ":", "self", ".", "_device", ".", "mute_on", "(", ")", "else", ":", "self", ".", "_device", ".", "mute_off", "(", ")" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
VizioDevice.volume_up
Increasing volume of the device.
custom_components/vizio/media_player.py
def volume_up(self): """Increasing volume of the device.""" self._volume_level += self._volume_step / self._max_volume self._device.vol_up(num=self._volume_step)
def volume_up(self): """Increasing volume of the device.""" self._volume_level += self._volume_step / self._max_volume self._device.vol_up(num=self._volume_step)
[ "Increasing", "volume", "of", "the", "device", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L228-L231
[ "def", "volume_up", "(", "self", ")", ":", "self", ".", "_volume_level", "+=", "self", ".", "_volume_step", "/", "self", ".", "_max_volume", "self", ".", "_device", ".", "vol_up", "(", "num", "=", "self", ".", "_volume_step", ")" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
VizioDevice.volume_down
Decreasing volume of the device.
custom_components/vizio/media_player.py
def volume_down(self): """Decreasing volume of the device.""" self._volume_level -= self._volume_step / self._max_volume self._device.vol_down(num=self._volume_step)
def volume_down(self): """Decreasing volume of the device.""" self._volume_level -= self._volume_step / self._max_volume self._device.vol_down(num=self._volume_step)
[ "Decreasing", "volume", "of", "the", "device", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L233-L236
[ "def", "volume_down", "(", "self", ")", ":", "self", ".", "_volume_level", "-=", "self", ".", "_volume_step", "/", "self", ".", "_max_volume", "self", ".", "_device", ".", "vol_down", "(", "num", "=", "self", ".", "_volume_step", ")" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
VizioDevice.set_volume_level
Set volume level.
custom_components/vizio/media_player.py
def set_volume_level(self, volume): """Set volume level.""" if self._volume_level is not None: if volume > self._volume_level: num = int(self._max_volume * (volume - self._volume_level)) self._volume_level = volume self._device.vol_up(num=num) elif volume < self._volume_level: num = int(self._max_volume * (self._volume_level - volume)) self._volume_level = volume self._device.vol_down(num=num)
def set_volume_level(self, volume): """Set volume level.""" if self._volume_level is not None: if volume > self._volume_level: num = int(self._max_volume * (volume - self._volume_level)) self._volume_level = volume self._device.vol_up(num=num) elif volume < self._volume_level: num = int(self._max_volume * (self._volume_level - volume)) self._volume_level = volume self._device.vol_down(num=num)
[ "Set", "volume", "level", "." ]
vkorn/pyvizio
python
https://github.com/vkorn/pyvizio/blob/7153c9ad544195c867c14f8f03c97dba416c0a7a/custom_components/vizio/media_player.py#L242-L252
[ "def", "set_volume_level", "(", "self", ",", "volume", ")", ":", "if", "self", ".", "_volume_level", "is", "not", "None", ":", "if", "volume", ">", "self", ".", "_volume_level", ":", "num", "=", "int", "(", "self", ".", "_max_volume", "*", "(", "volume", "-", "self", ".", "_volume_level", ")", ")", "self", ".", "_volume_level", "=", "volume", "self", ".", "_device", ".", "vol_up", "(", "num", "=", "num", ")", "elif", "volume", "<", "self", ".", "_volume_level", ":", "num", "=", "int", "(", "self", ".", "_max_volume", "*", "(", "self", ".", "_volume_level", "-", "volume", ")", ")", "self", ".", "_volume_level", "=", "volume", "self", ".", "_device", ".", "vol_down", "(", "num", "=", "num", ")" ]
7153c9ad544195c867c14f8f03c97dba416c0a7a
test
Board.reset
Restores the starting position.
shogi/__init__.py
def reset(self): '''Restores the starting position.''' self.piece_bb = [ BB_VOID, # NONE BB_RANK_C | BB_RANK_G, # PAWN BB_A1 | BB_I1 | BB_A9 | BB_I9, # LANCE BB_A2 | BB_A8 | BB_I2 | BB_I8, # KNIGHT BB_A3 | BB_A7 | BB_I3 | BB_I7, # SILVER BB_A4 | BB_A6 | BB_I4 | BB_I6, # GOLD BB_B2 | BB_H8, # BISHOP BB_B8 | BB_H2, # ROOK BB_A5 | BB_I5, # KING BB_VOID, # PROM_PAWN BB_VOID, # PROM_LANCE BB_VOID, # PROM_KNIGHT BB_VOID, # PROM_SILVER BB_VOID, # PROM_BISHOP BB_VOID, # PROM_ROOK ] self.pieces_in_hand = [collections.Counter(), collections.Counter()] self.occupied = Occupied(BB_RANK_G | BB_H2 | BB_H8 | BB_RANK_I, BB_RANK_A | BB_B2 | BB_B8 | BB_RANK_C) self.king_squares = [I5, A5] self.pieces = [NONE for i in SQUARES] for i in SQUARES: mask = BB_SQUARES[i] for piece_type in PIECE_TYPES: if mask & self.piece_bb[piece_type]: self.pieces[i] = piece_type self.turn = BLACK self.move_number = 1 self.captured_piece_stack = collections.deque() self.move_stack = collections.deque() self.incremental_zobrist_hash = self.board_zobrist_hash(DEFAULT_RANDOM_ARRAY) self.transpositions = collections.Counter((self.zobrist_hash(), ))
def reset(self): '''Restores the starting position.''' self.piece_bb = [ BB_VOID, # NONE BB_RANK_C | BB_RANK_G, # PAWN BB_A1 | BB_I1 | BB_A9 | BB_I9, # LANCE BB_A2 | BB_A8 | BB_I2 | BB_I8, # KNIGHT BB_A3 | BB_A7 | BB_I3 | BB_I7, # SILVER BB_A4 | BB_A6 | BB_I4 | BB_I6, # GOLD BB_B2 | BB_H8, # BISHOP BB_B8 | BB_H2, # ROOK BB_A5 | BB_I5, # KING BB_VOID, # PROM_PAWN BB_VOID, # PROM_LANCE BB_VOID, # PROM_KNIGHT BB_VOID, # PROM_SILVER BB_VOID, # PROM_BISHOP BB_VOID, # PROM_ROOK ] self.pieces_in_hand = [collections.Counter(), collections.Counter()] self.occupied = Occupied(BB_RANK_G | BB_H2 | BB_H8 | BB_RANK_I, BB_RANK_A | BB_B2 | BB_B8 | BB_RANK_C) self.king_squares = [I5, A5] self.pieces = [NONE for i in SQUARES] for i in SQUARES: mask = BB_SQUARES[i] for piece_type in PIECE_TYPES: if mask & self.piece_bb[piece_type]: self.pieces[i] = piece_type self.turn = BLACK self.move_number = 1 self.captured_piece_stack = collections.deque() self.move_stack = collections.deque() self.incremental_zobrist_hash = self.board_zobrist_hash(DEFAULT_RANDOM_ARRAY) self.transpositions = collections.Counter((self.zobrist_hash(), ))
[ "Restores", "the", "starting", "position", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L526-L564
[ "def", "reset", "(", "self", ")", ":", "self", ".", "piece_bb", "=", "[", "BB_VOID", ",", "# NONE", "BB_RANK_C", "|", "BB_RANK_G", ",", "# PAWN", "BB_A1", "|", "BB_I1", "|", "BB_A9", "|", "BB_I9", ",", "# LANCE", "BB_A2", "|", "BB_A8", "|", "BB_I2", "|", "BB_I8", ",", "# KNIGHT", "BB_A3", "|", "BB_A7", "|", "BB_I3", "|", "BB_I7", ",", "# SILVER", "BB_A4", "|", "BB_A6", "|", "BB_I4", "|", "BB_I6", ",", "# GOLD", "BB_B2", "|", "BB_H8", ",", "# BISHOP", "BB_B8", "|", "BB_H2", ",", "# ROOK", "BB_A5", "|", "BB_I5", ",", "# KING", "BB_VOID", ",", "# PROM_PAWN", "BB_VOID", ",", "# PROM_LANCE", "BB_VOID", ",", "# PROM_KNIGHT", "BB_VOID", ",", "# PROM_SILVER", "BB_VOID", ",", "# PROM_BISHOP", "BB_VOID", ",", "# PROM_ROOK", "]", "self", ".", "pieces_in_hand", "=", "[", "collections", ".", "Counter", "(", ")", ",", "collections", ".", "Counter", "(", ")", "]", "self", ".", "occupied", "=", "Occupied", "(", "BB_RANK_G", "|", "BB_H2", "|", "BB_H8", "|", "BB_RANK_I", ",", "BB_RANK_A", "|", "BB_B2", "|", "BB_B8", "|", "BB_RANK_C", ")", "self", ".", "king_squares", "=", "[", "I5", ",", "A5", "]", "self", ".", "pieces", "=", "[", "NONE", "for", "i", "in", "SQUARES", "]", "for", "i", "in", "SQUARES", ":", "mask", "=", "BB_SQUARES", "[", "i", "]", "for", "piece_type", "in", "PIECE_TYPES", ":", "if", "mask", "&", "self", ".", "piece_bb", "[", "piece_type", "]", ":", "self", ".", "pieces", "[", "i", "]", "=", "piece_type", "self", ".", "turn", "=", "BLACK", "self", ".", "move_number", "=", "1", "self", ".", "captured_piece_stack", "=", "collections", ".", "deque", "(", ")", "self", ".", "move_stack", "=", "collections", ".", "deque", "(", ")", "self", ".", "incremental_zobrist_hash", "=", "self", ".", "board_zobrist_hash", "(", "DEFAULT_RANDOM_ARRAY", ")", "self", ".", "transpositions", "=", "collections", ".", "Counter", "(", "(", "self", ".", "zobrist_hash", "(", ")", ",", ")", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.piece_at
Gets the piece at the given square.
shogi/__init__.py
def piece_at(self, square): '''Gets the piece at the given square.''' mask = BB_SQUARES[square] color = int(bool(self.occupied[WHITE] & mask)) piece_type = self.piece_type_at(square) if piece_type: return Piece(piece_type, color)
def piece_at(self, square): '''Gets the piece at the given square.''' mask = BB_SQUARES[square] color = int(bool(self.occupied[WHITE] & mask)) piece_type = self.piece_type_at(square) if piece_type: return Piece(piece_type, color)
[ "Gets", "the", "piece", "at", "the", "given", "square", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L599-L606
[ "def", "piece_at", "(", "self", ",", "square", ")", ":", "mask", "=", "BB_SQUARES", "[", "square", "]", "color", "=", "int", "(", "bool", "(", "self", ".", "occupied", "[", "WHITE", "]", "&", "mask", ")", ")", "piece_type", "=", "self", ".", "piece_type_at", "(", "square", ")", "if", "piece_type", ":", "return", "Piece", "(", "piece_type", ",", "color", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.remove_piece_at
Removes a piece from the given square if present.
shogi/__init__.py
def remove_piece_at(self, square, into_hand=False): '''Removes a piece from the given square if present.''' piece_type = self.piece_type_at(square) if piece_type == NONE: return if into_hand: self.add_piece_into_hand(piece_type, self.turn) mask = BB_SQUARES[square] self.piece_bb[piece_type] ^= mask color = int(bool(self.occupied[WHITE] & mask)) self.pieces[square] = NONE self.occupied.ixor(mask, color, square) # Update incremental zobrist hash. if color == BLACK: piece_index = (piece_type - 1) * 2 else: piece_index = (piece_type - 1) * 2 + 1 self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]
def remove_piece_at(self, square, into_hand=False): '''Removes a piece from the given square if present.''' piece_type = self.piece_type_at(square) if piece_type == NONE: return if into_hand: self.add_piece_into_hand(piece_type, self.turn) mask = BB_SQUARES[square] self.piece_bb[piece_type] ^= mask color = int(bool(self.occupied[WHITE] & mask)) self.pieces[square] = NONE self.occupied.ixor(mask, color, square) # Update incremental zobrist hash. if color == BLACK: piece_index = (piece_type - 1) * 2 else: piece_index = (piece_type - 1) * 2 + 1 self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]
[ "Removes", "a", "piece", "from", "the", "given", "square", "if", "present", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L633-L657
[ "def", "remove_piece_at", "(", "self", ",", "square", ",", "into_hand", "=", "False", ")", ":", "piece_type", "=", "self", ".", "piece_type_at", "(", "square", ")", "if", "piece_type", "==", "NONE", ":", "return", "if", "into_hand", ":", "self", ".", "add_piece_into_hand", "(", "piece_type", ",", "self", ".", "turn", ")", "mask", "=", "BB_SQUARES", "[", "square", "]", "self", ".", "piece_bb", "[", "piece_type", "]", "^=", "mask", "color", "=", "int", "(", "bool", "(", "self", ".", "occupied", "[", "WHITE", "]", "&", "mask", ")", ")", "self", ".", "pieces", "[", "square", "]", "=", "NONE", "self", ".", "occupied", ".", "ixor", "(", "mask", ",", "color", ",", "square", ")", "# Update incremental zobrist hash.", "if", "color", "==", "BLACK", ":", "piece_index", "=", "(", "piece_type", "-", "1", ")", "*", "2", "else", ":", "piece_index", "=", "(", "piece_type", "-", "1", ")", "*", "2", "+", "1", "self", ".", "incremental_zobrist_hash", "^=", "DEFAULT_RANDOM_ARRAY", "[", "81", "*", "piece_index", "+", "9", "*", "rank_index", "(", "square", ")", "+", "file_index", "(", "square", ")", "]" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.set_piece_at
Sets a piece at the given square. An existing piece is replaced.
shogi/__init__.py
def set_piece_at(self, square, piece, from_hand=False, into_hand=False): '''Sets a piece at the given square. An existing piece is replaced.''' if from_hand: self.remove_piece_from_hand(piece.piece_type, self.turn) self.remove_piece_at(square, into_hand) self.pieces[square] = piece.piece_type mask = BB_SQUARES[square] piece_type = piece.piece_type self.piece_bb[piece_type] |= mask if piece_type == KING: self.king_squares[piece.color] = square self.occupied.ixor(mask, piece.color, square) # Update incremental zorbist hash. if piece.color == BLACK: piece_index = (piece.piece_type - 1) * 2 else: piece_index = (piece.piece_type - 1) * 2 + 1 self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]
def set_piece_at(self, square, piece, from_hand=False, into_hand=False): '''Sets a piece at the given square. An existing piece is replaced.''' if from_hand: self.remove_piece_from_hand(piece.piece_type, self.turn) self.remove_piece_at(square, into_hand) self.pieces[square] = piece.piece_type mask = BB_SQUARES[square] piece_type = piece.piece_type self.piece_bb[piece_type] |= mask if piece_type == KING: self.king_squares[piece.color] = square self.occupied.ixor(mask, piece.color, square) # Update incremental zorbist hash. if piece.color == BLACK: piece_index = (piece.piece_type - 1) * 2 else: piece_index = (piece.piece_type - 1) * 2 + 1 self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]
[ "Sets", "a", "piece", "at", "the", "given", "square", ".", "An", "existing", "piece", "is", "replaced", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L659-L684
[ "def", "set_piece_at", "(", "self", ",", "square", ",", "piece", ",", "from_hand", "=", "False", ",", "into_hand", "=", "False", ")", ":", "if", "from_hand", ":", "self", ".", "remove_piece_from_hand", "(", "piece", ".", "piece_type", ",", "self", ".", "turn", ")", "self", ".", "remove_piece_at", "(", "square", ",", "into_hand", ")", "self", ".", "pieces", "[", "square", "]", "=", "piece", ".", "piece_type", "mask", "=", "BB_SQUARES", "[", "square", "]", "piece_type", "=", "piece", ".", "piece_type", "self", ".", "piece_bb", "[", "piece_type", "]", "|=", "mask", "if", "piece_type", "==", "KING", ":", "self", ".", "king_squares", "[", "piece", ".", "color", "]", "=", "square", "self", ".", "occupied", ".", "ixor", "(", "mask", ",", "piece", ".", "color", ",", "square", ")", "# Update incremental zorbist hash.", "if", "piece", ".", "color", "==", "BLACK", ":", "piece_index", "=", "(", "piece", ".", "piece_type", "-", "1", ")", "*", "2", "else", ":", "piece_index", "=", "(", "piece", ".", "piece_type", "-", "1", ")", "*", "2", "+", "1", "self", ".", "incremental_zobrist_hash", "^=", "DEFAULT_RANDOM_ARRAY", "[", "81", "*", "piece_index", "+", "9", "*", "rank_index", "(", "square", ")", "+", "file_index", "(", "square", ")", "]" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.is_suicide_or_check_by_dropping_pawn
Checks if the given move would move would leave the king in check or put it into check.
shogi/__init__.py
def is_suicide_or_check_by_dropping_pawn(self, move): ''' Checks if the given move would move would leave the king in check or put it into check. ''' self.push(move) is_suicide = self.was_suicide() is_check_by_dropping_pawn = self.was_check_by_dropping_pawn(move) self.pop() return is_suicide or is_check_by_dropping_pawn
def is_suicide_or_check_by_dropping_pawn(self, move): ''' Checks if the given move would move would leave the king in check or put it into check. ''' self.push(move) is_suicide = self.was_suicide() is_check_by_dropping_pawn = self.was_check_by_dropping_pawn(move) self.pop() return is_suicide or is_check_by_dropping_pawn
[ "Checks", "if", "the", "given", "move", "would", "move", "would", "leave", "the", "king", "in", "check", "or", "put", "it", "into", "check", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L789-L799
[ "def", "is_suicide_or_check_by_dropping_pawn", "(", "self", ",", "move", ")", ":", "self", ".", "push", "(", "move", ")", "is_suicide", "=", "self", ".", "was_suicide", "(", ")", "is_check_by_dropping_pawn", "=", "self", ".", "was_check_by_dropping_pawn", "(", "move", ")", "self", ".", "pop", "(", ")", "return", "is_suicide", "or", "is_check_by_dropping_pawn" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.was_suicide
Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move.
shogi/__init__.py
def was_suicide(self): ''' Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move. ''' return self.is_attacked_by(self.turn, self.king_squares[self.turn ^ 1])
def was_suicide(self): ''' Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move. ''' return self.is_attacked_by(self.turn, self.king_squares[self.turn ^ 1])
[ "Checks", "if", "the", "king", "of", "the", "other", "side", "is", "attacked", ".", "Such", "a", "position", "is", "not", "valid", "and", "could", "only", "be", "reached", "by", "an", "illegal", "move", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L801-L806
[ "def", "was_suicide", "(", "self", ")", ":", "return", "self", ".", "is_attacked_by", "(", "self", ".", "turn", ",", "self", ".", "king_squares", "[", "self", ".", "turn", "^", "1", "]", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.is_game_over
Checks if the game is over due to checkmate, stalemate or fourfold repetition.
shogi/__init__.py
def is_game_over(self): ''' Checks if the game is over due to checkmate, stalemate or fourfold repetition. ''' # Stalemate or checkmate. try: next(self.generate_legal_moves().__iter__()) except StopIteration: return True # Fourfold repetition. if self.is_fourfold_repetition(): return True return False
def is_game_over(self): ''' Checks if the game is over due to checkmate, stalemate or fourfold repetition. ''' # Stalemate or checkmate. try: next(self.generate_legal_moves().__iter__()) except StopIteration: return True # Fourfold repetition. if self.is_fourfold_repetition(): return True return False
[ "Checks", "if", "the", "game", "is", "over", "due", "to", "checkmate", "stalemate", "or", "fourfold", "repetition", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L915-L931
[ "def", "is_game_over", "(", "self", ")", ":", "# Stalemate or checkmate.", "try", ":", "next", "(", "self", ".", "generate_legal_moves", "(", ")", ".", "__iter__", "(", ")", ")", "except", "StopIteration", ":", "return", "True", "# Fourfold repetition.", "if", "self", ".", "is_fourfold_repetition", "(", ")", ":", "return", "True", "return", "False" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.is_checkmate
Checks if the current position is a checkmate.
shogi/__init__.py
def is_checkmate(self): '''Checks if the current position is a checkmate.''' if not self.is_check(): return False try: next(self.generate_legal_moves().__iter__()) return False except StopIteration: return True
def is_checkmate(self): '''Checks if the current position is a checkmate.''' if not self.is_check(): return False try: next(self.generate_legal_moves().__iter__()) return False except StopIteration: return True
[ "Checks", "if", "the", "current", "position", "is", "a", "checkmate", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L933-L942
[ "def", "is_checkmate", "(", "self", ")", ":", "if", "not", "self", ".", "is_check", "(", ")", ":", "return", "False", "try", ":", "next", "(", "self", ".", "generate_legal_moves", "(", ")", ".", "__iter__", "(", ")", ")", "return", "False", "except", "StopIteration", ":", "return", "True" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.is_fourfold_repetition
a game is ended if a position occurs for the fourth time on consecutive alternating moves.
shogi/__init__.py
def is_fourfold_repetition(self): ''' a game is ended if a position occurs for the fourth time on consecutive alternating moves. ''' zobrist_hash = self.zobrist_hash() # A minimum amount of moves must have been played and the position # in question must have appeared at least four times. if self.transpositions[zobrist_hash] < 4: return False return True
def is_fourfold_repetition(self): ''' a game is ended if a position occurs for the fourth time on consecutive alternating moves. ''' zobrist_hash = self.zobrist_hash() # A minimum amount of moves must have been played and the position # in question must have appeared at least four times. if self.transpositions[zobrist_hash] < 4: return False return True
[ "a", "game", "is", "ended", "if", "a", "position", "occurs", "for", "the", "fourth", "time", "on", "consecutive", "alternating", "moves", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L955-L967
[ "def", "is_fourfold_repetition", "(", "self", ")", ":", "zobrist_hash", "=", "self", ".", "zobrist_hash", "(", ")", "# A minimum amount of moves must have been played and the position", "# in question must have appeared at least four times.", "if", "self", ".", "transpositions", "[", "zobrist_hash", "]", "<", "4", ":", "return", "False", "return", "True" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.push
Updates the position with the given move and puts it onto a stack. Null moves just increment the move counters, switch turns and forfeit en passant capturing. No validation is performed. For performance moves are assumed to be at least pseudo legal. Otherwise there is no guarantee that the previous board state can be restored. To check it yourself you can use: >>> move in board.pseudo_legal_moves True
shogi/__init__.py
def push(self, move): ''' Updates the position with the given move and puts it onto a stack. Null moves just increment the move counters, switch turns and forfeit en passant capturing. No validation is performed. For performance moves are assumed to be at least pseudo legal. Otherwise there is no guarantee that the previous board state can be restored. To check it yourself you can use: >>> move in board.pseudo_legal_moves True ''' # Increment move number. self.move_number += 1 # Remember game state. captured_piece = self.piece_type_at(move.to_square) if move else NONE self.captured_piece_stack.append(captured_piece) self.move_stack.append(move) # On a null move simply swap turns. if not move: self.turn ^= 1 return if move.drop_piece_type: # Drops. piece_type = move.drop_piece_type from_hand = True else: # Promotion. piece_type = self.piece_type_at(move.from_square) from_hand = False if move.promotion: piece_type = PIECE_PROMOTED[piece_type] # Remove piece from target square. self.remove_piece_at(move.from_square, False) # Put piece on target square. self.set_piece_at(move.to_square, Piece(piece_type, self.turn), from_hand, True) # Swap turn. self.turn ^= 1 # Update transposition table. self.transpositions.update((self.zobrist_hash(), ))
def push(self, move): ''' Updates the position with the given move and puts it onto a stack. Null moves just increment the move counters, switch turns and forfeit en passant capturing. No validation is performed. For performance moves are assumed to be at least pseudo legal. Otherwise there is no guarantee that the previous board state can be restored. To check it yourself you can use: >>> move in board.pseudo_legal_moves True ''' # Increment move number. self.move_number += 1 # Remember game state. captured_piece = self.piece_type_at(move.to_square) if move else NONE self.captured_piece_stack.append(captured_piece) self.move_stack.append(move) # On a null move simply swap turns. if not move: self.turn ^= 1 return if move.drop_piece_type: # Drops. piece_type = move.drop_piece_type from_hand = True else: # Promotion. piece_type = self.piece_type_at(move.from_square) from_hand = False if move.promotion: piece_type = PIECE_PROMOTED[piece_type] # Remove piece from target square. self.remove_piece_at(move.from_square, False) # Put piece on target square. self.set_piece_at(move.to_square, Piece(piece_type, self.turn), from_hand, True) # Swap turn. self.turn ^= 1 # Update transposition table. self.transpositions.update((self.zobrist_hash(), ))
[ "Updates", "the", "position", "with", "the", "given", "move", "and", "puts", "it", "onto", "a", "stack", ".", "Null", "moves", "just", "increment", "the", "move", "counters", "switch", "turns", "and", "forfeit", "en", "passant", "capturing", ".", "No", "validation", "is", "performed", ".", "For", "performance", "moves", "are", "assumed", "to", "be", "at", "least", "pseudo", "legal", ".", "Otherwise", "there", "is", "no", "guarantee", "that", "the", "previous", "board", "state", "can", "be", "restored", ".", "To", "check", "it", "yourself", "you", "can", "use", ":", ">>>", "move", "in", "board", ".", "pseudo_legal_moves", "True" ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L974-L1020
[ "def", "push", "(", "self", ",", "move", ")", ":", "# Increment move number.", "self", ".", "move_number", "+=", "1", "# Remember game state.", "captured_piece", "=", "self", ".", "piece_type_at", "(", "move", ".", "to_square", ")", "if", "move", "else", "NONE", "self", ".", "captured_piece_stack", ".", "append", "(", "captured_piece", ")", "self", ".", "move_stack", ".", "append", "(", "move", ")", "# On a null move simply swap turns.", "if", "not", "move", ":", "self", ".", "turn", "^=", "1", "return", "if", "move", ".", "drop_piece_type", ":", "# Drops.", "piece_type", "=", "move", ".", "drop_piece_type", "from_hand", "=", "True", "else", ":", "# Promotion.", "piece_type", "=", "self", ".", "piece_type_at", "(", "move", ".", "from_square", ")", "from_hand", "=", "False", "if", "move", ".", "promotion", ":", "piece_type", "=", "PIECE_PROMOTED", "[", "piece_type", "]", "# Remove piece from target square.", "self", ".", "remove_piece_at", "(", "move", ".", "from_square", ",", "False", ")", "# Put piece on target square.", "self", ".", "set_piece_at", "(", "move", ".", "to_square", ",", "Piece", "(", "piece_type", ",", "self", ".", "turn", ")", ",", "from_hand", ",", "True", ")", "# Swap turn.", "self", ".", "turn", "^=", "1", "# Update transposition table.", "self", ".", "transpositions", ".", "update", "(", "(", "self", ".", "zobrist_hash", "(", ")", ",", ")", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.pop
Restores the previous position and returns the last move from the stack.
shogi/__init__.py
def pop(self): ''' Restores the previous position and returns the last move from the stack. ''' move = self.move_stack.pop() # Update transposition table. self.transpositions.subtract((self.zobrist_hash(), )) # Decrement move number. self.move_number -= 1 # Restore state. captured_piece_type = self.captured_piece_stack.pop() captured_piece_color = self.turn # On a null move simply swap the turn. if not move: self.turn ^= 1 return move # Restore the source square. piece_type = self.piece_type_at(move.to_square) if move.promotion: piece_type = PIECE_PROMOTED.index(piece_type) if move.from_square is None: self.add_piece_into_hand(piece_type, self.turn ^ 1) else: self.set_piece_at(move.from_square, Piece(piece_type, self.turn ^ 1)) # Restore target square. if captured_piece_type: self.remove_piece_from_hand(captured_piece_type, captured_piece_color ^ 1) self.set_piece_at(move.to_square, Piece(captured_piece_type, captured_piece_color)) else: self.remove_piece_at(move.to_square) # Swap turn. self.turn ^= 1 return move
def pop(self): ''' Restores the previous position and returns the last move from the stack. ''' move = self.move_stack.pop() # Update transposition table. self.transpositions.subtract((self.zobrist_hash(), )) # Decrement move number. self.move_number -= 1 # Restore state. captured_piece_type = self.captured_piece_stack.pop() captured_piece_color = self.turn # On a null move simply swap the turn. if not move: self.turn ^= 1 return move # Restore the source square. piece_type = self.piece_type_at(move.to_square) if move.promotion: piece_type = PIECE_PROMOTED.index(piece_type) if move.from_square is None: self.add_piece_into_hand(piece_type, self.turn ^ 1) else: self.set_piece_at(move.from_square, Piece(piece_type, self.turn ^ 1)) # Restore target square. if captured_piece_type: self.remove_piece_from_hand(captured_piece_type, captured_piece_color ^ 1) self.set_piece_at(move.to_square, Piece(captured_piece_type, captured_piece_color)) else: self.remove_piece_at(move.to_square) # Swap turn. self.turn ^= 1 return move
[ "Restores", "the", "previous", "position", "and", "returns", "the", "last", "move", "from", "the", "stack", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L1022-L1063
[ "def", "pop", "(", "self", ")", ":", "move", "=", "self", ".", "move_stack", ".", "pop", "(", ")", "# Update transposition table.", "self", ".", "transpositions", ".", "subtract", "(", "(", "self", ".", "zobrist_hash", "(", ")", ",", ")", ")", "# Decrement move number.", "self", ".", "move_number", "-=", "1", "# Restore state.", "captured_piece_type", "=", "self", ".", "captured_piece_stack", ".", "pop", "(", ")", "captured_piece_color", "=", "self", ".", "turn", "# On a null move simply swap the turn.", "if", "not", "move", ":", "self", ".", "turn", "^=", "1", "return", "move", "# Restore the source square.", "piece_type", "=", "self", ".", "piece_type_at", "(", "move", ".", "to_square", ")", "if", "move", ".", "promotion", ":", "piece_type", "=", "PIECE_PROMOTED", ".", "index", "(", "piece_type", ")", "if", "move", ".", "from_square", "is", "None", ":", "self", ".", "add_piece_into_hand", "(", "piece_type", ",", "self", ".", "turn", "^", "1", ")", "else", ":", "self", ".", "set_piece_at", "(", "move", ".", "from_square", ",", "Piece", "(", "piece_type", ",", "self", ".", "turn", "^", "1", ")", ")", "# Restore target square.", "if", "captured_piece_type", ":", "self", ".", "remove_piece_from_hand", "(", "captured_piece_type", ",", "captured_piece_color", "^", "1", ")", "self", ".", "set_piece_at", "(", "move", ".", "to_square", ",", "Piece", "(", "captured_piece_type", ",", "captured_piece_color", ")", ")", "else", ":", "self", ".", "remove_piece_at", "(", "move", ".", "to_square", ")", "# Swap turn.", "self", ".", "turn", "^=", "1", "return", "move" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.sfen
Gets an SFEN representation of the current position.
shogi/__init__.py
def sfen(self): ''' Gets an SFEN representation of the current position. ''' sfen = [] empty = 0 # Position part. for square in SQUARES: piece = self.piece_at(square) if not piece: empty += 1 else: if empty: sfen.append(str(empty)) empty = 0 sfen.append(piece.symbol()) if BB_SQUARES[square] & BB_FILE_1: if empty: sfen.append(str(empty)) empty = 0 if square != I1: sfen.append('/') sfen.append(' ') # Side to move. if self.turn == WHITE: sfen.append('w') else: sfen.append('b') sfen.append(' ') # Pieces in hand pih_len = 0 for color in COLORS: p = self.pieces_in_hand[color] pih_len += len(p) for piece_type in sorted(p.keys(), reverse=True): if p[piece_type] >= 1: if p[piece_type] > 1: sfen.append(str(p[piece_type])) piece = Piece(piece_type, color) sfen.append(piece.symbol()) if pih_len == 0: sfen.append('-') sfen.append(' ') # Move count sfen.append(str(self.move_number)) return ''.join(sfen)
def sfen(self): ''' Gets an SFEN representation of the current position. ''' sfen = [] empty = 0 # Position part. for square in SQUARES: piece = self.piece_at(square) if not piece: empty += 1 else: if empty: sfen.append(str(empty)) empty = 0 sfen.append(piece.symbol()) if BB_SQUARES[square] & BB_FILE_1: if empty: sfen.append(str(empty)) empty = 0 if square != I1: sfen.append('/') sfen.append(' ') # Side to move. if self.turn == WHITE: sfen.append('w') else: sfen.append('b') sfen.append(' ') # Pieces in hand pih_len = 0 for color in COLORS: p = self.pieces_in_hand[color] pih_len += len(p) for piece_type in sorted(p.keys(), reverse=True): if p[piece_type] >= 1: if p[piece_type] > 1: sfen.append(str(p[piece_type])) piece = Piece(piece_type, color) sfen.append(piece.symbol()) if pih_len == 0: sfen.append('-') sfen.append(' ') # Move count sfen.append(str(self.move_number)) return ''.join(sfen)
[ "Gets", "an", "SFEN", "representation", "of", "the", "current", "position", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L1069-L1125
[ "def", "sfen", "(", "self", ")", ":", "sfen", "=", "[", "]", "empty", "=", "0", "# Position part.", "for", "square", "in", "SQUARES", ":", "piece", "=", "self", ".", "piece_at", "(", "square", ")", "if", "not", "piece", ":", "empty", "+=", "1", "else", ":", "if", "empty", ":", "sfen", ".", "append", "(", "str", "(", "empty", ")", ")", "empty", "=", "0", "sfen", ".", "append", "(", "piece", ".", "symbol", "(", ")", ")", "if", "BB_SQUARES", "[", "square", "]", "&", "BB_FILE_1", ":", "if", "empty", ":", "sfen", ".", "append", "(", "str", "(", "empty", ")", ")", "empty", "=", "0", "if", "square", "!=", "I1", ":", "sfen", ".", "append", "(", "'/'", ")", "sfen", ".", "append", "(", "' '", ")", "# Side to move.", "if", "self", ".", "turn", "==", "WHITE", ":", "sfen", ".", "append", "(", "'w'", ")", "else", ":", "sfen", ".", "append", "(", "'b'", ")", "sfen", ".", "append", "(", "' '", ")", "# Pieces in hand", "pih_len", "=", "0", "for", "color", "in", "COLORS", ":", "p", "=", "self", ".", "pieces_in_hand", "[", "color", "]", "pih_len", "+=", "len", "(", "p", ")", "for", "piece_type", "in", "sorted", "(", "p", ".", "keys", "(", ")", ",", "reverse", "=", "True", ")", ":", "if", "p", "[", "piece_type", "]", ">=", "1", ":", "if", "p", "[", "piece_type", "]", ">", "1", ":", "sfen", ".", "append", "(", "str", "(", "p", "[", "piece_type", "]", ")", ")", "piece", "=", "Piece", "(", "piece_type", ",", "color", ")", "sfen", ".", "append", "(", "piece", ".", "symbol", "(", ")", ")", "if", "pih_len", "==", "0", ":", "sfen", ".", "append", "(", "'-'", ")", "sfen", ".", "append", "(", "' '", ")", "# Move count", "sfen", ".", "append", "(", "str", "(", "self", ".", "move_number", ")", ")", "return", "''", ".", "join", "(", "sfen", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.set_sfen
Parses a SFEN and sets the position from it. Rasies `ValueError` if the SFEN string is invalid.
shogi/__init__.py
def set_sfen(self, sfen): ''' Parses a SFEN and sets the position from it. Rasies `ValueError` if the SFEN string is invalid. ''' # Ensure there are six parts. parts = sfen.split() if len(parts) != 4: raise ValueError('sfen string should consist of 6 parts: {0}'.format(repr(sfen))) # Ensure the board part is valid. rows = parts[0].split('/') if len(rows) != 9: raise ValueError('expected 9 rows in position part of sfen: {0}'.format(repr(sfen))) # Validate each row. for row in rows: field_sum = 0 previous_was_digit = False previous_was_plus = False for c in row: if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: if previous_was_digit: raise ValueError('two subsequent digits in position part of sfen: {0}'.format(repr(sfen))) if previous_was_plus: raise ValueError('Cannot promote squares in position part of sfen: {0}'.format(repr(sfen))) field_sum += int(c) previous_was_digit = True previous_was_plus = False elif c == '+': if previous_was_plus: raise ValueError('Double promotion prefixes in position part of sfen: {0}'.format(repr(sfen))) previous_was_digit = False previous_was_plus = True elif c.lower() in ['p', 'l', 'n', 's', 'g', 'b', 'r', 'k']: field_sum += 1 if previous_was_plus and (c.lower() == 'g' or c.lower() == 'k'): raise ValueError('Gold and King cannot promote in position part of sfen: {0}') previous_was_digit = False previous_was_plus = False else: raise ValueError('invalid character in position part of sfen: {0}'.format(repr(sfen))) if field_sum != 9: raise ValueError('expected 9 columns per row in position part of sfen: {0}'.format(repr(sfen))) # Check that the turn part is valid. if not parts[1] in ['b', 'w']: raise ValueError("expected 'b' or 'w' for turn part of sfen: {0}".format(repr(sfen))) # Check pieces in hand is valid. # TODO: implement with checking parts[2] # Check that the fullmove number part is valid. # 0 is allowed for compability but later replaced with 1. if int(parts[3]) < 0: raise ValueError('fullmove number must be positive: {0}'.format(repr(sfen))) # Clear board. self.clear() # Put pieces on the board. square_index = 0 previous_was_plus = False for c in parts[0]: if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: square_index += int(c) elif c == '+': previous_was_plus = True elif c == '/': pass else: piece_symbol = c if previous_was_plus: piece_symbol = '+' + piece_symbol self.set_piece_at(square_index, Piece.from_symbol(piece_symbol)) square_index += 1 previous_was_plus = False # Set the turn. if parts[1] == 'w': self.turn = WHITE else: self.turn = BLACK # Set the pieces in hand self.pieces_in_hand = [collections.Counter(), collections.Counter()] if parts[2] != '-': piece_count = 0 for c in parts[2]: if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: piece_count *= 10 piece_count += int(c) else: piece = Piece.from_symbol(c) if piece_count == 0: piece_count = 1 self.add_piece_into_hand(piece.piece_type, piece.color, piece_count) piece_count = 0 # Set the mover counters. self.move_number = int(parts[3]) or 1 # Reset the transposition table. self.transpositions = collections.Counter((self.zobrist_hash(), ))
def set_sfen(self, sfen): ''' Parses a SFEN and sets the position from it. Rasies `ValueError` if the SFEN string is invalid. ''' # Ensure there are six parts. parts = sfen.split() if len(parts) != 4: raise ValueError('sfen string should consist of 6 parts: {0}'.format(repr(sfen))) # Ensure the board part is valid. rows = parts[0].split('/') if len(rows) != 9: raise ValueError('expected 9 rows in position part of sfen: {0}'.format(repr(sfen))) # Validate each row. for row in rows: field_sum = 0 previous_was_digit = False previous_was_plus = False for c in row: if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: if previous_was_digit: raise ValueError('two subsequent digits in position part of sfen: {0}'.format(repr(sfen))) if previous_was_plus: raise ValueError('Cannot promote squares in position part of sfen: {0}'.format(repr(sfen))) field_sum += int(c) previous_was_digit = True previous_was_plus = False elif c == '+': if previous_was_plus: raise ValueError('Double promotion prefixes in position part of sfen: {0}'.format(repr(sfen))) previous_was_digit = False previous_was_plus = True elif c.lower() in ['p', 'l', 'n', 's', 'g', 'b', 'r', 'k']: field_sum += 1 if previous_was_plus and (c.lower() == 'g' or c.lower() == 'k'): raise ValueError('Gold and King cannot promote in position part of sfen: {0}') previous_was_digit = False previous_was_plus = False else: raise ValueError('invalid character in position part of sfen: {0}'.format(repr(sfen))) if field_sum != 9: raise ValueError('expected 9 columns per row in position part of sfen: {0}'.format(repr(sfen))) # Check that the turn part is valid. if not parts[1] in ['b', 'w']: raise ValueError("expected 'b' or 'w' for turn part of sfen: {0}".format(repr(sfen))) # Check pieces in hand is valid. # TODO: implement with checking parts[2] # Check that the fullmove number part is valid. # 0 is allowed for compability but later replaced with 1. if int(parts[3]) < 0: raise ValueError('fullmove number must be positive: {0}'.format(repr(sfen))) # Clear board. self.clear() # Put pieces on the board. square_index = 0 previous_was_plus = False for c in parts[0]: if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: square_index += int(c) elif c == '+': previous_was_plus = True elif c == '/': pass else: piece_symbol = c if previous_was_plus: piece_symbol = '+' + piece_symbol self.set_piece_at(square_index, Piece.from_symbol(piece_symbol)) square_index += 1 previous_was_plus = False # Set the turn. if parts[1] == 'w': self.turn = WHITE else: self.turn = BLACK # Set the pieces in hand self.pieces_in_hand = [collections.Counter(), collections.Counter()] if parts[2] != '-': piece_count = 0 for c in parts[2]: if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: piece_count *= 10 piece_count += int(c) else: piece = Piece.from_symbol(c) if piece_count == 0: piece_count = 1 self.add_piece_into_hand(piece.piece_type, piece.color, piece_count) piece_count = 0 # Set the mover counters. self.move_number = int(parts[3]) or 1 # Reset the transposition table. self.transpositions = collections.Counter((self.zobrist_hash(), ))
[ "Parses", "a", "SFEN", "and", "sets", "the", "position", "from", "it", ".", "Rasies", "ValueError", "if", "the", "SFEN", "string", "is", "invalid", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L1127-L1232
[ "def", "set_sfen", "(", "self", ",", "sfen", ")", ":", "# Ensure there are six parts.", "parts", "=", "sfen", ".", "split", "(", ")", "if", "len", "(", "parts", ")", "!=", "4", ":", "raise", "ValueError", "(", "'sfen string should consist of 6 parts: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "# Ensure the board part is valid.", "rows", "=", "parts", "[", "0", "]", ".", "split", "(", "'/'", ")", "if", "len", "(", "rows", ")", "!=", "9", ":", "raise", "ValueError", "(", "'expected 9 rows in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "# Validate each row.", "for", "row", "in", "rows", ":", "field_sum", "=", "0", "previous_was_digit", "=", "False", "previous_was_plus", "=", "False", "for", "c", "in", "row", ":", "if", "c", "in", "[", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ",", "'8'", ",", "'9'", "]", ":", "if", "previous_was_digit", ":", "raise", "ValueError", "(", "'two subsequent digits in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "if", "previous_was_plus", ":", "raise", "ValueError", "(", "'Cannot promote squares in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "field_sum", "+=", "int", "(", "c", ")", "previous_was_digit", "=", "True", "previous_was_plus", "=", "False", "elif", "c", "==", "'+'", ":", "if", "previous_was_plus", ":", "raise", "ValueError", "(", "'Double promotion prefixes in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "previous_was_digit", "=", "False", "previous_was_plus", "=", "True", "elif", "c", ".", "lower", "(", ")", "in", "[", "'p'", ",", "'l'", ",", "'n'", ",", "'s'", ",", "'g'", ",", "'b'", ",", "'r'", ",", "'k'", "]", ":", "field_sum", "+=", "1", "if", "previous_was_plus", "and", "(", "c", ".", "lower", "(", ")", "==", "'g'", "or", "c", ".", "lower", "(", ")", "==", "'k'", ")", ":", "raise", "ValueError", "(", "'Gold and King cannot promote in position part of sfen: {0}'", ")", "previous_was_digit", "=", "False", "previous_was_plus", "=", "False", "else", ":", "raise", "ValueError", "(", "'invalid character in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "if", "field_sum", "!=", "9", ":", "raise", "ValueError", "(", "'expected 9 columns per row in position part of sfen: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "# Check that the turn part is valid.", "if", "not", "parts", "[", "1", "]", "in", "[", "'b'", ",", "'w'", "]", ":", "raise", "ValueError", "(", "\"expected 'b' or 'w' for turn part of sfen: {0}\"", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "# Check pieces in hand is valid.", "# TODO: implement with checking parts[2]", "# Check that the fullmove number part is valid.", "# 0 is allowed for compability but later replaced with 1.", "if", "int", "(", "parts", "[", "3", "]", ")", "<", "0", ":", "raise", "ValueError", "(", "'fullmove number must be positive: {0}'", ".", "format", "(", "repr", "(", "sfen", ")", ")", ")", "# Clear board.", "self", ".", "clear", "(", ")", "# Put pieces on the board.", "square_index", "=", "0", "previous_was_plus", "=", "False", "for", "c", "in", "parts", "[", "0", "]", ":", "if", "c", "in", "[", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ",", "'8'", ",", "'9'", "]", ":", "square_index", "+=", "int", "(", "c", ")", "elif", "c", "==", "'+'", ":", "previous_was_plus", "=", "True", "elif", "c", "==", "'/'", ":", "pass", "else", ":", "piece_symbol", "=", "c", "if", "previous_was_plus", ":", "piece_symbol", "=", "'+'", "+", "piece_symbol", "self", ".", "set_piece_at", "(", "square_index", ",", "Piece", ".", "from_symbol", "(", "piece_symbol", ")", ")", "square_index", "+=", "1", "previous_was_plus", "=", "False", "# Set the turn.", "if", "parts", "[", "1", "]", "==", "'w'", ":", "self", ".", "turn", "=", "WHITE", "else", ":", "self", ".", "turn", "=", "BLACK", "# Set the pieces in hand", "self", ".", "pieces_in_hand", "=", "[", "collections", ".", "Counter", "(", ")", ",", "collections", ".", "Counter", "(", ")", "]", "if", "parts", "[", "2", "]", "!=", "'-'", ":", "piece_count", "=", "0", "for", "c", "in", "parts", "[", "2", "]", ":", "if", "c", "in", "[", "'0'", ",", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ",", "'8'", ",", "'9'", "]", ":", "piece_count", "*=", "10", "piece_count", "+=", "int", "(", "c", ")", "else", ":", "piece", "=", "Piece", ".", "from_symbol", "(", "c", ")", "if", "piece_count", "==", "0", ":", "piece_count", "=", "1", "self", ".", "add_piece_into_hand", "(", "piece", ".", "piece_type", ",", "piece", ".", "color", ",", "piece_count", ")", "piece_count", "=", "0", "# Set the mover counters.", "self", ".", "move_number", "=", "int", "(", "parts", "[", "3", "]", ")", "or", "1", "# Reset the transposition table.", "self", ".", "transpositions", "=", "collections", ".", "Counter", "(", "(", "self", ".", "zobrist_hash", "(", ")", ",", ")", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.push_usi
Parses a move in standard coordinate notation, makes the move and puts it on the the move stack. Raises `ValueError` if neither legal nor a null move. Returns the move.
shogi/__init__.py
def push_usi(self, usi): ''' Parses a move in standard coordinate notation, makes the move and puts it on the the move stack. Raises `ValueError` if neither legal nor a null move. Returns the move. ''' move = Move.from_usi(usi) self.push(move) return move
def push_usi(self, usi): ''' Parses a move in standard coordinate notation, makes the move and puts it on the the move stack. Raises `ValueError` if neither legal nor a null move. Returns the move. ''' move = Move.from_usi(usi) self.push(move) return move
[ "Parses", "a", "move", "in", "standard", "coordinate", "notation", "makes", "the", "move", "and", "puts", "it", "on", "the", "the", "move", "stack", ".", "Raises", "ValueError", "if", "neither", "legal", "nor", "a", "null", "move", ".", "Returns", "the", "move", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L1234-L1243
[ "def", "push_usi", "(", "self", ",", "usi", ")", ":", "move", "=", "Move", ".", "from_usi", "(", "usi", ")", "self", ".", "push", "(", "move", ")", "return", "move" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Board.zobrist_hash
Returns a Zobrist hash of the current position.
shogi/__init__.py
def zobrist_hash(self, array=None): ''' Returns a Zobrist hash of the current position. ''' # Hash in the board setup. zobrist_hash = self.board_zobrist_hash(array) if array is None: array = DEFAULT_RANDOM_ARRAY if self.turn == WHITE: zobrist_hash ^= array[2268] # pieces in hand pattern is # 19 * 5 * 5 * 5 * 5 * 3 * 3 = 106875 < pow(2, 17) # just checking black side is okay in normal state i = ( self.pieces_in_hand[BLACK][ROOK] * 35625 + self.pieces_in_hand[BLACK][BISHOP] * 11875 + self.pieces_in_hand[BLACK][GOLD] * 2375 + self.pieces_in_hand[BLACK][SILVER] * 475 + self.pieces_in_hand[BLACK][KNIGHT] * 95 + self.pieces_in_hand[BLACK][LANCE] * 19 + self.pieces_in_hand[BLACK][PAWN]) bit = bit_scan(i) while bit != -1 and bit is not None: zobrist_hash ^= array[2269 + bit] bit = bit_scan(i, bit + 1) return zobrist_hash
def zobrist_hash(self, array=None): ''' Returns a Zobrist hash of the current position. ''' # Hash in the board setup. zobrist_hash = self.board_zobrist_hash(array) if array is None: array = DEFAULT_RANDOM_ARRAY if self.turn == WHITE: zobrist_hash ^= array[2268] # pieces in hand pattern is # 19 * 5 * 5 * 5 * 5 * 3 * 3 = 106875 < pow(2, 17) # just checking black side is okay in normal state i = ( self.pieces_in_hand[BLACK][ROOK] * 35625 + self.pieces_in_hand[BLACK][BISHOP] * 11875 + self.pieces_in_hand[BLACK][GOLD] * 2375 + self.pieces_in_hand[BLACK][SILVER] * 475 + self.pieces_in_hand[BLACK][KNIGHT] * 95 + self.pieces_in_hand[BLACK][LANCE] * 19 + self.pieces_in_hand[BLACK][PAWN]) bit = bit_scan(i) while bit != -1 and bit is not None: zobrist_hash ^= array[2269 + bit] bit = bit_scan(i, bit + 1) return zobrist_hash
[ "Returns", "a", "Zobrist", "hash", "of", "the", "current", "position", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L1353-L1382
[ "def", "zobrist_hash", "(", "self", ",", "array", "=", "None", ")", ":", "# Hash in the board setup.", "zobrist_hash", "=", "self", ".", "board_zobrist_hash", "(", "array", ")", "if", "array", "is", "None", ":", "array", "=", "DEFAULT_RANDOM_ARRAY", "if", "self", ".", "turn", "==", "WHITE", ":", "zobrist_hash", "^=", "array", "[", "2268", "]", "# pieces in hand pattern is", "# 19 * 5 * 5 * 5 * 5 * 3 * 3 = 106875 < pow(2, 17)", "# just checking black side is okay in normal state", "i", "=", "(", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "ROOK", "]", "*", "35625", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "BISHOP", "]", "*", "11875", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "GOLD", "]", "*", "2375", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "SILVER", "]", "*", "475", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "KNIGHT", "]", "*", "95", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "LANCE", "]", "*", "19", "+", "self", ".", "pieces_in_hand", "[", "BLACK", "]", "[", "PAWN", "]", ")", "bit", "=", "bit_scan", "(", "i", ")", "while", "bit", "!=", "-", "1", "and", "bit", "is", "not", "None", ":", "zobrist_hash", "^=", "array", "[", "2269", "+", "bit", "]", "bit", "=", "bit_scan", "(", "i", ",", "bit", "+", "1", ")", "return", "zobrist_hash" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Piece.symbol
Gets the symbol `p`, `l`, `n`, etc.
shogi/Piece.py
def symbol(self): ''' Gets the symbol `p`, `l`, `n`, etc. ''' if self.color == BLACK: return PIECE_SYMBOLS[self.piece_type].upper() else: return PIECE_SYMBOLS[self.piece_type]
def symbol(self): ''' Gets the symbol `p`, `l`, `n`, etc. ''' if self.color == BLACK: return PIECE_SYMBOLS[self.piece_type].upper() else: return PIECE_SYMBOLS[self.piece_type]
[ "Gets", "the", "symbol", "p", "l", "n", "etc", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/Piece.py#L24-L31
[ "def", "symbol", "(", "self", ")", ":", "if", "self", ".", "color", "==", "BLACK", ":", "return", "PIECE_SYMBOLS", "[", "self", ".", "piece_type", "]", ".", "upper", "(", ")", "else", ":", "return", "PIECE_SYMBOLS", "[", "self", ".", "piece_type", "]" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Piece.from_symbol
Creates a piece instance from a piece symbol. Raises `ValueError` if the symbol is invalid.
shogi/Piece.py
def from_symbol(cls, symbol): ''' Creates a piece instance from a piece symbol. Raises `ValueError` if the symbol is invalid. ''' if symbol.lower() == symbol: return cls(PIECE_SYMBOLS.index(symbol), WHITE) else: return cls(PIECE_SYMBOLS.index(symbol.lower()), BLACK)
def from_symbol(cls, symbol): ''' Creates a piece instance from a piece symbol. Raises `ValueError` if the symbol is invalid. ''' if symbol.lower() == symbol: return cls(PIECE_SYMBOLS.index(symbol), WHITE) else: return cls(PIECE_SYMBOLS.index(symbol.lower()), BLACK)
[ "Creates", "a", "piece", "instance", "from", "a", "piece", "symbol", ".", "Raises", "ValueError", "if", "the", "symbol", "is", "invalid", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/Piece.py#L66-L74
[ "def", "from_symbol", "(", "cls", ",", "symbol", ")", ":", "if", "symbol", ".", "lower", "(", ")", "==", "symbol", ":", "return", "cls", "(", "PIECE_SYMBOLS", ".", "index", "(", "symbol", ")", ",", "WHITE", ")", "else", ":", "return", "cls", "(", "PIECE_SYMBOLS", ".", "index", "(", "symbol", ".", "lower", "(", ")", ")", ",", "BLACK", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Move.usi
Gets an USI string for the move. For example a move from 7A to 8A would be `7a8a` or `7a8a+` if it is a promotion.
shogi/Move.py
def usi(self): ''' Gets an USI string for the move. For example a move from 7A to 8A would be `7a8a` or `7a8a+` if it is a promotion. ''' if self: if self.drop_piece_type: return '{0}*{1}'.format(PIECE_SYMBOLS[self.drop_piece_type].upper(), SQUARE_NAMES[self.to_square]) else: return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + \ ('+' if self.promotion else '') else: return '0000'
def usi(self): ''' Gets an USI string for the move. For example a move from 7A to 8A would be `7a8a` or `7a8a+` if it is a promotion. ''' if self: if self.drop_piece_type: return '{0}*{1}'.format(PIECE_SYMBOLS[self.drop_piece_type].upper(), SQUARE_NAMES[self.to_square]) else: return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + \ ('+' if self.promotion else '') else: return '0000'
[ "Gets", "an", "USI", "string", "for", "the", "move", ".", "For", "example", "a", "move", "from", "7A", "to", "8A", "would", "be", "7a8a", "or", "7a8a", "+", "if", "it", "is", "a", "promotion", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/Move.py#L48-L61
[ "def", "usi", "(", "self", ")", ":", "if", "self", ":", "if", "self", ".", "drop_piece_type", ":", "return", "'{0}*{1}'", ".", "format", "(", "PIECE_SYMBOLS", "[", "self", ".", "drop_piece_type", "]", ".", "upper", "(", ")", ",", "SQUARE_NAMES", "[", "self", ".", "to_square", "]", ")", "else", ":", "return", "SQUARE_NAMES", "[", "self", ".", "from_square", "]", "+", "SQUARE_NAMES", "[", "self", ".", "to_square", "]", "+", "(", "'+'", "if", "self", ".", "promotion", "else", "''", ")", "else", ":", "return", "'0000'" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
Move.from_usi
Parses an USI string. Raises `ValueError` if the USI string is invalid.
shogi/Move.py
def from_usi(cls, usi): ''' Parses an USI string. Raises `ValueError` if the USI string is invalid. ''' if usi == '0000': return cls.null() elif len(usi) == 4: if usi[1] == '*': piece = Piece.from_symbol(usi[0]) return cls(None, SQUARE_NAMES.index(usi[2:4]), False, piece.piece_type) else: return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4])) elif len(usi) == 5 and usi[4] == '+': return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4]), True) else: raise ValueError('expected usi string to be of length 4 or 5')
def from_usi(cls, usi): ''' Parses an USI string. Raises `ValueError` if the USI string is invalid. ''' if usi == '0000': return cls.null() elif len(usi) == 4: if usi[1] == '*': piece = Piece.from_symbol(usi[0]) return cls(None, SQUARE_NAMES.index(usi[2:4]), False, piece.piece_type) else: return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4])) elif len(usi) == 5 and usi[4] == '+': return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4]), True) else: raise ValueError('expected usi string to be of length 4 or 5')
[ "Parses", "an", "USI", "string", ".", "Raises", "ValueError", "if", "the", "USI", "string", "is", "invalid", "." ]
gunyarakun/python-shogi
python
https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/Move.py#L94-L110
[ "def", "from_usi", "(", "cls", ",", "usi", ")", ":", "if", "usi", "==", "'0000'", ":", "return", "cls", ".", "null", "(", ")", "elif", "len", "(", "usi", ")", "==", "4", ":", "if", "usi", "[", "1", "]", "==", "'*'", ":", "piece", "=", "Piece", ".", "from_symbol", "(", "usi", "[", "0", "]", ")", "return", "cls", "(", "None", ",", "SQUARE_NAMES", ".", "index", "(", "usi", "[", "2", ":", "4", "]", ")", ",", "False", ",", "piece", ".", "piece_type", ")", "else", ":", "return", "cls", "(", "SQUARE_NAMES", ".", "index", "(", "usi", "[", "0", ":", "2", "]", ")", ",", "SQUARE_NAMES", ".", "index", "(", "usi", "[", "2", ":", "4", "]", ")", ")", "elif", "len", "(", "usi", ")", "==", "5", "and", "usi", "[", "4", "]", "==", "'+'", ":", "return", "cls", "(", "SQUARE_NAMES", ".", "index", "(", "usi", "[", "0", ":", "2", "]", ")", ",", "SQUARE_NAMES", ".", "index", "(", "usi", "[", "2", ":", "4", "]", ")", ",", "True", ")", "else", ":", "raise", "ValueError", "(", "'expected usi string to be of length 4 or 5'", ")" ]
137fe5f5e72251e8a97a1dba4a9b44b7c3c79914
test
parse_commits
Accept a string and parse it into many commits. Parse and yield each commit-dictionary. This function is a generator.
git2json/parser.py
def parse_commits(data): '''Accept a string and parse it into many commits. Parse and yield each commit-dictionary. This function is a generator. ''' raw_commits = RE_COMMIT.finditer(data) for rc in raw_commits: full_commit = rc.groups()[0] parts = RE_COMMIT.match(full_commit).groupdict() parsed_commit = parse_commit(parts) yield parsed_commit
def parse_commits(data): '''Accept a string and parse it into many commits. Parse and yield each commit-dictionary. This function is a generator. ''' raw_commits = RE_COMMIT.finditer(data) for rc in raw_commits: full_commit = rc.groups()[0] parts = RE_COMMIT.match(full_commit).groupdict() parsed_commit = parse_commit(parts) yield parsed_commit
[ "Accept", "a", "string", "and", "parse", "it", "into", "many", "commits", ".", "Parse", "and", "yield", "each", "commit", "-", "dictionary", ".", "This", "function", "is", "a", "generator", "." ]
tarmstrong/git2json
python
https://github.com/tarmstrong/git2json/blob/ee2688f91841b5e8d1e478a228b03b9df8e7d2db/git2json/parser.py#L40-L50
[ "def", "parse_commits", "(", "data", ")", ":", "raw_commits", "=", "RE_COMMIT", ".", "finditer", "(", "data", ")", "for", "rc", "in", "raw_commits", ":", "full_commit", "=", "rc", ".", "groups", "(", ")", "[", "0", "]", "parts", "=", "RE_COMMIT", ".", "match", "(", "full_commit", ")", ".", "groupdict", "(", ")", "parsed_commit", "=", "parse_commit", "(", "parts", ")", "yield", "parsed_commit" ]
ee2688f91841b5e8d1e478a228b03b9df8e7d2db
test
parse_commit
Accept a parsed single commit. Some of the named groups require further processing, so parse those groups. Return a dictionary representing the completely parsed commit.
git2json/parser.py
def parse_commit(parts): '''Accept a parsed single commit. Some of the named groups require further processing, so parse those groups. Return a dictionary representing the completely parsed commit. ''' commit = {} commit['commit'] = parts['commit'] commit['tree'] = parts['tree'] parent_block = parts['parents'] commit['parents'] = [ parse_parent_line(parentline) for parentline in parent_block.splitlines() ] commit['author'] = parse_author_line(parts['author']) commit['committer'] = parse_committer_line(parts['committer']) message_lines = [ parse_message_line(msgline) for msgline in parts['message'].split("\n") ] commit['message'] = "\n".join( msgline for msgline in message_lines if msgline is not None ) commit['changes'] = [ parse_numstat_line(numstat) for numstat in parts['numstats'].splitlines() ] return commit
def parse_commit(parts): '''Accept a parsed single commit. Some of the named groups require further processing, so parse those groups. Return a dictionary representing the completely parsed commit. ''' commit = {} commit['commit'] = parts['commit'] commit['tree'] = parts['tree'] parent_block = parts['parents'] commit['parents'] = [ parse_parent_line(parentline) for parentline in parent_block.splitlines() ] commit['author'] = parse_author_line(parts['author']) commit['committer'] = parse_committer_line(parts['committer']) message_lines = [ parse_message_line(msgline) for msgline in parts['message'].split("\n") ] commit['message'] = "\n".join( msgline for msgline in message_lines if msgline is not None ) commit['changes'] = [ parse_numstat_line(numstat) for numstat in parts['numstats'].splitlines() ] return commit
[ "Accept", "a", "parsed", "single", "commit", ".", "Some", "of", "the", "named", "groups", "require", "further", "processing", "so", "parse", "those", "groups", ".", "Return", "a", "dictionary", "representing", "the", "completely", "parsed", "commit", "." ]
tarmstrong/git2json
python
https://github.com/tarmstrong/git2json/blob/ee2688f91841b5e8d1e478a228b03b9df8e7d2db/git2json/parser.py#L53-L86
[ "def", "parse_commit", "(", "parts", ")", ":", "commit", "=", "{", "}", "commit", "[", "'commit'", "]", "=", "parts", "[", "'commit'", "]", "commit", "[", "'tree'", "]", "=", "parts", "[", "'tree'", "]", "parent_block", "=", "parts", "[", "'parents'", "]", "commit", "[", "'parents'", "]", "=", "[", "parse_parent_line", "(", "parentline", ")", "for", "parentline", "in", "parent_block", ".", "splitlines", "(", ")", "]", "commit", "[", "'author'", "]", "=", "parse_author_line", "(", "parts", "[", "'author'", "]", ")", "commit", "[", "'committer'", "]", "=", "parse_committer_line", "(", "parts", "[", "'committer'", "]", ")", "message_lines", "=", "[", "parse_message_line", "(", "msgline", ")", "for", "msgline", "in", "parts", "[", "'message'", "]", ".", "split", "(", "\"\\n\"", ")", "]", "commit", "[", "'message'", "]", "=", "\"\\n\"", ".", "join", "(", "msgline", "for", "msgline", "in", "message_lines", "if", "msgline", "is", "not", "None", ")", "commit", "[", "'changes'", "]", "=", "[", "parse_numstat_line", "(", "numstat", ")", "for", "numstat", "in", "parts", "[", "'numstats'", "]", ".", "splitlines", "(", ")", "]", "return", "commit" ]
ee2688f91841b5e8d1e478a228b03b9df8e7d2db
test
run_git_log
run_git_log([git_dir]) -> File Run `git log --numstat --pretty=raw` on the specified git repository and return its stdout as a pseudo-File.
git2json/__init__.py
def run_git_log(git_dir=None, git_since=None): '''run_git_log([git_dir]) -> File Run `git log --numstat --pretty=raw` on the specified git repository and return its stdout as a pseudo-File.''' import subprocess if git_dir: command = [ 'git', '--git-dir=' + git_dir, 'log', '--numstat', '--pretty=raw' ] else: command = ['git', 'log', '--numstat', '--pretty=raw'] if git_since is not None: command.append('--since=' + git_since) raw_git_log = subprocess.Popen( command, stdout=subprocess.PIPE ) if sys.version_info < (3, 0): return raw_git_log.stdout else: return raw_git_log.stdout.read().decode('utf-8', 'ignore')
def run_git_log(git_dir=None, git_since=None): '''run_git_log([git_dir]) -> File Run `git log --numstat --pretty=raw` on the specified git repository and return its stdout as a pseudo-File.''' import subprocess if git_dir: command = [ 'git', '--git-dir=' + git_dir, 'log', '--numstat', '--pretty=raw' ] else: command = ['git', 'log', '--numstat', '--pretty=raw'] if git_since is not None: command.append('--since=' + git_since) raw_git_log = subprocess.Popen( command, stdout=subprocess.PIPE ) if sys.version_info < (3, 0): return raw_git_log.stdout else: return raw_git_log.stdout.read().decode('utf-8', 'ignore')
[ "run_git_log", "(", "[", "git_dir", "]", ")", "-", ">", "File" ]
tarmstrong/git2json
python
https://github.com/tarmstrong/git2json/blob/ee2688f91841b5e8d1e478a228b03b9df8e7d2db/git2json/__init__.py#L56-L81
[ "def", "run_git_log", "(", "git_dir", "=", "None", ",", "git_since", "=", "None", ")", ":", "import", "subprocess", "if", "git_dir", ":", "command", "=", "[", "'git'", ",", "'--git-dir='", "+", "git_dir", ",", "'log'", ",", "'--numstat'", ",", "'--pretty=raw'", "]", "else", ":", "command", "=", "[", "'git'", ",", "'log'", ",", "'--numstat'", ",", "'--pretty=raw'", "]", "if", "git_since", "is", "not", "None", ":", "command", ".", "append", "(", "'--since='", "+", "git_since", ")", "raw_git_log", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "return", "raw_git_log", ".", "stdout", "else", ":", "return", "raw_git_log", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ",", "'ignore'", ")" ]
ee2688f91841b5e8d1e478a228b03b9df8e7d2db
test
main
Examples: simple call $ vl README.md Adding debug outputs $ vl README.md --debug Adding a custom timeout for each url. time on seconds. $ vl README.md -t 3 Adding a custom size param, to add throttle n requests per time $ vl README -s 1000 Skipping some error codes. This will allow 500 and 404 responses to be ignored $ vl README.md -a 500,404 Adding Whitelists $ vl README.md -w server1.com,server2.com
vl/cli.py
def main(doc, timeout, size, debug, allow_codes, whitelist): """ Examples: simple call $ vl README.md Adding debug outputs $ vl README.md --debug Adding a custom timeout for each url. time on seconds. $ vl README.md -t 3 Adding a custom size param, to add throttle n requests per time $ vl README -s 1000 Skipping some error codes. This will allow 500 and 404 responses to be ignored $ vl README.md -a 500,404 Adding Whitelists $ vl README.md -w server1.com,server2.com """ t0 = time.time() links = [i[0] for i in LINK_RE.findall(doc.read())] request_urls = [] counts = {} for link in links: # no static if is_static(link): STATICS.append(link) continue # no dupes if link in counts: counts[link] += 1 continue else: counts[link] = 1 parsed = urlparse(link) # fix no scheme links if not parsed.scheme: link = 'http://{0}'.format(link) # whitelisted if whitelist: exists = [i for i in whitelist if i in parsed.netloc] if exists: WHITELISTED.append(link) continue request_urls.append(link) # removing dupes counts_keys = counts.keys() DUPES.extend([(i, counts[i]) for i in counts_keys if counts[i] > 1]) requests = (grequests.head(u, timeout=timeout, verify=False) for u in request_urls) responses = grequests.imap(requests, exception_handler=handle_exception, size=size) for res in responses: color = 'green' if is_error_code(res.status_code): if res.status_code not in allow_codes: ERRORS.append((res.status_code, res.url)) color = 'red' else: WHITELISTED.append(res.url) status = click.style(str(res.status_code), fg=color) click.echo('[{}] {}'.format(status, res.url)) errors_len = len(ERRORS) exceptions_len = len(EXCEPTIONS) dupes_len = len(DUPES) white_len = len(WHITELISTED) if errors_len: click.echo() click.echo('Failed URLs:') for code, url in ERRORS: code = click.style(str(code), fg='red') click.echo('[{0}] {1}'.format(code, url)) if exceptions_len and debug: import ssl click.echo('Exceptions raised:') click.echo('Note: OpenSSL Version = {0}'.format(ssl.OPENSSL_VERSION)) click.secho('Check URLs for possible false positives', fg='yellow') for url, exception in EXCEPTIONS: click.echo('- {0}'.format(url)) click.secho('{0}'.format(exception), fg='red', bold=True) if dupes_len and debug: # pragma: nocover click.echo('Dupes:') for url, count in DUPES: click.secho('- {0} - {1} times'.format(url, count), fg='yellow', bold=True) if white_len and debug: click.echo() click.echo('Whitelisted (allowed codes and whitelisted param)') for url in WHITELISTED: click.secho('- {0}'.format(url), fg='magenta') click.secho('Total Links Parsed {0}'.format(len(links)), fg='green') click.secho('Total Errors {0}'.format(errors_len), fg='red') click.secho('Total Exceptions {0}'.format(exceptions_len), fg='red') click.secho('Total Dupes {0}'.format(dupes_len), fg='yellow') click.secho('Total whitelisted {0}'.format(white_len), fg='yellow') click.secho('Total static {0}'.format(len(STATICS)), fg='yellow') if debug: click.echo('Execution time: {0:.2f} seconds'.format(time.time() - t0)) if errors_len: sys.exit(1)
def main(doc, timeout, size, debug, allow_codes, whitelist): """ Examples: simple call $ vl README.md Adding debug outputs $ vl README.md --debug Adding a custom timeout for each url. time on seconds. $ vl README.md -t 3 Adding a custom size param, to add throttle n requests per time $ vl README -s 1000 Skipping some error codes. This will allow 500 and 404 responses to be ignored $ vl README.md -a 500,404 Adding Whitelists $ vl README.md -w server1.com,server2.com """ t0 = time.time() links = [i[0] for i in LINK_RE.findall(doc.read())] request_urls = [] counts = {} for link in links: # no static if is_static(link): STATICS.append(link) continue # no dupes if link in counts: counts[link] += 1 continue else: counts[link] = 1 parsed = urlparse(link) # fix no scheme links if not parsed.scheme: link = 'http://{0}'.format(link) # whitelisted if whitelist: exists = [i for i in whitelist if i in parsed.netloc] if exists: WHITELISTED.append(link) continue request_urls.append(link) # removing dupes counts_keys = counts.keys() DUPES.extend([(i, counts[i]) for i in counts_keys if counts[i] > 1]) requests = (grequests.head(u, timeout=timeout, verify=False) for u in request_urls) responses = grequests.imap(requests, exception_handler=handle_exception, size=size) for res in responses: color = 'green' if is_error_code(res.status_code): if res.status_code not in allow_codes: ERRORS.append((res.status_code, res.url)) color = 'red' else: WHITELISTED.append(res.url) status = click.style(str(res.status_code), fg=color) click.echo('[{}] {}'.format(status, res.url)) errors_len = len(ERRORS) exceptions_len = len(EXCEPTIONS) dupes_len = len(DUPES) white_len = len(WHITELISTED) if errors_len: click.echo() click.echo('Failed URLs:') for code, url in ERRORS: code = click.style(str(code), fg='red') click.echo('[{0}] {1}'.format(code, url)) if exceptions_len and debug: import ssl click.echo('Exceptions raised:') click.echo('Note: OpenSSL Version = {0}'.format(ssl.OPENSSL_VERSION)) click.secho('Check URLs for possible false positives', fg='yellow') for url, exception in EXCEPTIONS: click.echo('- {0}'.format(url)) click.secho('{0}'.format(exception), fg='red', bold=True) if dupes_len and debug: # pragma: nocover click.echo('Dupes:') for url, count in DUPES: click.secho('- {0} - {1} times'.format(url, count), fg='yellow', bold=True) if white_len and debug: click.echo() click.echo('Whitelisted (allowed codes and whitelisted param)') for url in WHITELISTED: click.secho('- {0}'.format(url), fg='magenta') click.secho('Total Links Parsed {0}'.format(len(links)), fg='green') click.secho('Total Errors {0}'.format(errors_len), fg='red') click.secho('Total Exceptions {0}'.format(exceptions_len), fg='red') click.secho('Total Dupes {0}'.format(dupes_len), fg='yellow') click.secho('Total whitelisted {0}'.format(white_len), fg='yellow') click.secho('Total static {0}'.format(len(STATICS)), fg='yellow') if debug: click.echo('Execution time: {0:.2f} seconds'.format(time.time() - t0)) if errors_len: sys.exit(1)
[ "Examples", ":", "simple", "call", "$", "vl", "README", ".", "md" ]
ellisonleao/vl
python
https://github.com/ellisonleao/vl/blob/2650b1fc9172a1fa46aaef4e66bd944bcc0a6ece/vl/cli.py#L90-L213
[ "def", "main", "(", "doc", ",", "timeout", ",", "size", ",", "debug", ",", "allow_codes", ",", "whitelist", ")", ":", "t0", "=", "time", ".", "time", "(", ")", "links", "=", "[", "i", "[", "0", "]", "for", "i", "in", "LINK_RE", ".", "findall", "(", "doc", ".", "read", "(", ")", ")", "]", "request_urls", "=", "[", "]", "counts", "=", "{", "}", "for", "link", "in", "links", ":", "# no static", "if", "is_static", "(", "link", ")", ":", "STATICS", ".", "append", "(", "link", ")", "continue", "# no dupes", "if", "link", "in", "counts", ":", "counts", "[", "link", "]", "+=", "1", "continue", "else", ":", "counts", "[", "link", "]", "=", "1", "parsed", "=", "urlparse", "(", "link", ")", "# fix no scheme links", "if", "not", "parsed", ".", "scheme", ":", "link", "=", "'http://{0}'", ".", "format", "(", "link", ")", "# whitelisted", "if", "whitelist", ":", "exists", "=", "[", "i", "for", "i", "in", "whitelist", "if", "i", "in", "parsed", ".", "netloc", "]", "if", "exists", ":", "WHITELISTED", ".", "append", "(", "link", ")", "continue", "request_urls", ".", "append", "(", "link", ")", "# removing dupes", "counts_keys", "=", "counts", ".", "keys", "(", ")", "DUPES", ".", "extend", "(", "[", "(", "i", ",", "counts", "[", "i", "]", ")", "for", "i", "in", "counts_keys", "if", "counts", "[", "i", "]", ">", "1", "]", ")", "requests", "=", "(", "grequests", ".", "head", "(", "u", ",", "timeout", "=", "timeout", ",", "verify", "=", "False", ")", "for", "u", "in", "request_urls", ")", "responses", "=", "grequests", ".", "imap", "(", "requests", ",", "exception_handler", "=", "handle_exception", ",", "size", "=", "size", ")", "for", "res", "in", "responses", ":", "color", "=", "'green'", "if", "is_error_code", "(", "res", ".", "status_code", ")", ":", "if", "res", ".", "status_code", "not", "in", "allow_codes", ":", "ERRORS", ".", "append", "(", "(", "res", ".", "status_code", ",", "res", ".", "url", ")", ")", "color", "=", "'red'", "else", ":", "WHITELISTED", ".", "append", "(", "res", ".", "url", ")", "status", "=", "click", ".", "style", "(", "str", "(", "res", ".", "status_code", ")", ",", "fg", "=", "color", ")", "click", ".", "echo", "(", "'[{}] {}'", ".", "format", "(", "status", ",", "res", ".", "url", ")", ")", "errors_len", "=", "len", "(", "ERRORS", ")", "exceptions_len", "=", "len", "(", "EXCEPTIONS", ")", "dupes_len", "=", "len", "(", "DUPES", ")", "white_len", "=", "len", "(", "WHITELISTED", ")", "if", "errors_len", ":", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'Failed URLs:'", ")", "for", "code", ",", "url", "in", "ERRORS", ":", "code", "=", "click", ".", "style", "(", "str", "(", "code", ")", ",", "fg", "=", "'red'", ")", "click", ".", "echo", "(", "'[{0}] {1}'", ".", "format", "(", "code", ",", "url", ")", ")", "if", "exceptions_len", "and", "debug", ":", "import", "ssl", "click", ".", "echo", "(", "'Exceptions raised:'", ")", "click", ".", "echo", "(", "'Note: OpenSSL Version = {0}'", ".", "format", "(", "ssl", ".", "OPENSSL_VERSION", ")", ")", "click", ".", "secho", "(", "'Check URLs for possible false positives'", ",", "fg", "=", "'yellow'", ")", "for", "url", ",", "exception", "in", "EXCEPTIONS", ":", "click", ".", "echo", "(", "'- {0}'", ".", "format", "(", "url", ")", ")", "click", ".", "secho", "(", "'{0}'", ".", "format", "(", "exception", ")", ",", "fg", "=", "'red'", ",", "bold", "=", "True", ")", "if", "dupes_len", "and", "debug", ":", "# pragma: nocover", "click", ".", "echo", "(", "'Dupes:'", ")", "for", "url", ",", "count", "in", "DUPES", ":", "click", ".", "secho", "(", "'- {0} - {1} times'", ".", "format", "(", "url", ",", "count", ")", ",", "fg", "=", "'yellow'", ",", "bold", "=", "True", ")", "if", "white_len", "and", "debug", ":", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'Whitelisted (allowed codes and whitelisted param)'", ")", "for", "url", "in", "WHITELISTED", ":", "click", ".", "secho", "(", "'- {0}'", ".", "format", "(", "url", ")", ",", "fg", "=", "'magenta'", ")", "click", ".", "secho", "(", "'Total Links Parsed {0}'", ".", "format", "(", "len", "(", "links", ")", ")", ",", "fg", "=", "'green'", ")", "click", ".", "secho", "(", "'Total Errors {0}'", ".", "format", "(", "errors_len", ")", ",", "fg", "=", "'red'", ")", "click", ".", "secho", "(", "'Total Exceptions {0}'", ".", "format", "(", "exceptions_len", ")", ",", "fg", "=", "'red'", ")", "click", ".", "secho", "(", "'Total Dupes {0}'", ".", "format", "(", "dupes_len", ")", ",", "fg", "=", "'yellow'", ")", "click", ".", "secho", "(", "'Total whitelisted {0}'", ".", "format", "(", "white_len", ")", ",", "fg", "=", "'yellow'", ")", "click", ".", "secho", "(", "'Total static {0}'", ".", "format", "(", "len", "(", "STATICS", ")", ")", ",", "fg", "=", "'yellow'", ")", "if", "debug", ":", "click", ".", "echo", "(", "'Execution time: {0:.2f} seconds'", ".", "format", "(", "time", ".", "time", "(", ")", "-", "t0", ")", ")", "if", "errors_len", ":", "sys", ".", "exit", "(", "1", ")" ]
2650b1fc9172a1fa46aaef4e66bd944bcc0a6ece