text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sap_confirmation(self, apdu):
"""This function is called when the application is responding to a request, the apdu may be a simple ack, complex ack, error, reject or abort.""" |
if _debug: StateMachineAccessPoint._debug("sap_confirmation %r", apdu)
if isinstance(apdu, SimpleAckPDU) \
or isinstance(apdu, ComplexAckPDU) \
or isinstance(apdu, ErrorPDU) \
or isinstance(apdu, RejectPDU) \
or isinstance(apdu, AbortPDU):
# find the appropriate server transaction
for tr in self.serverTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduDestination == tr.pdu_address):
break
else:
return
# pass control to the transaction
tr.confirmation(apdu)
else:
raise RuntimeError("invalid APDU (10)") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_peer(self, peerAddr, networks=None):
"""Add a peer and optionally provide a list of the reachable networks.""" |
if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks)
# see if this is already a peer
if peerAddr in self.peers:
# add the (new?) reachable networks
if not networks:
networks = []
else:
self.peers[peerAddr].extend(networks)
else:
if not networks:
networks = []
# save the networks
self.peers[peerAddr] = networks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_peer(self, peerAddr):
"""Delete a peer.""" |
if _debug: BTR._debug("delete_peer %r", peerAddr)
# get the peer networks
# networks = self.peers[peerAddr]
### send a control message upstream that these are no longer reachable
# now delete the peer
del self.peers[peerAddr] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, addr, ttl):
"""Initiate the process of registering with a BBMD.""" |
# a little error checking
if ttl <= 0:
raise ValueError("time-to-live must be greater than zero")
# save the BBMD address and time-to-live
if isinstance(addr, Address):
self.bbmdAddress = addr
else:
self.bbmdAddress = Address(addr)
self.bbmdTimeToLive = ttl
# install this task to run when it gets a chance
self.install_task(when=0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self):
"""Drop the registration with a BBMD.""" |
pdu = RegisterForeignDevice(0)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu)
# change the status to unregistered
self.registrationStatus = -2
# clear the BBMD address and time-to-live
self.bbmdAddress = None
self.bbmdTimeToLive = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_task(self):
"""Called when the registration request should be sent to the BBMD.""" |
pdu = RegisterForeignDevice(self.bbmdTimeToLive)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_foreign_device(self, addr, ttl):
"""Add a foreign device to the FDT.""" |
if _debug: BIPBBMD._debug("register_foreign_device %r %r", addr, ttl)
# see if it is an address or make it one
if isinstance(addr, Address):
pass
elif isinstance(addr, str):
addr = Address(addr)
else:
raise TypeError("addr must be a string or an Address")
for fdte in self.bbmdFDT:
if addr == fdte.fdAddress:
break
else:
fdte = FDTEntry()
fdte.fdAddress = addr
self.bbmdFDT.append( fdte )
fdte.fdTTL = ttl
fdte.fdRemain = ttl + 5
# return success
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_max_segments_accepted(arg):
"""Encode the maximum number of segments the device will accept, Section 20.1.2.4, and if the device says it can only accept one segment it shouldn't say that it supports segmentation!""" |
# unspecified
if not arg:
return 0
if arg > 64:
return 7
# the largest number not greater than the arg
for i in range(6, 0, -1):
if _max_segments_accepted_encoding[i] <= arg:
return i
raise ValueError("invalid max max segments accepted: %r" % (arg,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_max_apdu_length_accepted(arg):
"""Return the encoding of the highest encodable value less than the value of the arg.""" |
for i in range(5, -1, -1):
if (arg >= _max_apdu_length_encoding[i]):
return i
raise ValueError("invalid max APDU length accepted: %r" % (arg,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, pdu):
"""encode the contents of the APCI into the PDU.""" |
if _debug: APCI._debug("encode %r", pdu)
PCI.update(pdu, self)
if (self.apduType == ConfirmedRequestPDU.pduType):
# PDU type
buff = self.apduType << 4
if self.apduSeg:
buff += 0x08
if self.apduMor:
buff += 0x04
if self.apduSA:
buff += 0x02
pdu.put(buff)
pdu.put((self.apduMaxSegs << 4) + self.apduMaxResp)
pdu.put(self.apduInvokeID)
if self.apduSeg:
pdu.put(self.apduSeq)
pdu.put(self.apduWin)
pdu.put(self.apduService)
elif (self.apduType == UnconfirmedRequestPDU.pduType):
pdu.put(self.apduType << 4)
pdu.put(self.apduService)
elif (self.apduType == SimpleAckPDU.pduType):
pdu.put(self.apduType << 4)
pdu.put(self.apduInvokeID)
pdu.put(self.apduService)
elif (self.apduType == ComplexAckPDU.pduType):
# PDU type
buff = self.apduType << 4
if self.apduSeg:
buff += 0x08
if self.apduMor:
buff += 0x04
pdu.put(buff)
pdu.put(self.apduInvokeID)
if self.apduSeg:
pdu.put(self.apduSeq)
pdu.put(self.apduWin)
pdu.put(self.apduService)
elif (self.apduType == SegmentAckPDU.pduType):
# PDU type
buff = self.apduType << 4
if self.apduNak:
buff += 0x02
if self.apduSrv:
buff += 0x01
pdu.put(buff)
pdu.put(self.apduInvokeID)
pdu.put(self.apduSeq)
pdu.put(self.apduWin)
elif (self.apduType == ErrorPDU.pduType):
pdu.put(self.apduType << 4)
pdu.put(self.apduInvokeID)
pdu.put(self.apduService)
elif (self.apduType == RejectPDU.pduType):
pdu.put(self.apduType << 4)
pdu.put(self.apduInvokeID)
pdu.put(self.apduAbortRejectReason)
elif (self.apduType == AbortPDU.pduType):
# PDU type
buff = self.apduType << 4
if self.apduSrv:
buff += 0x01
pdu.put(buff)
pdu.put(self.apduInvokeID)
pdu.put(self.apduAbortRejectReason)
else:
raise ValueError("invalid APCI.apduType") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, pdu):
"""decode the contents of the PDU into the APCI.""" |
if _debug: APCI._debug("decode %r", pdu)
PCI.update(self, pdu)
# decode the first octet
buff = pdu.get()
# decode the APCI type
self.apduType = (buff >> 4) & 0x0F
if (self.apduType == ConfirmedRequestPDU.pduType):
self.apduSeg = ((buff & 0x08) != 0)
self.apduMor = ((buff & 0x04) != 0)
self.apduSA = ((buff & 0x02) != 0)
buff = pdu.get()
self.apduMaxSegs = (buff >> 4) & 0x07
self.apduMaxResp = buff & 0x0F
self.apduInvokeID = pdu.get()
if self.apduSeg:
self.apduSeq = pdu.get()
self.apduWin = pdu.get()
self.apduService = pdu.get()
self.pduData = pdu.pduData
elif (self.apduType == UnconfirmedRequestPDU.pduType):
self.apduService = pdu.get()
self.pduData = pdu.pduData
elif (self.apduType == SimpleAckPDU.pduType):
self.apduInvokeID = pdu.get()
self.apduService = pdu.get()
elif (self.apduType == ComplexAckPDU.pduType):
self.apduSeg = ((buff & 0x08) != 0)
self.apduMor = ((buff & 0x04) != 0)
self.apduInvokeID = pdu.get()
if self.apduSeg:
self.apduSeq = pdu.get()
self.apduWin = pdu.get()
self.apduService = pdu.get()
self.pduData = pdu.pduData
elif (self.apduType == SegmentAckPDU.pduType):
self.apduNak = ((buff & 0x02) != 0)
self.apduSrv = ((buff & 0x01) != 0)
self.apduInvokeID = pdu.get()
self.apduSeq = pdu.get()
self.apduWin = pdu.get()
elif (self.apduType == ErrorPDU.pduType):
self.apduInvokeID = pdu.get()
self.apduService = pdu.get()
self.pduData = pdu.pduData
elif (self.apduType == RejectPDU.pduType):
self.apduInvokeID = pdu.get()
self.apduAbortRejectReason = pdu.get()
elif (self.apduType == AbortPDU.pduType):
self.apduSrv = ((buff & 0x01) != 0)
self.apduInvokeID = pdu.get()
self.apduAbortRejectReason = pdu.get()
self.pduData = pdu.pduData
else:
raise DecodingError("invalid APDU type") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, pdu):
"""Decode a tag from the PDU.""" |
try:
tag = pdu.get()
# extract the type
self.tagClass = (tag >> 3) & 0x01
# extract the tag number
self.tagNumber = (tag >> 4)
if (self.tagNumber == 0x0F):
self.tagNumber = pdu.get()
# extract the length
self.tagLVT = tag & 0x07
if (self.tagLVT == 5):
self.tagLVT = pdu.get()
if (self.tagLVT == 254):
self.tagLVT = pdu.get_short()
elif (self.tagLVT == 255):
self.tagLVT = pdu.get_long()
elif (self.tagLVT == 6):
self.tagClass = Tag.openingTagClass
self.tagLVT = 0
elif (self.tagLVT == 7):
self.tagClass = Tag.closingTagClass
self.tagLVT = 0
# application tagged boolean has no more data
if (self.tagClass == Tag.applicationTagClass) and (self.tagNumber == Tag.booleanAppTag):
# tagLVT contains value
self.tagData = ''
else:
# tagLVT contains length
self.tagData = pdu.get_data(self.tagLVT)
except DecodingError:
raise InvalidTag("invalid tag encoding") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_to_context(self, context):
"""Return a context encoded tag.""" |
if self.tagClass != Tag.applicationTagClass:
raise ValueError("application tag required")
# application tagged boolean now has data
if (self.tagNumber == Tag.booleanAppTag):
return ContextTag(context, chr(self.tagLVT))
else:
return ContextTag(context, self.tagData) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_to_app(self, dataType):
"""Return an application encoded tag.""" |
if self.tagClass != Tag.contextTagClass:
raise ValueError("context tag required")
# context booleans have value in data
if (dataType == Tag.booleanAppTag):
return Tag(Tag.applicationTagClass, Tag.booleanAppTag, struct.unpack('B', self.tagData)[0], '')
else:
return ApplicationTag(dataType, self.tagData) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, pdu):
"""encode the contents of the BSLCI into the PDU.""" |
if _debug: BSLCI._debug("encode %r", pdu)
# copy the basics
PCI.update(pdu, self)
pdu.put( self.bslciType ) # 0x83
pdu.put( self.bslciFunction )
if (self.bslciLength != len(self.pduData) + 4):
raise EncodingError("invalid BSLCI length")
pdu.put_short( self.bslciLength ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, pdu):
"""decode the contents of the PDU into the BSLCI.""" |
if _debug: BSLCI._debug("decode %r", pdu)
# copy the basics
PCI.update(self, pdu)
self.bslciType = pdu.get()
if self.bslciType != 0x83:
raise DecodingError("invalid BSLCI type")
self.bslciFunction = pdu.get()
self.bslciLength = pdu.get_short()
if (self.bslciLength != len(pdu.pduData) + 4):
raise DecodingError("invalid BSLCI length") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None):
"""Add a handler to stderr with our custom formatter to a logger.""" |
if isinstance(loggerRef, logging.Logger):
pass
elif isinstance(loggerRef, str):
# check for root
if not loggerRef:
loggerRef = _log
# check for a valid logger name
elif loggerRef not in logging.Logger.manager.loggerDict:
raise RuntimeError("not a valid logger name: %r" % (loggerRef,))
# get the logger
loggerRef = logging.getLogger(loggerRef)
else:
raise RuntimeError("not a valid logger reference: %r" % (loggerRef,))
# see if this (or its parent) is a module level logger
if hasattr(loggerRef, 'globs'):
loggerRef.globs['_debug'] += 1
elif hasattr(loggerRef.parent, 'globs'):
loggerRef.parent.globs['_debug'] += 1
# make a handler if one wasn't provided
if not handler:
handler = logging.StreamHandler()
handler.setLevel(level)
# use our formatter
handler.setFormatter(LoggingFormatter(color))
# add it to the logger
loggerRef.addHandler(handler)
# make sure the logger has at least this level
loggerRef.setLevel(level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_me(iocb):
""" When a controller completes the processing of a request, the IOCB can contain one or more functions to be called. """ |
if _debug: call_me._debug("callback_function %r", iocb)
# it will be successful or have an error
print("call me, %r or %r" % (iocb.ioResponse, iocb.ioError)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_object_class(object_type, vendor_id=0):
"""Return the class associated with an object type.""" |
if _debug: get_object_class._debug("get_object_class %r vendor_id=%r", object_type, vendor_id)
# find the klass as given
cls = registered_object_types.get((object_type, vendor_id))
if _debug: get_object_class._debug(" - direct lookup: %s", repr(cls))
# if the class isn't found and the vendor id is non-zero, try the standard class for the type
if (not cls) and vendor_id:
cls = registered_object_types.get((object_type, 0))
if _debug: get_object_class._debug(" - default lookup: %s", repr(cls))
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attr_to_property(self, attr):
"""Common routine to translate a python attribute name to a property name and return the appropriate property.""" |
# get the property
prop = self._properties.get(attr)
if not prop:
raise PropertyError(attr)
# found it
return prop |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_property(self, prop):
"""Add a property to an object. The property is an instance of a Property or one of its derived classes. Adding a property disconnects it from the collection of properties common to all of the objects of its class.""" |
if _debug: Object._debug("add_property %r", prop)
# make a copy of the properties dictionary
self._properties = _copy(self._properties)
# save the property reference and default value (usually None)
self._properties[prop.identifier] = prop
self._values[prop.identifier] = prop.default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_property(self, prop):
"""Delete a property from an object. The property is an instance of a Property or one of its derived classes, but only the property is relavent. Deleting a property disconnects it from the collection of properties common to all of the objects of its class.""" |
if _debug: Object._debug("delete_property %r", prop)
# make a copy of the properties dictionary
self._properties = _copy(self._properties)
# delete the property from the dictionary and values
del self._properties[prop.identifier]
if prop.identifier in self._values:
del self._values[prop.identifier] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug_contents(self, indent=1, file=sys.stdout, _ids=None):
"""Print out interesting things about the object.""" |
klasses = list(self.__class__.__mro__)
klasses.reverse()
# print special attributes "bottom up"
previous_attrs = ()
for c in klasses:
attrs = getattr(c, '_debug_contents', ())
# if we have seen this list already, move to the next class
if attrs is previous_attrs:
continue
for attr in attrs:
file.write("%s%s = %s\n" % (" " * indent, attr, getattr(self, attr)))
previous_attrs = attrs
# build a list of property identifiers "bottom up"
property_names = []
properties_seen = set()
for c in klasses:
for prop in getattr(c, 'properties', []):
if prop.identifier not in properties_seen:
property_names.append(prop.identifier)
properties_seen.add(prop.identifier)
# print out the values
for property_name in property_names:
property_value = self._values.get(property_name, None)
# printing out property values that are None is tedious
if property_value is None:
continue
if hasattr(property_value, "debug_contents"):
file.write("%s%s\n" % (" " * indent, property_name))
property_value.debug_contents(indent+1, file, _ids)
else:
file.write("%s%s = %r\n" % (" " * indent, property_name, property_value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, pdu):
"""encode the contents of the BVLCI into the PDU.""" |
if _debug: BVLCI._debug("encode %s", str(pdu))
# copy the basics
PCI.update(pdu, self)
pdu.put( self.bvlciType ) # 0x81
pdu.put( self.bvlciFunction )
if (self.bvlciLength != len(self.pduData) + 4):
raise EncodingError("invalid BVLCI length")
pdu.put_short( self.bvlciLength ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, pdu):
"""decode the contents of the PDU into the BVLCI.""" |
if _debug: BVLCI._debug("decode %s", str(pdu))
# copy the basics
PCI.update(self, pdu)
self.bvlciType = pdu.get()
if self.bvlciType != 0x81:
raise DecodingError("invalid BVLCI type")
self.bvlciFunction = pdu.get()
self.bvlciLength = pdu.get_short()
if (self.bvlciLength != len(pdu.pduData) + 4):
raise DecodingError("invalid BVLCI length") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indication(self, *args, **kwargs):
"""Downstream packet, send to current terminal.""" |
if not self.current_terminal:
raise RuntimeError("no active terminal")
if not isinstance(self.current_terminal, Server):
raise RuntimeError("current terminal not a server")
self.current_terminal.indication(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirmation(self, *args, **kwargs):
"""Upstream packet, send to current terminal.""" |
if not self.current_terminal:
raise RuntimeError("no active terminal")
if not isinstance(self.current_terminal, Client):
raise RuntimeError("current terminal not a client")
self.current_terminal.confirmation(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_ReadPropertyRequest(self, apdu):
"""Return the value of some property of one of our objects.""" |
if _debug: ReadWritePropertyServices._debug("do_ReadPropertyRequest %r", apdu)
# extract the object identifier
objId = apdu.objectIdentifier
# check for wildcard
if (objId == ('device', 4194303)) and self.localDevice is not None:
if _debug: ReadWritePropertyServices._debug(" - wildcard device identifier")
objId = self.localDevice.objectIdentifier
# get the object
obj = self.get_object_id(objId)
if _debug: ReadWritePropertyServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
try:
# get the datatype
datatype = obj.get_datatype(apdu.propertyIdentifier)
if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype)
# get the value
value = obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex)
if _debug: ReadWritePropertyServices._debug(" - value: %r", value)
if value is None:
raise PropertyError(apdu.propertyIdentifier)
# change atomic values into something encodeable
if issubclass(datatype, Atomic):
value = datatype(value)
elif issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
if apdu.propertyArrayIndex == 0:
value = Unsigned(value)
elif issubclass(datatype.subtype, Atomic):
value = datatype.subtype(value)
elif not isinstance(value, datatype.subtype):
raise TypeError("invalid result datatype, expecting %r and got %r" \
% (datatype.subtype.__name__, type(value).__name__))
elif not isinstance(value, datatype):
raise TypeError("invalid result datatype, expecting %r and got %r" \
% (datatype.__name__, type(value).__name__))
if _debug: ReadWritePropertyServices._debug(" - encodeable value: %r", value)
# this is a ReadProperty ack
resp = ReadPropertyACK(context=apdu)
resp.objectIdentifier = objId
resp.propertyIdentifier = apdu.propertyIdentifier
resp.propertyArrayIndex = apdu.propertyArrayIndex
# save the result in the property value
resp.propertyValue = Any()
resp.propertyValue.cast_in(value)
if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp)
except PropertyError:
raise ExecutionError(errorClass='property', errorCode='unknownProperty')
# return the result
self.response(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_WritePropertyRequest(self, apdu):
"""Change the value of some property of one of our objects.""" |
if _debug: ReadWritePropertyServices._debug("do_WritePropertyRequest %r", apdu)
# get the object
obj = self.get_object_id(apdu.objectIdentifier)
if _debug: ReadWritePropertyServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
try:
# check if the property exists
if obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex) is None:
raise PropertyError(apdu.propertyIdentifier)
# get the datatype, special case for null
if apdu.propertyValue.is_application_class_null():
datatype = Null
else:
datatype = obj.get_datatype(apdu.propertyIdentifier)
if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype)
# special case for array parts, others are managed by cast_out
if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
if apdu.propertyArrayIndex == 0:
value = apdu.propertyValue.cast_out(Unsigned)
else:
value = apdu.propertyValue.cast_out(datatype.subtype)
else:
value = apdu.propertyValue.cast_out(datatype)
if _debug: ReadWritePropertyServices._debug(" - value: %r", value)
# change the value
value = obj.WriteProperty(apdu.propertyIdentifier, value, apdu.propertyArrayIndex, apdu.priority)
# success
resp = SimpleAckPDU(context=apdu)
if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp)
except PropertyError:
raise ExecutionError(errorClass='property', errorCode='unknownProperty')
# return the result
self.response(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_ReadPropertyMultipleRequest(self, apdu):
"""Respond to a ReadPropertyMultiple Request.""" |
if _debug: ReadWritePropertyMultipleServices._debug("do_ReadPropertyMultipleRequest %r", apdu)
# response is a list of read access results (or an error)
resp = None
read_access_result_list = []
# loop through the request
for read_access_spec in apdu.listOfReadAccessSpecs:
# get the object identifier
objectIdentifier = read_access_spec.objectIdentifier
if _debug: ReadWritePropertyMultipleServices._debug(" - objectIdentifier: %r", objectIdentifier)
# check for wildcard
if (objectIdentifier == ('device', 4194303)) and self.localDevice is not None:
if _debug: ReadWritePropertyMultipleServices._debug(" - wildcard device identifier")
objectIdentifier = self.localDevice.objectIdentifier
# get the object
obj = self.get_object_id(objectIdentifier)
if _debug: ReadWritePropertyMultipleServices._debug(" - object: %r", obj)
# build a list of result elements
read_access_result_element_list = []
# loop through the property references
for prop_reference in read_access_spec.listOfPropertyReferences:
# get the property identifier
propertyIdentifier = prop_reference.propertyIdentifier
if _debug: ReadWritePropertyMultipleServices._debug(" - propertyIdentifier: %r", propertyIdentifier)
# get the array index (optional)
propertyArrayIndex = prop_reference.propertyArrayIndex
if _debug: ReadWritePropertyMultipleServices._debug(" - propertyArrayIndex: %r", propertyArrayIndex)
# check for special property identifiers
if propertyIdentifier in ('all', 'required', 'optional'):
if not obj:
# build a property access error
read_result = ReadAccessResultElementChoice()
read_result.propertyAccessError = ErrorType(errorClass='object', errorCode='unknownObject')
# make an element for this error
read_access_result_element = ReadAccessResultElement(
propertyIdentifier=propertyIdentifier,
propertyArrayIndex=propertyArrayIndex,
readResult=read_result,
)
# add it to the list
read_access_result_element_list.append(read_access_result_element)
else:
for propId, prop in obj._properties.items():
if _debug: ReadWritePropertyMultipleServices._debug(" - checking: %r %r", propId, prop.optional)
if (propertyIdentifier == 'all'):
pass
elif (propertyIdentifier == 'required') and (prop.optional):
if _debug: ReadWritePropertyMultipleServices._debug(" - not a required property")
continue
elif (propertyIdentifier == 'optional') and (not prop.optional):
if _debug: ReadWritePropertyMultipleServices._debug(" - not an optional property")
continue
# read the specific property
read_access_result_element = read_property_to_result_element(obj, propId, propertyArrayIndex)
# check for undefined property
if read_access_result_element.readResult.propertyAccessError \
and read_access_result_element.readResult.propertyAccessError.errorCode == 'unknownProperty':
continue
# add it to the list
read_access_result_element_list.append(read_access_result_element)
else:
# read the specific property
read_access_result_element = read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex)
# add it to the list
read_access_result_element_list.append(read_access_result_element)
# build a read access result
read_access_result = ReadAccessResult(
objectIdentifier=objectIdentifier,
listOfResults=read_access_result_element_list
)
if _debug: ReadWritePropertyMultipleServices._debug(" - read_access_result: %r", read_access_result)
# add it to the list
read_access_result_list.append(read_access_result)
# this is a ReadPropertyMultiple ack
if not resp:
resp = ReadPropertyMultipleACK(context=apdu)
resp.listOfReadAccessResults = read_access_result_list
if _debug: ReadWritePropertyMultipleServices._debug(" - resp: %r", resp)
# return the result
self.response(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_write(self):
"""get a PDU from the queue and send it.""" |
if _debug: UDPDirector._debug("handle_write")
try:
pdu = self.request.get()
sent = self.socket.sendto(pdu.pduData, pdu.pduDestination)
if _debug: UDPDirector._debug(" - sent %d octets to %s", sent, pdu.pduDestination)
except socket.error, err:
if _debug: UDPDirector._debug(" - socket error: %s", err)
# get the peer
peer = self.peers.get(pdu.pduDestination, None)
if peer:
# let the actor handle the error
peer.handle_error(err)
else:
# let the director handle the error
self.handle_error(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indication(self, pdu):
"""Client requests are queued for delivery.""" |
if _debug: UDPDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the peer
peer = self.peers.get(addr, None)
if not peer:
peer = self.actorClass(self, addr)
# send the message
peer.indication(pdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _response(self, pdu):
"""Incoming datagrams are routed through an actor.""" |
if _debug: UDPDirector._debug("_response %r", pdu)
# get the destination
addr = pdu.pduSource
# get the peer
peer = self.peers.get(addr, None)
if not peer:
peer = self.actorClass(self, addr)
# send the message
peer.response(pdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscriptions(self):
"""Generator for the active subscriptions.""" |
if _debug: ChangeOfValueServices._debug("subscriptions")
subscription_list = []
# loop through the object and detection list
for obj, cov_detection in self.cov_detections.items():
for cov in cov_detection.cov_subscriptions:
subscription_list.append(cov)
return subscription_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(*args):
"""bind a list of clients and servers together, top down.""" |
if _debug: bind._debug("bind %r", args)
# generic bind is pairs of names
if not args:
# find unbound clients and bind them
for cid, client in client_map.items():
# skip those that are already bound
if client.clientPeer:
continue
if not cid in server_map:
raise RuntimeError("unmatched server {!r}".format(cid))
server = server_map[cid]
if server.serverPeer:
raise RuntimeError("server already bound %r".format(cid))
bind(client, server)
# see if there are any unbound servers
for sid, server in server_map.items():
if server.serverPeer:
continue
if not sid in client_map:
raise RuntimeError("unmatched client {!r}".format(sid))
else:
raise RuntimeError("mistery unbound server {!r}".format(sid))
# find unbound application service elements and bind them
for eid, element in element_map.items():
# skip those that are already bound
if element.elementService:
continue
if not eid in service_map:
raise RuntimeError("unmatched element {!r}".format(cid))
service = service_map[eid]
if server.serverPeer:
raise RuntimeError("service already bound {!r}".format(cid))
bind(element, service)
# see if there are any unbound services
for sid, service in service_map.items():
if service.serviceElement:
continue
if not sid in element_map:
raise RuntimeError("unmatched service {!r}".format(sid))
else:
raise RuntimeError("mistery unbound service {!r}".format(sid))
# go through the argument pairs
for i in xrange(len(args)-1):
client = args[i]
if _debug: bind._debug(" - client: %r", client)
server = args[i+1]
if _debug: bind._debug(" - server: %r", server)
# make sure we're binding clients and servers
if isinstance(client, Client) and isinstance(server, Server):
client.clientPeer = server
server.serverPeer = client
# we could be binding application clients and servers
elif isinstance(client, ApplicationServiceElement) and isinstance(server, ServiceAccessPoint):
client.elementService = server
server.serviceElement = client
# error
else:
raise TypeError("bind() requires a client and server")
if _debug: bind._debug(" - bound") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, pdu):
"""encode the contents of the NPCI into the PDU.""" |
if _debug: NPCI._debug("encode %s", repr(pdu))
PCI.update(pdu, self)
# only version 1 messages supported
pdu.put(self.npduVersion)
# build the flags
if self.npduNetMessage is not None:
netLayerMessage = 0x80
else:
netLayerMessage = 0x00
# map the destination address
dnetPresent = 0x00
if self.npduDADR is not None:
dnetPresent = 0x20
# map the source address
snetPresent = 0x00
if self.npduSADR is not None:
snetPresent = 0x08
# encode the control octet
control = netLayerMessage | dnetPresent | snetPresent
if self.pduExpectingReply:
control |= 0x04
control |= (self.pduNetworkPriority & 0x03)
self.npduControl = control
pdu.put(control)
# make sure expecting reply and priority get passed down
pdu.pduExpectingReply = self.pduExpectingReply
pdu.pduNetworkPriority = self.pduNetworkPriority
# encode the destination address
if dnetPresent:
if self.npduDADR.addrType == Address.remoteStationAddr:
pdu.put_short(self.npduDADR.addrNet)
pdu.put(self.npduDADR.addrLen)
pdu.put_data(self.npduDADR.addrAddr)
elif self.npduDADR.addrType == Address.remoteBroadcastAddr:
pdu.put_short(self.npduDADR.addrNet)
pdu.put(0)
elif self.npduDADR.addrType == Address.globalBroadcastAddr:
pdu.put_short(0xFFFF)
pdu.put(0)
# encode the source address
if snetPresent:
pdu.put_short(self.npduSADR.addrNet)
pdu.put(self.npduSADR.addrLen)
pdu.put_data(self.npduSADR.addrAddr)
# put the hop count
if dnetPresent:
pdu.put(self.npduHopCount)
# put the network layer message type (if present)
if netLayerMessage:
pdu.put(self.npduNetMessage)
# put the vendor ID
if (self.npduNetMessage >= 0x80) and (self.npduNetMessage <= 0xFF):
pdu.put_short(self.npduVendorID) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, pdu):
"""decode the contents of the PDU and put them into the NPDU.""" |
if _debug: NPCI._debug("decode %s", str(pdu))
PCI.update(self, pdu)
# check the length
if len(pdu.pduData) < 2:
raise DecodingError("invalid length")
# only version 1 messages supported
self.npduVersion = pdu.get()
if (self.npduVersion != 0x01):
raise DecodingError("only version 1 messages supported")
# decode the control octet
self.npduControl = control = pdu.get()
netLayerMessage = control & 0x80
dnetPresent = control & 0x20
snetPresent = control & 0x08
self.pduExpectingReply = (control & 0x04) != 0
self.pduNetworkPriority = control & 0x03
# extract the destination address
if dnetPresent:
dnet = pdu.get_short()
dlen = pdu.get()
dadr = pdu.get_data(dlen)
if dnet == 0xFFFF:
self.npduDADR = GlobalBroadcast()
elif dlen == 0:
self.npduDADR = RemoteBroadcast(dnet)
else:
self.npduDADR = RemoteStation(dnet, dadr)
# extract the source address
if snetPresent:
snet = pdu.get_short()
slen = pdu.get()
sadr = pdu.get_data(slen)
if snet == 0xFFFF:
raise DecodingError("SADR can't be a global broadcast")
elif slen == 0:
raise DecodingError("SADR can't be a remote broadcast")
self.npduSADR = RemoteStation(snet, sadr)
# extract the hop count
if dnetPresent:
self.npduHopCount = pdu.get()
# extract the network layer message type (if present)
if netLayerMessage:
self.npduNetMessage = pdu.get()
if (self.npduNetMessage >= 0x80) and (self.npduNetMessage <= 0xFF):
# extract the vendor ID
self.npduVendorID = pdu.get_short()
else:
# application layer message
self.npduNetMessage = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_actor(self, actor):
"""Remove an actor when the socket is closed.""" |
if _debug: TCPClientDirector._debug("del_actor %r", actor)
del self.clients[actor.peer]
# tell the ASE the client has gone away
if self.serviceElement:
self.sap_request(del_actor=actor)
# see if it should be reconnected
if actor.peer in self.reconnect:
connect_task = FunctionTask(self.connect, actor.peer)
connect_task.install_task(_time() + self.reconnect[actor.peer]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indication(self, pdu):
"""Direct this PDU to the appropriate server, create a connection if one hasn't already been created.""" |
if _debug: TCPClientDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the client
client = self.clients.get(addr, None)
if not client:
client = self.actorClass(self, addr)
# send the message
client.indication(pdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indication(self, pdu):
"""Direct this PDU to the appropriate server.""" |
if _debug: TCPServerDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the server
server = self.servers.get(addr, None)
if not server:
raise RuntimeError("not a connected server")
# pass the indication to the actor
server.indication(pdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indication(self, pdu):
"""Message going downstream.""" |
if _debug: StreamToPacket._debug("indication %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.downstreamBuffer):
self.request(packet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirmation(self, pdu):
"""Message going upstream.""" |
if _debug: StreamToPacket._debug("StreamToPacket.confirmation %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.upstreamBuffer):
self.response(packet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_callback(self, fn, *args, **kwargs):
"""Pass a function to be called when IO is complete.""" |
if _debug: IOCB._debug("add_callback(%d) %r %r %r", self.ioID, fn, args, kwargs)
# store it
self.ioCallback.append((fn, args, kwargs))
# already complete?
if self.ioComplete.isSet():
self.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(self, *args, **kwargs):
"""Wait for the completion event to be set.""" |
if _debug: IOCB._debug("wait(%d) %r %r", self.ioID, args, kwargs)
# waiting from a non-daemon thread could be trouble
return self.ioComplete.wait(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete(self, msg):
"""Called to complete a transaction, usually when ProcessIO has shipped the IOCB off to some other thread or function.""" |
if _debug: IOCB._debug("complete(%d) %r", self.ioID, msg)
if self.ioController:
# pass to controller
self.ioController.complete_io(self, msg)
else:
# just fill in the data
self.ioState = COMPLETED
self.ioResponse = msg
self.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self, err):
"""Called by a client to abort a transaction.""" |
if _debug: IOCB._debug("abort(%d) %r", self.ioID, err)
if self.ioController:
# pass to controller
self.ioController.abort_io(self, err)
elif self.ioState < COMPLETED:
# just fill in the data
self.ioState = ABORTED
self.ioError = err
self.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_timeout(self, delay, err=TimeoutError):
"""Called to set a transaction timer.""" |
if _debug: IOCB._debug("set_timeout(%d) %r err=%r", self.ioID, delay, err)
# if one has already been created, cancel it
if self.ioTimeout:
self.ioTimeout.suspend_task()
else:
self.ioTimeout = FunctionTask(self.abort, err)
# (re)schedule it
self.ioTimeout.install_task(delay=delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chain_callback(self, iocb):
"""Callback when this iocb completes.""" |
if _debug: IOChainMixIn._debug("chain_callback %r", iocb)
# if we're not chained, there's no notification to do
if not self.ioChain:
return
# refer to the chained iocb
iocb = self.ioChain
try:
if _debug: IOChainMixIn._debug(" - decoding")
# let the derived class transform the data
self.decode()
if _debug: IOChainMixIn._debug(" - decode complete")
except:
# extract the error and abort
err = sys.exc_info()[1]
if _debug: IOChainMixIn._exception(" - decoding exception: %r", err)
iocb.ioState = ABORTED
iocb.ioError = err
# break the references
self.ioChain = None
iocb.ioController = None
# notify the client
iocb.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort_io(self, iocb, err):
"""Forward the abort downstream.""" |
if _debug: IOChainMixIn._debug("abort_io %r %r", iocb, err)
# make sure we're being notified of an abort request from
# the iocb we are chained from
if iocb is not self.ioChain:
raise RuntimeError("broken chain")
# call my own Abort(), which may forward it to a controller or
# be overridden by IOGroup
self.abort(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self):
"""Hook to transform the response, called when this IOCB is completed.""" |
if _debug: IOChainMixIn._debug("decode")
# refer to the chained iocb
iocb = self.ioChain
# if this has completed successfully, pass it up
if self.ioState == COMPLETED:
if _debug: IOChainMixIn._debug(" - completed: %r", self.ioResponse)
# change the state and transform the content
iocb.ioState = COMPLETED
iocb.ioResponse = self.ioResponse
# if this aborted, pass that up too
elif self.ioState == ABORTED:
if _debug: IOChainMixIn._debug(" - aborted: %r", self.ioError)
# change the state
iocb.ioState = ABORTED
iocb.ioError = self.ioError
else:
raise RuntimeError("invalid state: %d" % (self.ioState,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups.""" |
if _debug: IOGroup._debug("add %r", iocb)
# add this to our members
self.ioMembers.append(iocb)
# assume all of our members have not completed yet
self.ioState = PENDING
self.ioComplete.clear()
# when this completes, call back to the group. If this
# has already completed, it will trigger
iocb.add_callback(self.group_callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_callback(self, iocb):
"""Callback when a child iocb completes.""" |
if _debug: IOGroup._debug("group_callback %r", iocb)
# check all the members
for iocb in self.ioMembers:
if not iocb.ioComplete.isSet():
if _debug: IOGroup._debug(" - waiting for child: %r", iocb)
break
else:
if _debug: IOGroup._debug(" - all children complete")
# everything complete
self.ioState = COMPLETED
self.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self, err):
"""Called by a client to abort all of the member transactions. When the last pending member is aborted the group callback function will be called.""" |
if _debug: IOGroup._debug("abort %r", err)
# change the state to reflect that it was killed
self.ioState = ABORTED
self.ioError = err
# abort all the members
for iocb in self.ioMembers:
iocb.abort(err)
# notify the client
self.trigger() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, iocb):
"""Add an IOCB to a queue. This is usually called by the function that filters requests and passes them out to the correct processing thread.""" |
if _debug: IOQueue._debug("put %r", iocb)
# requests should be pending before being queued
if iocb.ioState != PENDING:
raise RuntimeError("invalid state transition")
# save that it might have been empty
wasempty = not self.notempty.isSet()
# add the request to the end of the list of iocb's at same priority
priority = iocb.ioPriority
item = (priority, iocb)
self.queue.insert(bisect_left(self.queue, (priority+1,)), item)
# point the iocb back to this queue
iocb.ioQueue = self
# set the event, queue is no longer empty
self.notempty.set()
return wasempty |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request is available.""" |
if _debug: IOQueue._debug("get block=%r delay=%r", block, delay)
# if the queue is empty and we do not block return None
if not block and not self.notempty.isSet():
if _debug: IOQueue._debug(" - not blocking and empty")
return None
# wait for something to be in the queue
if delay:
self.notempty.wait(delay)
if not self.notempty.isSet():
return None
else:
self.notempty.wait()
# extract the first element
priority, iocb = self.queue[0]
del self.queue[0]
iocb.ioQueue = None
# if the queue is empty, clear the event
qlen = len(self.queue)
if not qlen:
self.notempty.clear()
# return the request
return iocb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self, err):
"""Abort all of the control blocks in the queue.""" |
if _debug: IOQueue._debug("abort %r", err)
# send aborts to all of the members
try:
for iocb in self.queue:
iocb.ioQueue = None
iocb.abort(err)
# flush the queue
self.queue = []
# the queue is now empty, clear the event
self.notempty.clear()
except ValueError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self, err):
"""Abort all pending requests.""" |
if _debug: IOQController._debug("abort %r", err)
if (self.state == CTRL_IDLE):
if _debug: IOQController._debug(" - idle")
return
while True:
iocb = self.ioQueue.get(block=0)
if not iocb:
break
if _debug: IOQController._debug(" - iocb: %r", iocb)
# change the state
iocb.ioState = ABORTED
iocb.ioError = err
# notify the client
iocb.trigger()
if (self.state != CTRL_IDLE):
if _debug: IOQController._debug(" - busy after aborts") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, addr):
"""Initiate a connection request to the peer router.""" |
if _debug: RouterToRouterService._debug("connect %r", addr)
# make a connection
conn = ConnectionState(addr)
self.multiplexer.connections[addr] = conn
# associate with this service, but it is not connected until the ack comes back
conn.service = self
# keep a list of pending NPDU objects until the ack comes back
conn.pendingNPDU = []
# build a service request
request = ServiceRequest(ROUTER_TO_ROUTER_SERVICE_ID)
request.pduDestination = addr
# send it
self.service_request(request)
# return the connection object
return conn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_npdu(self, npdu):
"""encode NPDUs from the network service access point and send them to the proxy.""" |
if _debug: ProxyServiceNetworkAdapter._debug("process_npdu %r", npdu)
# encode the npdu as if it was about to be delivered to the network
pdu = PDU()
npdu.encode(pdu)
if _debug: ProxyServiceNetworkAdapter._debug(" - pdu: %r", pdu)
# broadcast messages go to peers
if pdu.pduDestination.addrType == Address.localBroadcastAddr:
xpdu = ServerToProxyBroadcastNPDU(pdu)
else:
xpdu = ServerToProxyUnicastNPDU(pdu.pduDestination, pdu)
# the connection has the correct address
xpdu.pduDestination = self.conn.address
# send it down to the multiplexer
self.conn.service.service_request(xpdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_confirmation(self, bslpdu):
"""Receive packets forwarded by the proxy and send them upstream to the network service access point.""" |
if _debug: ProxyServiceNetworkAdapter._debug("service_confirmation %r", bslpdu)
# build a PDU
pdu = NPDU(bslpdu.pduData)
# the source is from the original source, not the proxy itself
pdu.pduSource = bslpdu.bslciAddress
# if the proxy received a broadcast, send it upstream as a broadcast
if isinstance(bslpdu, ProxyToServerBroadcastNPDU):
pdu.pduDestination = LocalBroadcast()
if _debug: ProxyServiceNetworkAdapter._debug(" - pdu: %r", pdu)
# decode it, the nework layer needs NPDUs
npdu = NPDU()
npdu.decode(pdu)
if _debug: ProxyServiceNetworkAdapter._debug(" - npdu: %r", npdu)
# send it to the service access point for processing
self.adapterSAP.process_npdu(self, npdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_confirmation(self, conn, bslpdu):
"""Receive packets forwarded by the proxy and redirect them to the proxy network adapter.""" |
if _debug: ProxyServerService._debug("service_confirmation %r %r", conn, bslpdu)
# make sure there is an adapter for it - or something went wrong
if not getattr(conn, 'proxyAdapter', None):
raise RuntimeError("service confirmation received but no adapter for it")
# forward along
conn.proxyAdapter.service_confirmation(bslpdu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_spell_damage(self, amount: int) -> int: """ Returns the amount of damage \a amount will do, taking SPELLPOWER and SPELLPOWER_DOUBLE into account. """ |
amount += self.spellpower
amount <<= self.controller.spellpower_double
return amount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_pay_cost(self, card):
""" Returns whether the player can pay the resource cost of a card. """ |
if self.spells_cost_health and card.type == CardType.SPELL:
return self.hero.health > card.cost
return self.mana >= card.cost |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pay_cost(self, source, amount: int) -> int: """ Make player pay \a amount mana. Returns how much mana is spent, after temporary mana adjustments. """ |
if self.spells_cost_health and source.type == CardType.SPELL:
self.log("%s spells cost %i health", self, amount)
self.game.queue_actions(self, [Hit(self.hero, amount)])
return amount
if self.temp_mana:
# Coin, Innervate etc
used_temp = min(self.temp_mana, amount)
amount -= used_temp
self.temp_mana -= used_temp
self.log("%s pays %i mana", self, amount)
self.used_mana += amount
return amount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summon(self, card):
""" Puts \a card in the PLAY zone """ |
if isinstance(card, str):
card = self.card(card, zone=Zone.PLAY)
self.game.cheat_action(self, [Summon(self, card)])
return card |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_damage(self, amount: int, target) -> int: """ Override to modify the damage dealt to a target from the given amount. """ |
if target.immune:
self.log("%r is immune to %s for %i damage", target, self, amount)
return 0
return amount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def then(self, *args):
""" Create a callback containing an action queue, called upon the action's trigger with the action's arguments available. """ |
ret = self.__class__(*self._args, **self._kwargs)
ret.callback = args
ret.times = self.times
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_draft(card_class: CardClass, exclude=[]):
""" Return a deck of 30 random cards for the \a card_class """ |
from . import cards
from .deck import Deck
deck = []
collection = []
# hero = card_class.default_hero
for card in cards.db.keys():
if card in exclude:
continue
cls = cards.db[card]
if not cls.collectible:
continue
if cls.type == CardType.HERO:
# Heroes are collectible...
continue
if cls.card_class and cls.card_class not in [card_class, CardClass.NEUTRAL]:
# Play with more possibilities
continue
collection.append(cls)
while len(deck) < Deck.MAX_CARDS:
card = random.choice(collection)
if deck.count(card.id) < card.max_count_in_deck:
deck.append(card.id)
return deck |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_script_definition(id):
""" Find and return the script definition for card \a id """ |
for cardset in CARD_SETS:
module = import_module("fireplace.cards.%s" % (cardset))
if hasattr(module, id):
return getattr(module, id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_for_end_game(self):
""" Check if one or more player is currently losing. End the game if they are. """ |
gameover = False
for player in self.players:
if player.playstate in (PlayState.CONCEDED, PlayState.DISCONNECTED):
player.playstate = PlayState.LOSING
if player.playstate == PlayState.LOSING:
gameover = True
if gameover:
if self.players[0].playstate == self.players[1].playstate:
for player in self.players:
player.playstate = PlayState.TIED
else:
for player in self.players:
if player.playstate == PlayState.LOSING:
player.playstate = PlayState.LOST
else:
player.playstate = PlayState.WON
self.state = State.COMPLETE
self.manager.step(self.next_step, Step.FINAL_WRAPUP)
self.manager.step(self.next_step, Step.FINAL_GAMEOVER)
self.manager.step(self.next_step) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue_actions(self, source, actions, event_args=None):
""" Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards. """ |
source.event_args = event_args
ret = self.trigger_actions(source, actions)
source.event_args = None
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger_actions(self, source, actions):
""" Performs a list of `actions` from `source`. This should seldom be called directly - use `queue_actions` instead. """ |
ret = []
for action in actions:
if isinstance(action, EventListener):
# Queuing an EventListener registers it as a one-time event
# This allows registering events from eg. play actions
self.log("Registering event listener %r on %r", action, self)
action.once = True
# FIXME: Figure out a cleaner way to get the event listener target
if source.type == CardType.SPELL:
listener = source.controller
else:
listener = source
listener._events.append(action)
else:
ret.append(action.trigger(source))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, source):
""" Evaluates the board state from `source` and returns an iterable of Actions as a result. """ |
ret = self.check(source)
if self._neg:
ret = not ret
if ret:
if self._if:
return self._if
elif self._else:
return self._else |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self, source):
""" Triggers all actions meant to trigger on the board state from `source`. """ |
actions = self.evaluate(source)
if actions:
if not hasattr(actions, "__iter__"):
actions = (actions, )
source.game.trigger_actions(source, actions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, source, entity):
""" Return a copy of \a entity """ |
log.info("Creating a copy of %r", entity)
return source.controller.card(entity.id, source) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_cards(self, source=None, **filters):
""" Generate a card pool with all cards matching specified filters """ |
if not filters:
new_filters = self.filters.copy()
else:
new_filters = filters.copy()
for k, v in new_filters.items():
if isinstance(v, LazyValue):
new_filters[k] = v.evaluate(source)
from .. import cards
return cards.filter(**new_filters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, source, cards=None) -> str: """ This picks from a single combined card pool without replacement, weighting each filtered set of cards against the total """ |
from ..utils import weighted_card_choice
if cards:
# Use specific card list if given
self.weights = [1]
card_sets = [list(cards)]
elif not self.weightedfilters:
# Use global filters if no weighted filter sets given
self.weights = [1]
card_sets = [self.find_cards(source)]
else:
# Otherwise find cards for each set of filters
# add the global filters to each set of filters
wf = [{**x, **self.filters} for x in self.weightedfilters]
card_sets = [self.find_cards(source, **x) for x in wf]
# get weighted sample of card pools
return weighted_card_choice(source, self.weights, card_sets, self.count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def powered_up(self):
""" Returns True whether the card is "powered up". """ |
if not self.data.scripts.powered_up:
return False
for script in self.data.scripts.powered_up:
if not script.check(self):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def play(self, target=None, index=None, choose=None):
""" Queue a Play action on the card. """ |
if choose:
if self.must_choose_one:
choose = card = self.choose_cards.filter(id=choose)[0]
self.log("%r: choosing %r", self, choose)
else:
raise InvalidAction("%r cannot be played with choice %r" % (self, choose))
else:
if self.must_choose_one:
raise InvalidAction("%r requires a choice (one of %r)" % (self, self.choose_cards))
card = self
if not self.is_playable():
raise InvalidAction("%r isn't playable." % (self))
if card.requires_target():
if not target:
raise InvalidAction("%r requires a target to play." % (self))
elif target not in self.play_targets:
raise InvalidAction("%r is not a valid target for %r." % (target, self))
elif target:
self.logger.warning("%r does not require a target, ignoring target %r", self, target)
self.game.play_card(self, target, index, choose)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def morph(self, into):
""" Morph the card into another card """ |
return self.game.cheat_action(self, [actions.Morph(self, into)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shuffle_into_deck(self):
""" Shuffle the card into the controller's deck """ |
return self.game.cheat_action(self, [actions.Shuffle(self.controller, self)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def battlecry_requires_target(self):
""" True if the play action of the card requires a target """ |
if self.has_combo and self.controller.combo:
if PlayReq.REQ_TARGET_FOR_COMBO in self.requirements:
return True
for req in TARGETING_PREREQUISITES:
if req in self.requirements:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requires_target(self):
""" True if the card currently requires a target """ |
if self.has_combo and PlayReq.REQ_TARGET_FOR_COMBO in self.requirements:
if self.controller.combo:
return True
if PlayReq.REQ_TARGET_IF_AVAILABLE in self.requirements:
return bool(self.play_targets)
if PlayReq.REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND in self.requirements:
if self.controller.hand.filter(race=Race.DRAGON):
return bool(self.play_targets)
req = self.requirements.get(PlayReq.REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS)
if req is not None:
if len(self.controller.field) >= req:
return bool(self.play_targets)
req = self.requirements.get(PlayReq.REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS)
if req is not None:
if len(self.controller.secrets) >= req:
return bool(self.play_targets)
return PlayReq.REQ_TARGET_TO_PLAY in self.requirements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(id, card, cardscript=None):
""" Find the xmlcard and the card definition of \a id Then return a merged class of the two """ |
if card is None:
card = cardxml.CardXML(id)
if cardscript is None:
cardscript = get_script_definition(id)
if cardscript:
card.scripts = type(id, (cardscript, ), {})
else:
card.scripts = type(id, (), {})
scriptnames = (
"activate", "combo", "deathrattle", "draw", "inspire", "play",
"enrage", "update", "powered_up"
)
for script in scriptnames:
actions = getattr(card.scripts, script, None)
if actions is None:
# Set the action by default to avoid runtime hasattr() calls
setattr(card.scripts, script, [])
elif not callable(actions):
if not hasattr(actions, "__iter__"):
# Ensure the actions are always iterable
setattr(card.scripts, script, (actions, ))
for script in ("events", "secret"):
events = getattr(card.scripts, script, None)
if events is None:
setattr(card.scripts, script, [])
elif not hasattr(events, "__iter__"):
setattr(card.scripts, script, [events])
if not hasattr(card.scripts, "cost_mod"):
card.scripts.cost_mod = None
if not hasattr(card.scripts, "Hand"):
card.scripts.Hand = type("Hand", (), {})
if not hasattr(card.scripts.Hand, "events"):
card.scripts.Hand.events = []
if not hasattr(card.scripts.Hand.events, "__iter__"):
card.scripts.Hand.events = [card.scripts.Hand.events]
if not hasattr(card.scripts.Hand, "update"):
card.scripts.Hand.update = ()
if not hasattr(card.scripts.Hand.update, "__iter__"):
card.scripts.Hand.update = (card.scripts.Hand.update, )
# Set choose one cards
if hasattr(cardscript, "choose"):
card.choose_cards = cardscript.choose[:]
else:
card.choose_cards = []
if hasattr(cardscript, "tags"):
for tag, value in cardscript.tags.items():
card.tags[tag] = value
# Set some additional events based on the base tags...
if card.poisonous:
card.scripts.events.append(POISONOUS)
return card |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_css(css_url=None, version='5.2.0'):
"""Load Dropzone's css resources with given version. .. versionadded:: 1.4.4 :param css_url: The CSS url for Dropzone.js. :param version: The version of Dropzone.js. """ |
css_filename = 'dropzone.min.css'
serve_local = current_app.config['DROPZONE_SERVE_LOCAL']
if serve_local:
css = '<link rel="stylesheet" href="%s" type="text/css">\n' % \
url_for('dropzone.static', filename=css_filename)
else:
css = '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone@%s/dist/min/%s"' \
' type="text/css">\n' % (version, css_filename)
if css_url:
css = '<link rel="stylesheet" href="%s" type="text/css">\n' % css_url
return Markup(css) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_js(js_url=None, version='5.2.0'):
"""Load Dropzone's js resources with given version. .. versionadded:: 1.4.4 :param js_url: The JS url for Dropzone.js. :param version: The version of Dropzone.js. """ |
js_filename = 'dropzone.min.js'
serve_local = current_app.config['DROPZONE_SERVE_LOCAL']
if serve_local:
js = '<script src="%s"></script>\n' % url_for('dropzone.static', filename=js_filename)
else:
js = '<script src="https://cdn.jsdelivr.net/npm/dropzone@%s/dist/%s"></script>\n' % (version, js_filename)
if js_url:
js = '<script src="%s"></script>\n' % js_url
return Markup(js) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" This example demonstrates how to generate pretty equations from the analytic expressions found in ``chempy.kinetics.integrated``. """ |
t, kf, t0, major, minor, prod, beta = sympy.symbols(
't k_f t0 Y Z X beta', negative=False)
for f in funcs:
args = [t, kf, prod, major, minor]
if f in (pseudo_rev, binary_rev):
args.insert(2, kf/beta)
expr = f(*args, backend='sympy')
with open(f.__name__ + '.png', 'wb') as ofh:
sympy.printing.preview(expr, output='png', filename='out.png',
viewer='BytesIO', outputbuffer=ofh)
with open(f.__name__ + '_diff.png', 'wb') as ofh:
sympy.printing.preview(expr.diff(t).subs({t0: 0}).simplify(),
output='png', filename='out.png',
viewer='BytesIO', outputbuffer=ofh) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dissolved(self, concs):
""" Return dissolved concentrations """ |
new_concs = concs.copy()
for r in self.rxns:
if r.has_precipitates(self.substances):
net_stoich = np.asarray(r.net_stoich(self.substances))
s_net, s_stoich, s_idx = r.precipitate_stoich(self.substances)
new_concs -= new_concs[s_idx]/s_stoich * net_stoich
return new_concs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lg_solubility_ratio(electrolytes, gas, units=None, warn=True):
""" Returns the log10 value of the solubilty ratio Implements equation 16, p 156. from Schumpe (1993) Parameters electrolytes : dict Mapping substance key (one in ``p_ion_rM``) to concentration. gas : str Substance key for the gas (one in ``p_gas_rM``). units : object (optional) object with attribute: molar warn : bool (default: True) Emit UserWarning when 'F-' among electrolytes. """ |
if units is None:
M = 1
else:
M = units.molar
if warn and 'F-' in electrolytes:
warnings.warn("In Schumpe 1993: data for fluoride uncertain.")
return sum([(p_gas_rM[gas]/M+p_ion_rM[k]/M)*v for k, v in electrolytes.items()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Henry_H_at_T(T, H, Tderiv, T0=None, units=None, backend=None):
""" Evaluate Henry's constant H at temperature T Parameters T: float Temperature (with units), assumed to be in Kelvin if ``units == None`` H: float Henry's constant Tderiv: float (optional) dln(H)/d(1/T), assumed to be in Kelvin if ``units == None``. T0: float Reference temperature, assumed to be in Kelvin if ``units == None`` default: 298.15 K units: object (optional) object with attributes: kelvin (e.g. chempy.units.default_units) backend : module (optional) module with "exp", default: numpy, math """ |
be = get_backend(backend)
if units is None:
K = 1
else:
K = units.Kelvin
if T0 is None:
T0 = 298.15*K
return H * be.exp(Tderiv*(1/T - 1/T0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mass_from_composition(composition):
""" Calculates molecular mass from atomic weights Parameters composition: dict Dictionary mapping int (atomic number) to int (coefficient) Returns ------- float molecular weight in atomic mass units Notes ----- Atomic number 0 denotes charge or "net electron defficiency" Examples -------- '17.01' """ |
mass = 0.0
for k, v in composition.items():
if k == 0: # electron
mass -= v*5.489e-4
else:
mass += v*relative_atomic_masses[k-1]
return mass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def water_self_diffusion_coefficient(T=None, units=None, warn=True, err_mult=None):
""" Temperature-dependent self-diffusion coefficient of water. Parameters T : float Temperature (default: in Kelvin) units : object (optional) object with attributes: Kelvin, meter, kilogram warn : bool (default: True) Emit UserWarning when outside temperature range. err_mult : length 2 array_like (default: None) Perturb paramaters D0 and TS with err_mult[0]*dD0 and err_mult[1]*dTS respectively, where dD0 and dTS are the reported uncertainties in the fitted paramters. Useful for estimating error in diffusion coefficient. References Temperature-dependent self-diffusion coefficients of water and six selected molecular liquids for calibration in accurate 1H NMR PFG measurements Manfred Holz, Stefan R. Heila, Antonio Saccob; Phys. Chem. Chem. Phys., 2000,2, 4740-4742 http://pubs.rsc.org/en/Content/ArticleLanding/2000/CP/b005319h DOI: 10.1039/B005319H """ |
if units is None:
K = 1
m = 1
s = 1
else:
K = units.Kelvin
m = units.meter
s = units.second
if T is None:
T = 298.15*K
_D0 = D0 * m**2 * s**-1
_TS = TS * K
if err_mult is not None:
_dD0 = dD0 * m**2 * s**-1
_dTS = dTS * K
_D0 += err_mult[0]*_dD0
_TS += err_mult[1]*_dTS
if warn and (_any(T < low_t_bound*K) or _any(T > high_t_bound*K)):
warnings.warn("Temperature is outside range (0-100 degC)")
return _D0*((T/_TS) - 1)**gamma |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rsys2graph(rsys, fname, output_dir=None, prog=None, save=False, **kwargs):
""" Convenience function to call `rsys2dot` and write output to file and render the graph Parameters rsys : ReactionSystem fname : str filename output_dir : str (optional) path to directory (default: temporary directory) prog : str (optional) default: 'dot' save : bool removes temporary directory if False, default: False \\*\\*kwargs : Keyword arguments passed along to py:func:`rsys2dot`. Returns ------- str Outpath Examples -------- """ |
lines = rsys2dot(rsys, **kwargs)
created_tempdir = False
try:
if output_dir is None:
output_dir = tempfile.mkdtemp()
created_tempdir = True
basename, ext = os.path.splitext(os.path.basename(fname))
outpath = os.path.join(output_dir, fname)
dotpath = os.path.join(output_dir, basename + '.dot')
with open(dotpath, 'wt') as ofh:
ofh.writelines(lines)
if ext == '.tex':
cmds = [prog or 'dot2tex']
else:
cmds = [prog or 'dot', '-T'+outpath.split('.')[-1]]
p = subprocess.Popen(cmds + [dotpath, '-o', outpath])
retcode = p.wait()
if retcode:
fmtstr = "{}\n returned with exit status {}"
raise RuntimeError(fmtstr.format(' '.join(cmds), retcode))
return outpath
finally:
if save is True or save == 'True':
pass
else:
if save is False or save == 'False':
if created_tempdir:
shutil.rmtree(output_dir)
else:
# interpret save as path to copy pdf to.
shutil.copy(outpath, save) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_permission_safety(path):
"""Check if the file at the given path is safe to use as a state file. This checks that group and others have no permissions on the file and that the current user is the owner. """ |
f_stats = os.stat(path)
return (f_stats.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) == 0 and f_stats.st_uid == os.getuid() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_private_key(key_path, password_path=None):
"""Open a JSON-encoded private key and return it If a password file is provided, uses it to decrypt the key. If not, the password is asked interactively. Raw hex-encoded private keys are supported, but deprecated.""" |
assert key_path, key_path
if not os.path.exists(key_path):
log.fatal('%s: no such file', key_path)
return None
if not check_permission_safety(key_path):
log.fatal('Private key file %s must be readable only by its owner.', key_path)
return None
if password_path and not check_permission_safety(password_path):
log.fatal('Password file %s must be readable only by its owner.', password_path)
return None
with open(key_path) as keyfile:
private_key = keyfile.readline().strip()
if is_hex(private_key) and len(decode_hex(private_key)) == 32:
log.warning('Private key in raw format. Consider switching to JSON-encoded')
else:
keyfile.seek(0)
try:
json_data = json.load(keyfile)
if password_path:
with open(password_path) as password_file:
password = password_file.readline().strip()
else:
password = getpass.getpass('Enter the private key password: ')
if json_data['crypto']['kdf'] == 'pbkdf2':
password = password.encode() # type: ignore
private_key = encode_hex(decode_keyfile_json(json_data, password))
except ValueError:
log.fatal('Invalid private key format or password!')
return None
return private_key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_token_contract( self, token_supply: int, token_decimals: int, token_name: str, token_symbol: str, token_type: str = 'CustomToken', ):
"""Deploy a token contract.""" |
receipt = self.deploy(
contract_name=token_type,
args=[token_supply, token_decimals, token_name, token_symbol],
)
token_address = receipt['contractAddress']
assert token_address and is_address(token_address)
token_address = to_checksum_address(token_address)
return {token_type: token_address} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deploy_and_remember( self, contract_name: str, arguments: List, deployed_contracts: 'DeployedContracts', ) -> Contract: """ Deploys contract_name with arguments and store the result in deployed_contracts. """ |
receipt = self.deploy(contract_name, arguments)
deployed_contracts['contracts'][contract_name] = _deployed_data_from_receipt(
receipt=receipt,
constructor_arguments=arguments,
)
return self.web3.eth.contract(
abi=self.contract_manager.get_contract_abi(contract_name),
address=deployed_contracts['contracts'][contract_name]['address'],
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_token_network( self, token_registry_abi: Dict, token_registry_address: str, token_address: str, channel_participant_deposit_limit: Optional[int], token_network_deposit_limit: Optional[int], ):
"""Register token with a TokenNetworkRegistry contract.""" |
with_limits = contracts_version_expects_deposit_limits(self.contracts_version)
if with_limits:
return self._register_token_network_with_limits(
token_registry_abi,
token_registry_address,
token_address,
channel_participant_deposit_limit,
token_network_deposit_limit,
)
else:
return self._register_token_network_without_limits(
token_registry_abi,
token_registry_address,
token_address,
channel_participant_deposit_limit,
token_network_deposit_limit,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _register_token_network_without_limits( self, token_registry_abi: Dict, token_registry_address: str, token_address: str, channel_participant_deposit_limit: Optional[int], token_network_deposit_limit: Optional[int], ):
"""Register token with a TokenNetworkRegistry contract with a contracts-version that doesn't require deposit limits in the TokenNetwork constructor. """ |
if channel_participant_deposit_limit:
raise ValueError(
'contracts_version below 0.9.0 does not expect '
'channel_participant_deposit_limit',
)
if token_network_deposit_limit:
raise ValueError(
'contracts_version below 0.9.0 does not expect token_network_deposit_limit',
)
token_network_registry = self.web3.eth.contract(
abi=token_registry_abi,
address=token_registry_address,
)
version_from_onchain = token_network_registry.functions.contract_version().call()
if version_from_onchain != self.contract_manager.version_string:
raise RuntimeError(
f'got {version_from_onchain} from the chain, expected '
f'{self.contract_manager.version_string} in the deployment data',
)
command = token_network_registry.functions.createERC20TokenNetwork(
token_address,
)
self.transact(command)
token_network_address = token_network_registry.functions.token_to_token_networks(
token_address,
).call()
token_network_address = to_checksum_address(token_network_address)
LOG.debug(f'TokenNetwork address: {token_network_address}')
return token_network_address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_service_contracts( self, token_address: str, user_deposit_whole_balance_limit: int, ):
"""Deploy 3rd party service contracts""" |
chain_id = int(self.web3.version.network)
deployed_contracts: DeployedContracts = {
'contracts_version': self.contract_version_string(),
'chain_id': chain_id,
'contracts': {},
}
self._deploy_and_remember(CONTRACT_SERVICE_REGISTRY, [token_address], deployed_contracts)
user_deposit = self._deploy_and_remember(
contract_name=CONTRACT_USER_DEPOSIT,
arguments=[token_address, user_deposit_whole_balance_limit],
deployed_contracts=deployed_contracts,
)
monitoring_service_constructor_args = [
token_address,
deployed_contracts['contracts'][CONTRACT_SERVICE_REGISTRY]['address'],
deployed_contracts['contracts'][CONTRACT_USER_DEPOSIT]['address'],
]
msc = self._deploy_and_remember(
contract_name=CONTRACT_MONITORING_SERVICE,
arguments=monitoring_service_constructor_args,
deployed_contracts=deployed_contracts,
)
one_to_n = self._deploy_and_remember(
contract_name=CONTRACT_ONE_TO_N,
arguments=[user_deposit.address, chain_id],
deployed_contracts=deployed_contracts,
)
# Tell the UserDeposit instance about other contracts.
LOG.debug(
'Calling UserDeposit.init() with '
f'msc_address={msc.address} '
f'one_to_n_address={one_to_n.address}',
)
self.transact(user_deposit.functions.init(
_msc_address=msc.address,
_one_to_n_address=one_to_n.address,
))
return deployed_contracts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.