repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pybluez/pybluez | bluetooth/btcommon.py | to_full_uuid | def to_full_uuid (uuid):
"""
converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth
UUID.
"""
if not is_valid_uuid (uuid): raise ValueError ("invalid UUID")
if len (uuid) == 4:
return "0000%s-0000-1000-8000-00805F9B34FB" % uuid
elif len (uuid) == 8:
return "%s-0000-1000-8000-00805F9B34FB" % uuid
else:
return uuid | python | def to_full_uuid (uuid):
"""
converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth
UUID.
"""
if not is_valid_uuid (uuid): raise ValueError ("invalid UUID")
if len (uuid) == 4:
return "0000%s-0000-1000-8000-00805F9B34FB" % uuid
elif len (uuid) == 8:
return "%s-0000-1000-8000-00805F9B34FB" % uuid
else:
return uuid | [
"def",
"to_full_uuid",
"(",
"uuid",
")",
":",
"if",
"not",
"is_valid_uuid",
"(",
"uuid",
")",
":",
"raise",
"ValueError",
"(",
"\"invalid UUID\"",
")",
"if",
"len",
"(",
"uuid",
")",
"==",
"4",
":",
"return",
"\"0000%s-0000-1000-8000-00805F9B34FB\"",
"%",
"u... | converts a short 16-bit or 32-bit reserved UUID to a full 128-bit Bluetooth
UUID. | [
"converts",
"a",
"short",
"16",
"-",
"bit",
"or",
"32",
"-",
"bit",
"reserved",
"UUID",
"to",
"a",
"full",
"128",
"-",
"bit",
"Bluetooth",
"UUID",
"."
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/btcommon.py#L234-L245 | train | 222,200 |
pybluez/pybluez | bluetooth/bluez.py | DeviceDiscoverer.cancel_inquiry | def cancel_inquiry (self):
"""
Call this method to cancel an inquiry in process. inquiry_complete
will still be called.
"""
self.names_to_find = {}
if self.is_inquiring:
try:
_bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \
_bt.OCF_INQUIRY_CANCEL)
except _bt.error as e:
self.sock.close ()
self.sock = None
raise BluetoothError (e.args[0],
"error canceling inquiry: " +
e.args[1])
self.is_inquiring = False | python | def cancel_inquiry (self):
"""
Call this method to cancel an inquiry in process. inquiry_complete
will still be called.
"""
self.names_to_find = {}
if self.is_inquiring:
try:
_bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \
_bt.OCF_INQUIRY_CANCEL)
except _bt.error as e:
self.sock.close ()
self.sock = None
raise BluetoothError (e.args[0],
"error canceling inquiry: " +
e.args[1])
self.is_inquiring = False | [
"def",
"cancel_inquiry",
"(",
"self",
")",
":",
"self",
".",
"names_to_find",
"=",
"{",
"}",
"if",
"self",
".",
"is_inquiring",
":",
"try",
":",
"_bt",
".",
"hci_send_cmd",
"(",
"self",
".",
"sock",
",",
"_bt",
".",
"OGF_LINK_CTL",
",",
"_bt",
".",
"... | Call this method to cancel an inquiry in process. inquiry_complete
will still be called. | [
"Call",
"this",
"method",
"to",
"cancel",
"an",
"inquiry",
"in",
"process",
".",
"inquiry_complete",
"will",
"still",
"be",
"called",
"."
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/bluez.py#L451-L468 | train | 222,201 |
pybluez/pybluez | bluetooth/bluez.py | DeviceDiscoverer.device_discovered | def device_discovered (self, address, device_class, rssi, name):
"""
Called when a bluetooth device is discovered.
address is the bluetooth address of the device
device_class is the Class of Device, as specified in [1]
passed in as a 3-byte string
name is the user-friendly name of the device if lookup_names was
set when the inquiry was started. otherwise None
This method exists to be overriden.
[1] https://www.bluetooth.org/foundry/assignnumb/document/baseband
"""
if name:
print(("found: %s - %s (class 0x%X, rssi %s)" % \
(address, name, device_class, rssi)))
else:
print(("found: %s (class 0x%X)" % (address, device_class)))
print(("found: %s (class 0x%X, rssi %s)" % \
(address, device_class, rssi))) | python | def device_discovered (self, address, device_class, rssi, name):
"""
Called when a bluetooth device is discovered.
address is the bluetooth address of the device
device_class is the Class of Device, as specified in [1]
passed in as a 3-byte string
name is the user-friendly name of the device if lookup_names was
set when the inquiry was started. otherwise None
This method exists to be overriden.
[1] https://www.bluetooth.org/foundry/assignnumb/document/baseband
"""
if name:
print(("found: %s - %s (class 0x%X, rssi %s)" % \
(address, name, device_class, rssi)))
else:
print(("found: %s (class 0x%X)" % (address, device_class)))
print(("found: %s (class 0x%X, rssi %s)" % \
(address, device_class, rssi))) | [
"def",
"device_discovered",
"(",
"self",
",",
"address",
",",
"device_class",
",",
"rssi",
",",
"name",
")",
":",
"if",
"name",
":",
"print",
"(",
"(",
"\"found: %s - %s (class 0x%X, rssi %s)\"",
"%",
"(",
"address",
",",
"name",
",",
"device_class",
",",
"r... | Called when a bluetooth device is discovered.
address is the bluetooth address of the device
device_class is the Class of Device, as specified in [1]
passed in as a 3-byte string
name is the user-friendly name of the device if lookup_names was
set when the inquiry was started. otherwise None
This method exists to be overriden.
[1] https://www.bluetooth.org/foundry/assignnumb/document/baseband | [
"Called",
"when",
"a",
"bluetooth",
"device",
"is",
"discovered",
"."
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/bluez.py#L646-L668 | train | 222,202 |
pybluez/pybluez | examples/advanced/write-inquiry-scan.py | read_inquiry_scan_activity | def read_inquiry_scan_activity(sock):
"""returns the current inquiry scan interval and window,
or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQ_ACTIVITY)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# first read the current inquiry mode.
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQ_ACTIVITY )
pkt = sock.recv(255)
status,interval,window = struct.unpack("!xxxxxxBHH", pkt)
interval = bluez.btohs(interval)
interval = (interval >> 8) | ( (interval & 0xFF) << 8 )
window = (window >> 8) | ( (window & 0xFF) << 8 )
if status != 0: mode = -1
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return interval, window | python | def read_inquiry_scan_activity(sock):
"""returns the current inquiry scan interval and window,
or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQ_ACTIVITY)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# first read the current inquiry mode.
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQ_ACTIVITY )
pkt = sock.recv(255)
status,interval,window = struct.unpack("!xxxxxxBHH", pkt)
interval = bluez.btohs(interval)
interval = (interval >> 8) | ( (interval & 0xFF) << 8 )
window = (window >> 8) | ( (window & 0xFF) << 8 )
if status != 0: mode = -1
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return interval, window | [
"def",
"read_inquiry_scan_activity",
"(",
"sock",
")",
":",
"# save current filter",
"old_filter",
"=",
"sock",
".",
"getsockopt",
"(",
"bluez",
".",
"SOL_HCI",
",",
"bluez",
".",
"HCI_FILTER",
",",
"14",
")",
"# Setup socket filter to receive only events related to the... | returns the current inquiry scan interval and window,
or -1 on failure | [
"returns",
"the",
"current",
"inquiry",
"scan",
"interval",
"and",
"window",
"or",
"-",
"1",
"on",
"failure"
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/write-inquiry-scan.py#L6-L36 | train | 222,203 |
pybluez/pybluez | examples/advanced/write-inquiry-scan.py | write_inquiry_scan_activity | def write_inquiry_scan_activity(sock, interval, window):
"""returns 0 on success, -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# write_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_WRITE_INQ_ACTIVITY)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# send the command!
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_WRITE_INQ_ACTIVITY, struct.pack("HH",
interval, window) )
pkt = sock.recv(255)
status = struct.unpack("xxxxxxB", pkt)[0]
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
if status != 0: return -1
return 0 | python | def write_inquiry_scan_activity(sock, interval, window):
"""returns 0 on success, -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# write_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_WRITE_INQ_ACTIVITY)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# send the command!
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_WRITE_INQ_ACTIVITY, struct.pack("HH",
interval, window) )
pkt = sock.recv(255)
status = struct.unpack("xxxxxxB", pkt)[0]
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
if status != 0: return -1
return 0 | [
"def",
"write_inquiry_scan_activity",
"(",
"sock",
",",
"interval",
",",
"window",
")",
":",
"# save current filter",
"old_filter",
"=",
"sock",
".",
"getsockopt",
"(",
"bluez",
".",
"SOL_HCI",
",",
"bluez",
".",
"HCI_FILTER",
",",
"14",
")",
"# Setup socket fil... | returns 0 on success, -1 on failure | [
"returns",
"0",
"on",
"success",
"-",
"1",
"on",
"failure"
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/write-inquiry-scan.py#L38-L65 | train | 222,204 |
pybluez/pybluez | examples/advanced/inquiry-with-rssi.py | read_inquiry_mode | def read_inquiry_mode(sock):
"""returns the current mode, or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQUIRY_MODE)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# first read the current inquiry mode.
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQUIRY_MODE )
pkt = sock.recv(255)
status,mode = struct.unpack("xxxxxxBB", pkt)
if status != 0: mode = -1
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return mode | python | def read_inquiry_mode(sock):
"""returns the current mode, or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQUIRY_MODE)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);
bluez.hci_filter_set_opcode(flt, opcode)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
# first read the current inquiry mode.
bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL,
bluez.OCF_READ_INQUIRY_MODE )
pkt = sock.recv(255)
status,mode = struct.unpack("xxxxxxBB", pkt)
if status != 0: mode = -1
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return mode | [
"def",
"read_inquiry_mode",
"(",
"sock",
")",
":",
"# save current filter",
"old_filter",
"=",
"sock",
".",
"getsockopt",
"(",
"bluez",
".",
"SOL_HCI",
",",
"bluez",
".",
"HCI_FILTER",
",",
"14",
")",
"# Setup socket filter to receive only events related to the",
"# r... | returns the current mode, or -1 on failure | [
"returns",
"the",
"current",
"mode",
"or",
"-",
"1",
"on",
"failure"
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/examples/advanced/inquiry-with-rssi.py#L16-L42 | train | 222,205 |
pybluez/pybluez | macos/_lightbluecommon.py | splitclass | def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google for
"assigned numbers bluetooth baseband" you might find some documents
that discuss how to extract this information from the class of device.
Example:
>>> splitclass(1057036)
(129, 1, 3)
>>>
"""
if not isinstance(classofdevice, int):
try:
classofdevice = int(classofdevice)
except (TypeError, ValueError):
raise TypeError("Given device class '%s' cannot be split" % \
str(classofdevice))
data = classofdevice >> 2 # skip over the 2 "format" bits
service = data >> 11
major = (data >> 6) & 0x1F
minor = data & 0x3F
return (service, major, minor) | python | def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google for
"assigned numbers bluetooth baseband" you might find some documents
that discuss how to extract this information from the class of device.
Example:
>>> splitclass(1057036)
(129, 1, 3)
>>>
"""
if not isinstance(classofdevice, int):
try:
classofdevice = int(classofdevice)
except (TypeError, ValueError):
raise TypeError("Given device class '%s' cannot be split" % \
str(classofdevice))
data = classofdevice >> 2 # skip over the 2 "format" bits
service = data >> 11
major = (data >> 6) & 0x1F
minor = data & 0x3F
return (service, major, minor) | [
"def",
"splitclass",
"(",
"classofdevice",
")",
":",
"if",
"not",
"isinstance",
"(",
"classofdevice",
",",
"int",
")",
":",
"try",
":",
"classofdevice",
"=",
"int",
"(",
"classofdevice",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise"... | Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google for
"assigned numbers bluetooth baseband" you might find some documents
that discuss how to extract this information from the class of device.
Example:
>>> splitclass(1057036)
(129, 1, 3)
>>> | [
"Splits",
"the",
"given",
"class",
"of",
"device",
"to",
"return",
"a",
"3",
"-",
"item",
"tuple",
"with",
"the",
"major",
"service",
"class",
"major",
"device",
"class",
"and",
"minor",
"device",
"class",
"values",
"."
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightbluecommon.py#L43-L69 | train | 222,206 |
pybluez/pybluez | macos/_lightblue.py | _searchservices | def _searchservices(device, name=None, uuid=None, uuidbad=None):
"""
Searches the given IOBluetoothDevice using the specified parameters.
Returns an empty list if the device has no services.
uuid should be IOBluetoothSDPUUID object.
"""
if not isinstance(device, _IOBluetooth.IOBluetoothDevice):
raise ValueError("device must be IOBluetoothDevice, was %s" % \
type(device))
services = []
allservices = device.getServices()
if uuid:
gooduuids = (uuid, )
else:
gooduuids = ()
if uuidbad:
baduuids = (uuidbad, )
else:
baduuids = ()
if allservices is not None:
for s in allservices:
if gooduuids and not s.hasServiceFromArray_(gooduuids):
continue
if baduuids and s.hasServiceFromArray_(baduuids):
continue
if name is None or s.getServiceName() == name:
services.append(s)
return services | python | def _searchservices(device, name=None, uuid=None, uuidbad=None):
"""
Searches the given IOBluetoothDevice using the specified parameters.
Returns an empty list if the device has no services.
uuid should be IOBluetoothSDPUUID object.
"""
if not isinstance(device, _IOBluetooth.IOBluetoothDevice):
raise ValueError("device must be IOBluetoothDevice, was %s" % \
type(device))
services = []
allservices = device.getServices()
if uuid:
gooduuids = (uuid, )
else:
gooduuids = ()
if uuidbad:
baduuids = (uuidbad, )
else:
baduuids = ()
if allservices is not None:
for s in allservices:
if gooduuids and not s.hasServiceFromArray_(gooduuids):
continue
if baduuids and s.hasServiceFromArray_(baduuids):
continue
if name is None or s.getServiceName() == name:
services.append(s)
return services | [
"def",
"_searchservices",
"(",
"device",
",",
"name",
"=",
"None",
",",
"uuid",
"=",
"None",
",",
"uuidbad",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"device",
",",
"_IOBluetooth",
".",
"IOBluetoothDevice",
")",
":",
"raise",
"ValueError",
... | Searches the given IOBluetoothDevice using the specified parameters.
Returns an empty list if the device has no services.
uuid should be IOBluetoothSDPUUID object. | [
"Searches",
"the",
"given",
"IOBluetoothDevice",
"using",
"the",
"specified",
"parameters",
".",
"Returns",
"an",
"empty",
"list",
"if",
"the",
"device",
"has",
"no",
"services",
"."
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightblue.py#L485-L515 | train | 222,207 |
bambinos/bambi | bambi/backends/pymc.py | PyMC3BackEnd.reset | def reset(self):
'''
Reset PyMC3 model and all tracked distributions and parameters.
'''
self.model = pm.Model()
self.mu = None
self.par_groups = {} | python | def reset(self):
'''
Reset PyMC3 model and all tracked distributions and parameters.
'''
self.model = pm.Model()
self.mu = None
self.par_groups = {} | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"model",
"=",
"pm",
".",
"Model",
"(",
")",
"self",
".",
"mu",
"=",
"None",
"self",
".",
"par_groups",
"=",
"{",
"}"
] | Reset PyMC3 model and all tracked distributions and parameters. | [
"Reset",
"PyMC3",
"model",
"and",
"all",
"tracked",
"distributions",
"and",
"parameters",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/pymc.py#L37-L43 | train | 222,208 |
bambinos/bambi | bambi/backends/pymc.py | PyMC3BackEnd._build_dist | def _build_dist(self, spec, label, dist, **kwargs):
''' Build and return a PyMC3 Distribution. '''
if isinstance(dist, string_types):
if hasattr(pm, dist):
dist = getattr(pm, dist)
elif dist in self.dists:
dist = self.dists[dist]
else:
raise ValueError("The Distribution class '%s' was not "
"found in PyMC3 or the PyMC3BackEnd." % dist)
# Inspect all args in case we have hyperparameters
def _expand_args(k, v, label):
if isinstance(v, Prior):
label = '%s_%s' % (label, k)
return self._build_dist(spec, label, v.name, **v.args)
return v
kwargs = {k: _expand_args(k, v, label) for (k, v) in kwargs.items()}
# Non-centered parameterization for hyperpriors
if spec.noncentered and 'sd' in kwargs and 'observed' not in kwargs \
and isinstance(kwargs['sd'], pm.model.TransformedRV):
old_sd = kwargs['sd']
_offset = pm.Normal(label + '_offset', mu=0, sd=1,
shape=kwargs['shape'])
return pm.Deterministic(label, _offset * old_sd)
return dist(label, **kwargs) | python | def _build_dist(self, spec, label, dist, **kwargs):
''' Build and return a PyMC3 Distribution. '''
if isinstance(dist, string_types):
if hasattr(pm, dist):
dist = getattr(pm, dist)
elif dist in self.dists:
dist = self.dists[dist]
else:
raise ValueError("The Distribution class '%s' was not "
"found in PyMC3 or the PyMC3BackEnd." % dist)
# Inspect all args in case we have hyperparameters
def _expand_args(k, v, label):
if isinstance(v, Prior):
label = '%s_%s' % (label, k)
return self._build_dist(spec, label, v.name, **v.args)
return v
kwargs = {k: _expand_args(k, v, label) for (k, v) in kwargs.items()}
# Non-centered parameterization for hyperpriors
if spec.noncentered and 'sd' in kwargs and 'observed' not in kwargs \
and isinstance(kwargs['sd'], pm.model.TransformedRV):
old_sd = kwargs['sd']
_offset = pm.Normal(label + '_offset', mu=0, sd=1,
shape=kwargs['shape'])
return pm.Deterministic(label, _offset * old_sd)
return dist(label, **kwargs) | [
"def",
"_build_dist",
"(",
"self",
",",
"spec",
",",
"label",
",",
"dist",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"string_types",
")",
":",
"if",
"hasattr",
"(",
"pm",
",",
"dist",
")",
":",
"dist",
"=",
"getattr",... | Build and return a PyMC3 Distribution. | [
"Build",
"and",
"return",
"a",
"PyMC3",
"Distribution",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/pymc.py#L45-L73 | train | 222,209 |
bambinos/bambi | bambi/results.py | MCMCResults.to_df | def to_df(self, varnames=None, ranefs=False, transformed=False,
chains=None):
'''
Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains
concatenated.
Args:
varnames (list): List of variable names to include; if None
(default), all eligible variables are included.
ranefs (bool): Whether or not to include random effects in the
returned DataFrame. Default is True.
transformed (bool): Whether or not to include internally
transformed variables in the result. Default is False.
chains (int, list): Index, or list of indexes, of chains to
concatenate. E.g., [1, 3] would concatenate the first and
third chains, and ignore any others. If None (default),
concatenates all available chains.
'''
# filter out unwanted variables
names = self._filter_names(varnames, ranefs, transformed)
# concatenate the (pre-sliced) chains
if chains is None:
chains = list(range(self.n_chains))
chains = listify(chains)
data = [self.data[:, i, :] for i in chains]
data = np.concatenate(data, axis=0)
# construct the trace DataFrame
df = sum([self.level_dict[x] for x in names], [])
df = pd.DataFrame({x: data[:, self.levels.index(x)] for x in df})
return df | python | def to_df(self, varnames=None, ranefs=False, transformed=False,
chains=None):
'''
Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains
concatenated.
Args:
varnames (list): List of variable names to include; if None
(default), all eligible variables are included.
ranefs (bool): Whether or not to include random effects in the
returned DataFrame. Default is True.
transformed (bool): Whether or not to include internally
transformed variables in the result. Default is False.
chains (int, list): Index, or list of indexes, of chains to
concatenate. E.g., [1, 3] would concatenate the first and
third chains, and ignore any others. If None (default),
concatenates all available chains.
'''
# filter out unwanted variables
names = self._filter_names(varnames, ranefs, transformed)
# concatenate the (pre-sliced) chains
if chains is None:
chains = list(range(self.n_chains))
chains = listify(chains)
data = [self.data[:, i, :] for i in chains]
data = np.concatenate(data, axis=0)
# construct the trace DataFrame
df = sum([self.level_dict[x] for x in names], [])
df = pd.DataFrame({x: data[:, self.levels.index(x)] for x in df})
return df | [
"def",
"to_df",
"(",
"self",
",",
"varnames",
"=",
"None",
",",
"ranefs",
"=",
"False",
",",
"transformed",
"=",
"False",
",",
"chains",
"=",
"None",
")",
":",
"# filter out unwanted variables",
"names",
"=",
"self",
".",
"_filter_names",
"(",
"varnames",
... | Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains
concatenated.
Args:
varnames (list): List of variable names to include; if None
(default), all eligible variables are included.
ranefs (bool): Whether or not to include random effects in the
returned DataFrame. Default is True.
transformed (bool): Whether or not to include internally
transformed variables in the result. Default is False.
chains (int, list): Index, or list of indexes, of chains to
concatenate. E.g., [1, 3] would concatenate the first and
third chains, and ignore any others. If None (default),
concatenates all available chains. | [
"Returns",
"the",
"MCMC",
"samples",
"in",
"a",
"nice",
"neat",
"pandas",
"DataFrame",
"with",
"all",
"MCMC",
"chains",
"concatenated",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/results.py#L369-L402 | train | 222,210 |
bambinos/bambi | bambi/diagnostics.py | autocov | def autocov(x):
"""Compute autocovariance estimates for every lag for the input array.
Args:
x (array-like): An array containing MCMC samples.
Returns:
np.ndarray: An array of the same size as the input array.
"""
acorr = autocorr(x)
varx = np.var(x, ddof=1) * (len(x) - 1) / len(x)
acov = acorr * varx
return acov | python | def autocov(x):
"""Compute autocovariance estimates for every lag for the input array.
Args:
x (array-like): An array containing MCMC samples.
Returns:
np.ndarray: An array of the same size as the input array.
"""
acorr = autocorr(x)
varx = np.var(x, ddof=1) * (len(x) - 1) / len(x)
acov = acorr * varx
return acov | [
"def",
"autocov",
"(",
"x",
")",
":",
"acorr",
"=",
"autocorr",
"(",
"x",
")",
"varx",
"=",
"np",
".",
"var",
"(",
"x",
",",
"ddof",
"=",
"1",
")",
"*",
"(",
"len",
"(",
"x",
")",
"-",
"1",
")",
"/",
"len",
"(",
"x",
")",
"acov",
"=",
"... | Compute autocovariance estimates for every lag for the input array.
Args:
x (array-like): An array containing MCMC samples.
Returns:
np.ndarray: An array of the same size as the input array. | [
"Compute",
"autocovariance",
"estimates",
"for",
"every",
"lag",
"for",
"the",
"input",
"array",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/diagnostics.py#L30-L43 | train | 222,211 |
bambinos/bambi | bambi/models.py | Model.reset | def reset(self):
'''
Reset list of terms and y-variable.
'''
self.terms = OrderedDict()
self.y = None
self.backend = None
self.added_terms = []
self._added_priors = {}
self.completes = []
self.clean_data = None | python | def reset(self):
'''
Reset list of terms and y-variable.
'''
self.terms = OrderedDict()
self.y = None
self.backend = None
self.added_terms = []
self._added_priors = {}
self.completes = []
self.clean_data = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"terms",
"=",
"OrderedDict",
"(",
")",
"self",
".",
"y",
"=",
"None",
"self",
".",
"backend",
"=",
"None",
"self",
".",
"added_terms",
"=",
"[",
"]",
"self",
".",
"_added_priors",
"=",
"{",
"}",
... | Reset list of terms and y-variable. | [
"Reset",
"list",
"of",
"terms",
"and",
"y",
"-",
"variable",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L83-L93 | train | 222,212 |
bambinos/bambi | bambi/models.py | Model.fit | def fit(self, fixed=None, random=None, priors=None, family='gaussian',
link=None, run=True, categorical=None, backend=None, **kwargs):
'''Fit the model using the specified BackEnd.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
run (bool): Whether or not to immediately begin fitting the model
once any set up of passed arguments is complete.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
backend (str): The name of the BackEnd to use. Currently only
'pymc' and 'stan' backends are supported. Defaults to PyMC3.
'''
if fixed is not None or random is not None:
self.add(fixed=fixed, random=random, priors=priors, family=family,
link=link, categorical=categorical, append=False)
''' Run the BackEnd to fit the model. '''
if backend is None:
backend = 'pymc' if self._backend_name is None else self._backend_name
if run:
if not self.built or backend != self._backend_name:
self.build(backend)
return self.backend.run(**kwargs)
self._backend_name = backend | python | def fit(self, fixed=None, random=None, priors=None, family='gaussian',
link=None, run=True, categorical=None, backend=None, **kwargs):
'''Fit the model using the specified BackEnd.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
run (bool): Whether or not to immediately begin fitting the model
once any set up of passed arguments is complete.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
backend (str): The name of the BackEnd to use. Currently only
'pymc' and 'stan' backends are supported. Defaults to PyMC3.
'''
if fixed is not None or random is not None:
self.add(fixed=fixed, random=random, priors=priors, family=family,
link=link, categorical=categorical, append=False)
''' Run the BackEnd to fit the model. '''
if backend is None:
backend = 'pymc' if self._backend_name is None else self._backend_name
if run:
if not self.built or backend != self._backend_name:
self.build(backend)
return self.backend.run(**kwargs)
self._backend_name = backend | [
"def",
"fit",
"(",
"self",
",",
"fixed",
"=",
"None",
",",
"random",
"=",
"None",
",",
"priors",
"=",
"None",
",",
"family",
"=",
"'gaussian'",
",",
"link",
"=",
"None",
",",
"run",
"=",
"True",
",",
"categorical",
"=",
"None",
",",
"backend",
"=",... | Fit the model using the specified BackEnd.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
run (bool): Whether or not to immediately begin fitting the model
once any set up of passed arguments is complete.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
backend (str): The name of the BackEnd to use. Currently only
'pymc' and 'stan' backends are supported. Defaults to PyMC3. | [
"Fit",
"the",
"model",
"using",
"the",
"specified",
"BackEnd",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L236-L286 | train | 222,213 |
bambinos/bambi | bambi/models.py | Model.add | def add(self, fixed=None, random=None, priors=None, family='gaussian',
link=None, categorical=None, append=True):
'''Adds one or more terms to the model via an R-like formula syntax.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
append (bool): If True, terms are appended to the existing model
rather than replacing any existing terms. This allows
formula-based specification of the model in stages.
'''
data = self.data
# Primitive values (floats, strs) can be overwritten with Prior objects
# so we need to make sure to copy first to avoid bad things happening
# if user is re-using same prior dict in multiple models.
if priors is None:
priors = {}
else:
priors = deepcopy(priors)
if not append:
self.reset()
# Explicitly convert columns to category if desired--though this
# can also be done within the formula using C().
if categorical is not None:
data = data.copy()
cats = listify(categorical)
data[cats] = data[cats].apply(lambda x: x.astype('category'))
# Custom patsy.missing.NAAction class. Similar to patsy drop/raise
# defaults, but changes the raised message and logs any dropped rows
NA_handler = Custom_NA(dropna=self.dropna)
# screen fixed terms
if fixed is not None:
if '~' in fixed:
clean_fix = re.sub(r'\[.+\]', '', fixed)
dmatrices(clean_fix, data=data, NA_action=NA_handler)
else:
dmatrix(fixed, data=data, NA_action=NA_handler)
# screen random terms
if random is not None:
for term in listify(random):
for side in term.split('|'):
dmatrix(side, data=data, NA_action=NA_handler)
# update the running list of complete cases
if len(NA_handler.completes):
self.completes.append(NA_handler.completes)
# save arguments to pass to _add()
args = dict(zip(
['fixed', 'random', 'priors', 'family', 'link', 'categorical'],
[fixed, random, priors, family, link, categorical]))
self.added_terms.append(args)
self.built = False | python | def add(self, fixed=None, random=None, priors=None, family='gaussian',
link=None, categorical=None, append=True):
'''Adds one or more terms to the model via an R-like formula syntax.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
append (bool): If True, terms are appended to the existing model
rather than replacing any existing terms. This allows
formula-based specification of the model in stages.
'''
data = self.data
# Primitive values (floats, strs) can be overwritten with Prior objects
# so we need to make sure to copy first to avoid bad things happening
# if user is re-using same prior dict in multiple models.
if priors is None:
priors = {}
else:
priors = deepcopy(priors)
if not append:
self.reset()
# Explicitly convert columns to category if desired--though this
# can also be done within the formula using C().
if categorical is not None:
data = data.copy()
cats = listify(categorical)
data[cats] = data[cats].apply(lambda x: x.astype('category'))
# Custom patsy.missing.NAAction class. Similar to patsy drop/raise
# defaults, but changes the raised message and logs any dropped rows
NA_handler = Custom_NA(dropna=self.dropna)
# screen fixed terms
if fixed is not None:
if '~' in fixed:
clean_fix = re.sub(r'\[.+\]', '', fixed)
dmatrices(clean_fix, data=data, NA_action=NA_handler)
else:
dmatrix(fixed, data=data, NA_action=NA_handler)
# screen random terms
if random is not None:
for term in listify(random):
for side in term.split('|'):
dmatrix(side, data=data, NA_action=NA_handler)
# update the running list of complete cases
if len(NA_handler.completes):
self.completes.append(NA_handler.completes)
# save arguments to pass to _add()
args = dict(zip(
['fixed', 'random', 'priors', 'family', 'link', 'categorical'],
[fixed, random, priors, family, link, categorical]))
self.added_terms.append(args)
self.built = False | [
"def",
"add",
"(",
"self",
",",
"fixed",
"=",
"None",
",",
"random",
"=",
"None",
",",
"priors",
"=",
"None",
",",
"family",
"=",
"'gaussian'",
",",
"link",
"=",
"None",
",",
"categorical",
"=",
"None",
",",
"append",
"=",
"True",
")",
":",
"data",... | Adds one or more terms to the model via an R-like formula syntax.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Optional list-based specification of random effects.
priors (dict): Optional specification of priors for one or more
terms. A dict where the keys are the names of terms in the
model, and the values are either instances of class Prior or
ints, floats, or strings that specify the width of the priors
on a standardized scale.
family (str, Family): A specification of the model family
(analogous to the family object in R). Either a string, or an
instance of class priors.Family. If a string is passed, a
family with the corresponding name must be defined in the
defaults loaded at Model initialization. Valid pre-defined
families are 'gaussian', 'bernoulli', 'poisson', and 't'.
link (str): The model link function to use. Can be either a string
(must be one of the options defined in the current backend;
typically this will include at least 'identity', 'logit',
'inverse', and 'log'), or a callable that takes a 1D ndarray
or theano tensor as the sole argument and returns one with
the same shape.
categorical (str, list): The names of any variables to treat as
categorical. Can be either a single variable name, or a list
of names. If categorical is None, the data type of the columns
in the DataFrame will be used to infer handling. In cases where
numeric columns are to be treated as categoricals (e.g., random
factors coded as numerical IDs), explicitly passing variable
names via this argument is recommended.
append (bool): If True, terms are appended to the existing model
rather than replacing any existing terms. This allows
formula-based specification of the model in stages. | [
"Adds",
"one",
"or",
"more",
"terms",
"to",
"the",
"model",
"via",
"an",
"R",
"-",
"like",
"formula",
"syntax",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L288-L372 | train | 222,214 |
bambinos/bambi | bambi/models.py | Model.set_priors | def set_priors(self, priors=None, fixed=None, random=None,
match_derived_names=True):
'''Set priors for one or more existing terms.
Args:
priors (dict): Dict of priors to update. Keys are names of terms
to update; values are the new priors (either a Prior instance,
or an int or float that scales the default priors). Note that
a tuple can be passed as the key, in which case the same prior
will be applied to all terms named in the tuple.
fixed (Prior, int, float, str): a prior specification to apply to
all fixed terms currently included in the model.
random (Prior, int, float, str): a prior specification to apply to
all random terms currently included in the model.
match_derived_names (bool): if True, the specified prior(s) will be
applied not only to terms that match the keyword exactly,
but to the levels of random effects that were derived from
the original specification with the passed name. For example,
`priors={'condition|subject':0.5}` would apply the prior
to the terms with names '1|subject', 'condition[T.1]|subject',
and so on. If False, an exact match is required for the
prior to be applied.
'''
# save arguments to pass to _set_priors() at build time
kwargs = dict(zip(
['priors', 'fixed', 'random', 'match_derived_names'],
[priors, fixed, random, match_derived_names]))
self._added_priors.update(kwargs)
self.built = False | python | def set_priors(self, priors=None, fixed=None, random=None,
match_derived_names=True):
'''Set priors for one or more existing terms.
Args:
priors (dict): Dict of priors to update. Keys are names of terms
to update; values are the new priors (either a Prior instance,
or an int or float that scales the default priors). Note that
a tuple can be passed as the key, in which case the same prior
will be applied to all terms named in the tuple.
fixed (Prior, int, float, str): a prior specification to apply to
all fixed terms currently included in the model.
random (Prior, int, float, str): a prior specification to apply to
all random terms currently included in the model.
match_derived_names (bool): if True, the specified prior(s) will be
applied not only to terms that match the keyword exactly,
but to the levels of random effects that were derived from
the original specification with the passed name. For example,
`priors={'condition|subject':0.5}` would apply the prior
to the terms with names '1|subject', 'condition[T.1]|subject',
and so on. If False, an exact match is required for the
prior to be applied.
'''
# save arguments to pass to _set_priors() at build time
kwargs = dict(zip(
['priors', 'fixed', 'random', 'match_derived_names'],
[priors, fixed, random, match_derived_names]))
self._added_priors.update(kwargs)
self.built = False | [
"def",
"set_priors",
"(",
"self",
",",
"priors",
"=",
"None",
",",
"fixed",
"=",
"None",
",",
"random",
"=",
"None",
",",
"match_derived_names",
"=",
"True",
")",
":",
"# save arguments to pass to _set_priors() at build time",
"kwargs",
"=",
"dict",
"(",
"zip",
... | Set priors for one or more existing terms.
Args:
priors (dict): Dict of priors to update. Keys are names of terms
to update; values are the new priors (either a Prior instance,
or an int or float that scales the default priors). Note that
a tuple can be passed as the key, in which case the same prior
will be applied to all terms named in the tuple.
fixed (Prior, int, float, str): a prior specification to apply to
all fixed terms currently included in the model.
random (Prior, int, float, str): a prior specification to apply to
all random terms currently included in the model.
match_derived_names (bool): if True, the specified prior(s) will be
applied not only to terms that match the keyword exactly,
but to the levels of random effects that were derived from
the original specification with the passed name. For example,
`priors={'condition|subject':0.5}` would apply the prior
to the terms with names '1|subject', 'condition[T.1]|subject',
and so on. If False, an exact match is required for the
prior to be applied. | [
"Set",
"priors",
"for",
"one",
"or",
"more",
"existing",
"terms",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L576-L605 | train | 222,215 |
bambinos/bambi | bambi/models.py | Model.fixed_terms | def fixed_terms(self):
'''Return dict of all and only fixed effects in model.'''
return {k: v for (k, v) in self.terms.items() if not v.random} | python | def fixed_terms(self):
'''Return dict of all and only fixed effects in model.'''
return {k: v for (k, v) in self.terms.items() if not v.random} | [
"def",
"fixed_terms",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"terms",
".",
"items",
"(",
")",
"if",
"not",
"v",
".",
"random",
"}"
] | Return dict of all and only fixed effects in model. | [
"Return",
"dict",
"of",
"all",
"and",
"only",
"fixed",
"effects",
"in",
"model",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L722-L724 | train | 222,216 |
bambinos/bambi | bambi/models.py | Model.random_terms | def random_terms(self):
'''Return dict of all and only random effects in model.'''
return {k: v for (k, v) in self.terms.items() if v.random} | python | def random_terms(self):
'''Return dict of all and only random effects in model.'''
return {k: v for (k, v) in self.terms.items() if v.random} | [
"def",
"random_terms",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"terms",
".",
"items",
"(",
")",
"if",
"v",
".",
"random",
"}"
] | Return dict of all and only random effects in model. | [
"Return",
"dict",
"of",
"all",
"and",
"only",
"random",
"effects",
"in",
"model",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/models.py#L727-L729 | train | 222,217 |
bambinos/bambi | bambi/priors.py | Prior.update | def update(self, **kwargs):
'''Update the model arguments with additional arguments.
Args:
kwargs (dict): Optional keyword arguments to add to prior args.
'''
# Backends expect numpy arrays, so make sure all numeric values are
# represented as such.
kwargs = {k: (np.array(v) if isinstance(v, (int, float)) else v)
for k, v in kwargs.items()}
self.args.update(kwargs) | python | def update(self, **kwargs):
'''Update the model arguments with additional arguments.
Args:
kwargs (dict): Optional keyword arguments to add to prior args.
'''
# Backends expect numpy arrays, so make sure all numeric values are
# represented as such.
kwargs = {k: (np.array(v) if isinstance(v, (int, float)) else v)
for k, v in kwargs.items()}
self.args.update(kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Backends expect numpy arrays, so make sure all numeric values are",
"# represented as such.",
"kwargs",
"=",
"{",
"k",
":",
"(",
"np",
".",
"array",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
... | Update the model arguments with additional arguments.
Args:
kwargs (dict): Optional keyword arguments to add to prior args. | [
"Update",
"the",
"model",
"arguments",
"with",
"additional",
"arguments",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/priors.py#L59-L70 | train | 222,218 |
bambinos/bambi | bambi/priors.py | PriorFactory.get | def get(self, dist=None, term=None, family=None):
'''Retrieve default prior for a named distribution, term type, or family.
Args:
dist (str): Name of desired distribution. Note that the name is
the key in the defaults dictionary, not the name of the
Distribution object used to construct the prior.
term (str): The type of term family to retrieve defaults for.
Must be one of 'intercept', 'fixed', or 'random'.
family (str): The name of the Family to retrieve. Must be a value
defined internally. In the default config, this is one of
'gaussian', 'bernoulli', 'poisson', or 't'.
'''
if dist is not None:
if dist not in self.dists:
raise ValueError(
"'%s' is not a valid distribution name." % dist)
return self._get_prior(self.dists[dist])
elif term is not None:
if term not in self.terms:
raise ValueError("'%s' is not a valid term type." % term)
return self._get_prior(self.terms[term])
elif family is not None:
if family not in self.families:
raise ValueError("'%s' is not a valid family name." % family)
_f = self.families[family]
prior = self._get_prior(_f['dist'])
return Family(family, prior, _f['link'], _f['parent']) | python | def get(self, dist=None, term=None, family=None):
'''Retrieve default prior for a named distribution, term type, or family.
Args:
dist (str): Name of desired distribution. Note that the name is
the key in the defaults dictionary, not the name of the
Distribution object used to construct the prior.
term (str): The type of term family to retrieve defaults for.
Must be one of 'intercept', 'fixed', or 'random'.
family (str): The name of the Family to retrieve. Must be a value
defined internally. In the default config, this is one of
'gaussian', 'bernoulli', 'poisson', or 't'.
'''
if dist is not None:
if dist not in self.dists:
raise ValueError(
"'%s' is not a valid distribution name." % dist)
return self._get_prior(self.dists[dist])
elif term is not None:
if term not in self.terms:
raise ValueError("'%s' is not a valid term type." % term)
return self._get_prior(self.terms[term])
elif family is not None:
if family not in self.families:
raise ValueError("'%s' is not a valid family name." % family)
_f = self.families[family]
prior = self._get_prior(_f['dist'])
return Family(family, prior, _f['link'], _f['parent']) | [
"def",
"get",
"(",
"self",
",",
"dist",
"=",
"None",
",",
"term",
"=",
"None",
",",
"family",
"=",
"None",
")",
":",
"if",
"dist",
"is",
"not",
"None",
":",
"if",
"dist",
"not",
"in",
"self",
".",
"dists",
":",
"raise",
"ValueError",
"(",
"\"'%s'... | Retrieve default prior for a named distribution, term type, or family.
Args:
dist (str): Name of desired distribution. Note that the name is
the key in the defaults dictionary, not the name of the
Distribution object used to construct the prior.
term (str): The type of term family to retrieve defaults for.
Must be one of 'intercept', 'fixed', or 'random'.
family (str): The name of the Family to retrieve. Must be a value
defined internally. In the default config, this is one of
'gaussian', 'bernoulli', 'poisson', or 't'. | [
"Retrieve",
"default",
"prior",
"for",
"a",
"named",
"distribution",
"term",
"type",
"or",
"family",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/priors.py#L153-L181 | train | 222,219 |
bambinos/bambi | bambi/backends/stan.py | StanBackEnd.reset | def reset(self):
'''
Reset Stan model and all tracked distributions and parameters.
'''
self.parameters = []
self.transformed_parameters = []
self.expressions = []
self.data = []
self.transformed_data = []
self.X = {}
self.model = []
self.mu_cont = []
self.mu_cat = []
self._original_names = {}
# variables to suppress in output. Stan uses limited set for variable
# names, so track variable names we may need to simplify for the model
# code and then sub back later.
self._suppress_vars = ['yhat', 'lp__'] | python | def reset(self):
'''
Reset Stan model and all tracked distributions and parameters.
'''
self.parameters = []
self.transformed_parameters = []
self.expressions = []
self.data = []
self.transformed_data = []
self.X = {}
self.model = []
self.mu_cont = []
self.mu_cat = []
self._original_names = {}
# variables to suppress in output. Stan uses limited set for variable
# names, so track variable names we may need to simplify for the model
# code and then sub back later.
self._suppress_vars = ['yhat', 'lp__'] | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"parameters",
"=",
"[",
"]",
"self",
".",
"transformed_parameters",
"=",
"[",
"]",
"self",
".",
"expressions",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"[",
"]",
"self",
".",
"transformed_data",
"="... | Reset Stan model and all tracked distributions and parameters. | [
"Reset",
"Stan",
"model",
"and",
"all",
"tracked",
"distributions",
"and",
"parameters",
"."
] | b4a0ced917968bb99ca20915317417d708387946 | https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/stan.py#L63-L80 | train | 222,220 |
nfcpy/nfcpy | src/nfc/clf/rcs956.py | Chipset.reset_mode | def reset_mode(self):
"""Send a Reset command to set the operation mode to 0."""
self.command(0x18, b"\x01", timeout=0.1)
self.transport.write(Chipset.ACK)
time.sleep(0.010) | python | def reset_mode(self):
"""Send a Reset command to set the operation mode to 0."""
self.command(0x18, b"\x01", timeout=0.1)
self.transport.write(Chipset.ACK)
time.sleep(0.010) | [
"def",
"reset_mode",
"(",
"self",
")",
":",
"self",
".",
"command",
"(",
"0x18",
",",
"b\"\\x01\"",
",",
"timeout",
"=",
"0.1",
")",
"self",
".",
"transport",
".",
"write",
"(",
"Chipset",
".",
"ACK",
")",
"time",
".",
"sleep",
"(",
"0.010",
")"
] | Send a Reset command to set the operation mode to 0. | [
"Send",
"a",
"Reset",
"command",
"to",
"set",
"the",
"operation",
"mode",
"to",
"0",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L149-L153 | train | 222,221 |
nfcpy/nfcpy | src/nfc/clf/rcs956.py | Device.sense_ttb | def sense_ttb(self, target):
"""Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106
kbps. For a Type 4B Tag the firmware automatically sends an
ATTRIB command that configures the use of DID and 64 byte
maximum frame size. The driver reverts this configuration with
a DESELECT and WUPB command to return the target prepared for
activation (which nfcpy does in the tag activation code).
"""
return super(Device, self).sense_ttb(target, did=b'\x01') | python | def sense_ttb(self, target):
"""Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106
kbps. For a Type 4B Tag the firmware automatically sends an
ATTRIB command that configures the use of DID and 64 byte
maximum frame size. The driver reverts this configuration with
a DESELECT and WUPB command to return the target prepared for
activation (which nfcpy does in the tag activation code).
"""
return super(Device, self).sense_ttb(target, did=b'\x01') | [
"def",
"sense_ttb",
"(",
"self",
",",
"target",
")",
":",
"return",
"super",
"(",
"Device",
",",
"self",
")",
".",
"sense_ttb",
"(",
"target",
",",
"did",
"=",
"b'\\x01'",
")"
] | Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106
kbps. For a Type 4B Tag the firmware automatically sends an
ATTRIB command that configures the use of DID and 64 byte
maximum frame size. The driver reverts this configuration with
a DESELECT and WUPB command to return the target prepared for
activation (which nfcpy does in the tag activation code). | [
"Activate",
"the",
"RF",
"field",
"and",
"probe",
"for",
"a",
"Type",
"B",
"Target",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L231-L242 | train | 222,222 |
nfcpy/nfcpy | src/nfc/clf/rcs956.py | Device.sense_dep | def sense_dep(self, target):
"""Search for a DEP Target in active or passive communication mode.
"""
# Set timeout for PSL_RES and ATR_RES
self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A")
return super(Device, self).sense_dep(target) | python | def sense_dep(self, target):
"""Search for a DEP Target in active or passive communication mode.
"""
# Set timeout for PSL_RES and ATR_RES
self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A")
return super(Device, self).sense_dep(target) | [
"def",
"sense_dep",
"(",
"self",
",",
"target",
")",
":",
"# Set timeout for PSL_RES and ATR_RES",
"self",
".",
"chipset",
".",
"rf_configuration",
"(",
"0x02",
",",
"b\"\\x0B\\x0B\\x0A\"",
")",
"return",
"super",
"(",
"Device",
",",
"self",
")",
".",
"sense_dep... | Search for a DEP Target in active or passive communication mode. | [
"Search",
"for",
"a",
"DEP",
"Target",
"in",
"active",
"or",
"passive",
"communication",
"mode",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L250-L256 | train | 222,223 |
nfcpy/nfcpy | src/nfc/handover/client.py | HandoverClient.send | def send(self, message):
"""Send a handover request message to the remote server."""
log.debug("sending '{0}' message".format(message.type))
send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU)
try:
data = str(message)
except nfc.llcp.EncodeError as e:
log.error("message encoding failed: {0}".format(e))
else:
return self._send(data, send_miu) | python | def send(self, message):
"""Send a handover request message to the remote server."""
log.debug("sending '{0}' message".format(message.type))
send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU)
try:
data = str(message)
except nfc.llcp.EncodeError as e:
log.error("message encoding failed: {0}".format(e))
else:
return self._send(data, send_miu) | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"log",
".",
"debug",
"(",
"\"sending '{0}' message\"",
".",
"format",
"(",
"message",
".",
"type",
")",
")",
"send_miu",
"=",
"self",
".",
"socket",
".",
"getsockopt",
"(",
"nfc",
".",
"llcp",
".",
... | Send a handover request message to the remote server. | [
"Send",
"a",
"handover",
"request",
"message",
"to",
"the",
"remote",
"server",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/handover/client.py#L59-L68 | train | 222,224 |
nfcpy/nfcpy | src/nfc/handover/client.py | HandoverClient.recv | def recv(self, timeout=None):
"""Receive a handover select message from the remote server."""
message = self._recv(timeout)
if message and message.type == "urn:nfc:wkt:Hs":
log.debug("received '{0}' message".format(message.type))
return nfc.ndef.HandoverSelectMessage(message)
else:
log.error("received invalid message type {0}".format(message.type))
return None | python | def recv(self, timeout=None):
"""Receive a handover select message from the remote server."""
message = self._recv(timeout)
if message and message.type == "urn:nfc:wkt:Hs":
log.debug("received '{0}' message".format(message.type))
return nfc.ndef.HandoverSelectMessage(message)
else:
log.error("received invalid message type {0}".format(message.type))
return None | [
"def",
"recv",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"message",
"=",
"self",
".",
"_recv",
"(",
"timeout",
")",
"if",
"message",
"and",
"message",
".",
"type",
"==",
"\"urn:nfc:wkt:Hs\"",
":",
"log",
".",
"debug",
"(",
"\"received '{0}' mes... | Receive a handover select message from the remote server. | [
"Receive",
"a",
"handover",
"select",
"message",
"from",
"the",
"remote",
"server",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/handover/client.py#L78-L86 | train | 222,225 |
nfcpy/nfcpy | src/nfc/clf/pn531.py | Device.sense_ttb | def sense_ttb(self, target):
"""Sense for a Type B Target is not supported."""
info = "{device} does not support sense for Type B Target"
raise nfc.clf.UnsupportedTargetError(info.format(device=self)) | python | def sense_ttb(self, target):
"""Sense for a Type B Target is not supported."""
info = "{device} does not support sense for Type B Target"
raise nfc.clf.UnsupportedTargetError(info.format(device=self)) | [
"def",
"sense_ttb",
"(",
"self",
",",
"target",
")",
":",
"info",
"=",
"\"{device} does not support sense for Type B Target\"",
"raise",
"nfc",
".",
"clf",
".",
"UnsupportedTargetError",
"(",
"info",
".",
"format",
"(",
"device",
"=",
"self",
")",
")"
] | Sense for a Type B Target is not supported. | [
"Sense",
"for",
"a",
"Type",
"B",
"Target",
"is",
"not",
"supported",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/pn531.py#L231-L234 | train | 222,226 |
nfcpy/nfcpy | src/nfc/clf/pn531.py | Device.sense_dep | def sense_dep(self, target):
"""Search for a DEP Target in active communication mode.
Because the PN531 does not implement the extended frame syntax
for host controller communication, it can not support the
maximum payload size of 254 byte. The driver handles this by
modifying the length-reduction values in atr_req and atr_res.
"""
if target.atr_req[15] & 0x30 == 0x30:
self.log.warning("must reduce the max payload size in atr_req")
target.atr_req[15] = (target.atr_req[15] & 0xCF) | 0x20
target = super(Device, self).sense_dep(target)
if target is None:
return
if target.atr_res[16] & 0x30 == 0x30:
self.log.warning("must reduce the max payload size in atr_res")
target.atr_res[16] = (target.atr_res[16] & 0xCF) | 0x20
return target | python | def sense_dep(self, target):
"""Search for a DEP Target in active communication mode.
Because the PN531 does not implement the extended frame syntax
for host controller communication, it can not support the
maximum payload size of 254 byte. The driver handles this by
modifying the length-reduction values in atr_req and atr_res.
"""
if target.atr_req[15] & 0x30 == 0x30:
self.log.warning("must reduce the max payload size in atr_req")
target.atr_req[15] = (target.atr_req[15] & 0xCF) | 0x20
target = super(Device, self).sense_dep(target)
if target is None:
return
if target.atr_res[16] & 0x30 == 0x30:
self.log.warning("must reduce the max payload size in atr_res")
target.atr_res[16] = (target.atr_res[16] & 0xCF) | 0x20
return target | [
"def",
"sense_dep",
"(",
"self",
",",
"target",
")",
":",
"if",
"target",
".",
"atr_req",
"[",
"15",
"]",
"&",
"0x30",
"==",
"0x30",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"must reduce the max payload size in atr_req\"",
")",
"target",
".",
"atr_r... | Search for a DEP Target in active communication mode.
Because the PN531 does not implement the extended frame syntax
for host controller communication, it can not support the
maximum payload size of 254 byte. The driver handles this by
modifying the length-reduction values in atr_req and atr_res. | [
"Search",
"for",
"a",
"DEP",
"Target",
"in",
"active",
"communication",
"mode",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/pn531.py#L242-L263 | train | 222,227 |
nfcpy/nfcpy | src/nfc/tag/tt2_nxp.py | NTAG203.protect | def protect(self, password=None, read_protect=False, protect_from=0):
"""Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be reset). If valid NDEF
management data is found in page 4, protect() also sets the
NDEF write flag to read-only.
The NTAG203 can not be password protected. If a *password*
argument is provided, the protect() method always returns
False.
"""
return super(NTAG203, self).protect(
password, read_protect, protect_from) | python | def protect(self, password=None, read_protect=False, protect_from=0):
"""Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be reset). If valid NDEF
management data is found in page 4, protect() also sets the
NDEF write flag to read-only.
The NTAG203 can not be password protected. If a *password*
argument is provided, the protect() method always returns
False.
"""
return super(NTAG203, self).protect(
password, read_protect, protect_from) | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"return",
"super",
"(",
"NTAG203",
",",
"self",
")",
".",
"protect",
"(",
"password",
",",
"read_protect",
",",
"pr... | Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be reset). If valid NDEF
management data is found in page 4, protect() also sets the
NDEF write flag to read-only.
The NTAG203 can not be password protected. If a *password*
argument is provided, the protect() method always returns
False. | [
"Set",
"lock",
"bits",
"to",
"disable",
"future",
"memory",
"modifications",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L268-L283 | train | 222,228 |
nfcpy/nfcpy | src/nfc/tag/tt2_nxp.py | NTAG21x.signature | def signature(self):
"""The 32-byte ECC tag signature programmed at chip production. The
signature is provided as a string and can only be read.
The signature attribute is always loaded from the tag when it
is accessed, i.e. it is not cached. If communication with the
tag fails for some reason the signature attribute is set to a
32-byte string of all zeros.
"""
log.debug("read tag signature")
try:
return bytes(self.transceive(b"\x3C\x00"))
except tt2.Type2TagCommandError:
return 32 * b"\0" | python | def signature(self):
"""The 32-byte ECC tag signature programmed at chip production. The
signature is provided as a string and can only be read.
The signature attribute is always loaded from the tag when it
is accessed, i.e. it is not cached. If communication with the
tag fails for some reason the signature attribute is set to a
32-byte string of all zeros.
"""
log.debug("read tag signature")
try:
return bytes(self.transceive(b"\x3C\x00"))
except tt2.Type2TagCommandError:
return 32 * b"\0" | [
"def",
"signature",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"read tag signature\"",
")",
"try",
":",
"return",
"bytes",
"(",
"self",
".",
"transceive",
"(",
"b\"\\x3C\\x00\"",
")",
")",
"except",
"tt2",
".",
"Type2TagCommandError",
":",
"return",
... | The 32-byte ECC tag signature programmed at chip production. The
signature is provided as a string and can only be read.
The signature attribute is always loaded from the tag when it
is accessed, i.e. it is not cached. If communication with the
tag fails for some reason the signature attribute is set to a
32-byte string of all zeros. | [
"The",
"32",
"-",
"byte",
"ECC",
"tag",
"signature",
"programmed",
"at",
"chip",
"production",
".",
"The",
"signature",
"is",
"provided",
"as",
"a",
"string",
"and",
"can",
"only",
"be",
"read",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L330-L344 | train | 222,229 |
nfcpy/nfcpy | src/nfc/tag/tt2_nxp.py | NTAG21x.protect | def protect(self, password=None, read_protect=False, protect_from=0):
"""Set password protection or permanent lock bits.
If the *password* argument is None, all memory pages will be
protected by setting the relevant lock bits (note that lock
bits can not be reset). If valid NDEF management data is
found, protect() also sets the NDEF write flag to read-only.
All Tags of the NTAG21x family can alternatively be protected
by password. If a *password* argument is provided, the
protect() method writes the first 4 byte of the *password*
string into the Tag's password (PWD) memory bytes and the
following 2 byte of the *password* string into the password
acknowledge (PACK) memory bytes. Factory default values are
used if the *password* argument is an empty string. Lock bits
are not set for password protection.
The *read_protect* and *protect_from* arguments are only
evaluated if *password* is not None. If *read_protect* is
True, the memory protection bit (PROT) is set to require
password verification also for reading of protected memory
pages. The value of *protect_from* determines the first
password protected memory page (one page is 4 byte) with the
exception that the smallest set value is page 3 even if
*protect_from* is smaller.
"""
args = (password, read_protect, protect_from)
return super(NTAG21x, self).protect(*args) | python | def protect(self, password=None, read_protect=False, protect_from=0):
"""Set password protection or permanent lock bits.
If the *password* argument is None, all memory pages will be
protected by setting the relevant lock bits (note that lock
bits can not be reset). If valid NDEF management data is
found, protect() also sets the NDEF write flag to read-only.
All Tags of the NTAG21x family can alternatively be protected
by password. If a *password* argument is provided, the
protect() method writes the first 4 byte of the *password*
string into the Tag's password (PWD) memory bytes and the
following 2 byte of the *password* string into the password
acknowledge (PACK) memory bytes. Factory default values are
used if the *password* argument is an empty string. Lock bits
are not set for password protection.
The *read_protect* and *protect_from* arguments are only
evaluated if *password* is not None. If *read_protect* is
True, the memory protection bit (PROT) is set to require
password verification also for reading of protected memory
pages. The value of *protect_from* determines the first
password protected memory page (one page is 4 byte) with the
exception that the smallest set value is page 3 even if
*protect_from* is smaller.
"""
args = (password, read_protect, protect_from)
return super(NTAG21x, self).protect(*args) | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"args",
"=",
"(",
"password",
",",
"read_protect",
",",
"protect_from",
")",
"return",
"super",
"(",
"NTAG21x",
",",
... | Set password protection or permanent lock bits.
If the *password* argument is None, all memory pages will be
protected by setting the relevant lock bits (note that lock
bits can not be reset). If valid NDEF management data is
found, protect() also sets the NDEF write flag to read-only.
All Tags of the NTAG21x family can alternatively be protected
by password. If a *password* argument is provided, the
protect() method writes the first 4 byte of the *password*
string into the Tag's password (PWD) memory bytes and the
following 2 byte of the *password* string into the password
acknowledge (PACK) memory bytes. Factory default values are
used if the *password* argument is an empty string. Lock bits
are not set for password protection.
The *read_protect* and *protect_from* arguments are only
evaluated if *password* is not None. If *read_protect* is
True, the memory protection bit (PROT) is set to require
password verification also for reading of protected memory
pages. The value of *protect_from* determines the first
password protected memory page (one page is 4 byte) with the
exception that the smallest set value is page 3 even if
*protect_from* is smaller. | [
"Set",
"password",
"protection",
"or",
"permanent",
"lock",
"bits",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2_nxp.py#L346-L374 | train | 222,230 |
nfcpy/nfcpy | src/nfc/clf/device.py | Device.mute | def mute(self):
"""Mutes all existing communication, most notably the device will no
longer generate a 13.56 MHz carrier signal when operating as
Initiator.
"""
fname = "mute"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | python | def mute(self):
"""Mutes all existing communication, most notably the device will no
longer generate a 13.56 MHz carrier signal when operating as
Initiator.
"""
fname = "mute"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | [
"def",
"mute",
"(",
"self",
")",
":",
"fname",
"=",
"\"mute\"",
"cname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"NotImplementedError",
"(",
"\"%s.%s() is required\"",
"%",
"(",
... | Mutes all existing communication, most notably the device will no
longer generate a 13.56 MHz carrier signal when operating as
Initiator. | [
"Mutes",
"all",
"existing",
"communication",
"most",
"notably",
"the",
"device",
"will",
"no",
"longer",
"generate",
"a",
"13",
".",
"56",
"MHz",
"carrier",
"signal",
"when",
"operating",
"as",
"Initiator",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L174-L182 | train | 222,231 |
nfcpy/nfcpy | src/nfc/clf/device.py | Device.listen_tta | def listen_tta(self, target, timeout):
"""Listen as Type A Target.
Waits to receive a SENS_REQ command at the bitrate set by
**target.brty** and sends the **target.sens_res**
response. Depending on the SENS_RES bytes, the Initiator then
sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ
and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are
then generated from the **rid_res** or **sdd_res** and
**sel_res** attributes in *target*.
Note that none of the currently supported hardware can
actually receive an RID_CMD, thus Type 1 Tag emulation is
impossible.
Arguments:
target (nfc.clf.LocalTarget): Supplies bitrate and mandatory
response data to reply when being discovered.
timeout (float): The maximum number of seconds to wait for a
discovery command.
Returns:
nfc.clf.LocalTarget: Command data received from the remote
Initiator if being discovered and to the extent supported
by the device. The first command received after discovery
is returned as one of the **tt1_cmd**, **tt2_cmd** or
**tt4_cmd** attribute (note that unset attributes are
always None).
Raises:
nfc.clf.UnsupportedTargetError: The method is not supported
or the *target* argument requested an unsupported bitrate
(or has a wrong technology type identifier).
~exceptions.ValueError: A required target response attribute
is not present or does not supply the number of bytes
expected.
"""
fname = "listen_tta"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | python | def listen_tta(self, target, timeout):
"""Listen as Type A Target.
Waits to receive a SENS_REQ command at the bitrate set by
**target.brty** and sends the **target.sens_res**
response. Depending on the SENS_RES bytes, the Initiator then
sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ
and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are
then generated from the **rid_res** or **sdd_res** and
**sel_res** attributes in *target*.
Note that none of the currently supported hardware can
actually receive an RID_CMD, thus Type 1 Tag emulation is
impossible.
Arguments:
target (nfc.clf.LocalTarget): Supplies bitrate and mandatory
response data to reply when being discovered.
timeout (float): The maximum number of seconds to wait for a
discovery command.
Returns:
nfc.clf.LocalTarget: Command data received from the remote
Initiator if being discovered and to the extent supported
by the device. The first command received after discovery
is returned as one of the **tt1_cmd**, **tt2_cmd** or
**tt4_cmd** attribute (note that unset attributes are
always None).
Raises:
nfc.clf.UnsupportedTargetError: The method is not supported
or the *target* argument requested an unsupported bitrate
(or has a wrong technology type identifier).
~exceptions.ValueError: A required target response attribute
is not present or does not supply the number of bytes
expected.
"""
fname = "listen_tta"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | [
"def",
"listen_tta",
"(",
"self",
",",
"target",
",",
"timeout",
")",
":",
"fname",
"=",
"\"listen_tta\"",
"cname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"NotImplementedError",
... | Listen as Type A Target.
Waits to receive a SENS_REQ command at the bitrate set by
**target.brty** and sends the **target.sens_res**
response. Depending on the SENS_RES bytes, the Initiator then
sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ
and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are
then generated from the **rid_res** or **sdd_res** and
**sel_res** attributes in *target*.
Note that none of the currently supported hardware can
actually receive an RID_CMD, thus Type 1 Tag emulation is
impossible.
Arguments:
target (nfc.clf.LocalTarget): Supplies bitrate and mandatory
response data to reply when being discovered.
timeout (float): The maximum number of seconds to wait for a
discovery command.
Returns:
nfc.clf.LocalTarget: Command data received from the remote
Initiator if being discovered and to the extent supported
by the device. The first command received after discovery
is returned as one of the **tt1_cmd**, **tt2_cmd** or
**tt4_cmd** attribute (note that unset attributes are
always None).
Raises:
nfc.clf.UnsupportedTargetError: The method is not supported
or the *target* argument requested an unsupported bitrate
(or has a wrong technology type identifier).
~exceptions.ValueError: A required target response attribute
is not present or does not supply the number of bytes
expected. | [
"Listen",
"as",
"Type",
"A",
"Target",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L324-L369 | train | 222,232 |
nfcpy/nfcpy | src/nfc/clf/device.py | Device.send_cmd_recv_rsp | def send_cmd_recv_rsp(self, target, data, timeout):
"""Exchange data with a remote Target
Sends command *data* to the remote *target* discovered in the
most recent call to one of the sense_xxx() methods. Note that
*target* becomes invalid with any call to mute(), sense_xxx()
or listen_xxx()
Arguments:
target (nfc.clf.RemoteTarget): The target returned by the
last successful call of a sense_xxx() method.
data (bytearray): The binary data to send to the remote
device.
timeout (float): The maximum number of seconds to wait for
response data from the remote device.
Returns:
bytearray: Response data received from the remote device.
Raises:
nfc.clf.CommunicationError: When no data was received.
"""
fname = "send_cmd_recv_rsp"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | python | def send_cmd_recv_rsp(self, target, data, timeout):
"""Exchange data with a remote Target
Sends command *data* to the remote *target* discovered in the
most recent call to one of the sense_xxx() methods. Note that
*target* becomes invalid with any call to mute(), sense_xxx()
or listen_xxx()
Arguments:
target (nfc.clf.RemoteTarget): The target returned by the
last successful call of a sense_xxx() method.
data (bytearray): The binary data to send to the remote
device.
timeout (float): The maximum number of seconds to wait for
response data from the remote device.
Returns:
bytearray: Response data received from the remote device.
Raises:
nfc.clf.CommunicationError: When no data was received.
"""
fname = "send_cmd_recv_rsp"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | [
"def",
"send_cmd_recv_rsp",
"(",
"self",
",",
"target",
",",
"data",
",",
"timeout",
")",
":",
"fname",
"=",
"\"send_cmd_recv_rsp\"",
"cname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"ra... | Exchange data with a remote Target
Sends command *data* to the remote *target* discovered in the
most recent call to one of the sense_xxx() methods. Note that
*target* becomes invalid with any call to mute(), sense_xxx()
or listen_xxx()
Arguments:
target (nfc.clf.RemoteTarget): The target returned by the
last successful call of a sense_xxx() method.
data (bytearray): The binary data to send to the remote
device.
timeout (float): The maximum number of seconds to wait for
response data from the remote device.
Returns:
bytearray: Response data received from the remote device.
Raises:
nfc.clf.CommunicationError: When no data was received. | [
"Exchange",
"data",
"with",
"a",
"remote",
"Target"
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L496-L526 | train | 222,233 |
nfcpy/nfcpy | src/nfc/clf/device.py | Device.get_max_recv_data_size | def get_max_recv_data_size(self, target):
"""Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with
either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`.
The value reflects the local device capabilities for receiving
in the mode determined by *target*. It does not relate to any
protocol capabilities and negotiations.
Arguments:
target (nfc.clf.Target): The current local or remote
communication target.
Returns:
int: Maximum number of data bytes supported for receiving.
"""
fname = "get_max_recv_data_size"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | python | def get_max_recv_data_size(self, target):
"""Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with
either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`.
The value reflects the local device capabilities for receiving
in the mode determined by *target*. It does not relate to any
protocol capabilities and negotiations.
Arguments:
target (nfc.clf.Target): The current local or remote
communication target.
Returns:
int: Maximum number of data bytes supported for receiving.
"""
fname = "get_max_recv_data_size"
cname = self.__class__.__module__ + '.' + self.__class__.__name__
raise NotImplementedError("%s.%s() is required" % (cname, fname)) | [
"def",
"get_max_recv_data_size",
"(",
"self",
",",
"target",
")",
":",
"fname",
"=",
"\"get_max_recv_data_size\"",
"cname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"NotImplementedErro... | Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with
either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`.
The value reflects the local device capabilities for receiving
in the mode determined by *target*. It does not relate to any
protocol capabilities and negotiations.
Arguments:
target (nfc.clf.Target): The current local or remote
communication target.
Returns:
int: Maximum number of data bytes supported for receiving. | [
"Returns",
"the",
"maximum",
"number",
"of",
"data",
"bytes",
"for",
"receiving",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/device.py#L583-L604 | train | 222,234 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.format | def format(self, version=None, wipe=None):
"""Erase the NDEF message on a Type 2 Tag.
The :meth:`format` method will reset the length of the NDEF
message on a type 2 tag to zero, thus the tag will appear to
be empty. Additionally, if the *wipe* argument is set to some
integer then :meth:`format` will overwrite all user date that
follows the NDEF message TLV with that integer (mod 256). If
an NDEF message TLV is not present it will be created with a
length of zero.
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible. This is because the user
data are of a type 2 tag can not be safely determined, also
reading all memory pages until an error response yields only
the total memory size which includes an undetermined number of
special pages at the end of memory.
It is also not possible to change the NDEF mapping version,
located in a one-time-programmable area of the tag memory.
"""
return super(Type2Tag, self).format(version, wipe) | python | def format(self, version=None, wipe=None):
"""Erase the NDEF message on a Type 2 Tag.
The :meth:`format` method will reset the length of the NDEF
message on a type 2 tag to zero, thus the tag will appear to
be empty. Additionally, if the *wipe* argument is set to some
integer then :meth:`format` will overwrite all user date that
follows the NDEF message TLV with that integer (mod 256). If
an NDEF message TLV is not present it will be created with a
length of zero.
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible. This is because the user
data are of a type 2 tag can not be safely determined, also
reading all memory pages until an error response yields only
the total memory size which includes an undetermined number of
special pages at the end of memory.
It is also not possible to change the NDEF mapping version,
located in a one-time-programmable area of the tag memory.
"""
return super(Type2Tag, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"Type2Tag",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Erase the NDEF message on a Type 2 Tag.
The :meth:`format` method will reset the length of the NDEF
message on a type 2 tag to zero, thus the tag will appear to
be empty. Additionally, if the *wipe* argument is set to some
integer then :meth:`format` will overwrite all user date that
follows the NDEF message TLV with that integer (mod 256). If
an NDEF message TLV is not present it will be created with a
length of zero.
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible. This is because the user
data are of a type 2 tag can not be safely determined, also
reading all memory pages until an error response yields only
the total memory size which includes an undetermined number of
special pages at the end of memory.
It is also not possible to change the NDEF mapping version,
located in a one-time-programmable area of the tag memory. | [
"Erase",
"the",
"NDEF",
"message",
"on",
"a",
"Type",
"2",
"Tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L346-L368 | train | 222,235 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.protect | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect the tag against write access, i.e. make it read-only.
:meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to
read-only state by setting all lock bits to 1. This operation
can not be reversed. If the tag is not an NFC Forum Tag,
i.e. it is not formatted with an NDEF Capability Container,
the :meth:`protect` method simply returns :const:`False`.
A generic Type 2 Tag can not be protected with a password. If
the *password* argument is provided, the :meth:`protect`
method does nothing else than return :const:`False`. The
*read_protect* and *protect_from* arguments are safely
ignored.
"""
return super(Type2Tag, self).protect(
password, read_protect, protect_from) | python | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect the tag against write access, i.e. make it read-only.
:meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to
read-only state by setting all lock bits to 1. This operation
can not be reversed. If the tag is not an NFC Forum Tag,
i.e. it is not formatted with an NDEF Capability Container,
the :meth:`protect` method simply returns :const:`False`.
A generic Type 2 Tag can not be protected with a password. If
the *password* argument is provided, the :meth:`protect`
method does nothing else than return :const:`False`. The
*read_protect* and *protect_from* arguments are safely
ignored.
"""
return super(Type2Tag, self).protect(
password, read_protect, protect_from) | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"return",
"super",
"(",
"Type2Tag",
",",
"self",
")",
".",
"protect",
"(",
"password",
",",
"read_protect",
",",
"p... | Protect the tag against write access, i.e. make it read-only.
:meth:`Type2Tag.protect` switches an NFC Forum Type 2 Tag to
read-only state by setting all lock bits to 1. This operation
can not be reversed. If the tag is not an NFC Forum Tag,
i.e. it is not formatted with an NDEF Capability Container,
the :meth:`protect` method simply returns :const:`False`.
A generic Type 2 Tag can not be protected with a password. If
the *password* argument is provided, the :meth:`protect`
method does nothing else than return :const:`False`. The
*read_protect* and *protect_from* arguments are safely
ignored. | [
"Protect",
"the",
"tag",
"against",
"write",
"access",
"i",
".",
"e",
".",
"make",
"it",
"read",
"-",
"only",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L385-L402 | train | 222,236 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.read | def read(self, page):
"""Send a READ command to retrieve data from the tag.
The *page* argument specifies the offset in multiples of 4
bytes (i.e. page number 1 will return bytes 4 to 19). The data
returned is a byte array of length 16 or None if the block is
outside the readable memory range.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
log.debug("read pages {0} to {1}".format(page, page+3))
data = self.transceive("\x30"+chr(page % 256), timeout=0.005)
if len(data) == 1 and data[0] & 0xFA == 0x00:
log.debug("received nak response")
self.target.sel_req = self.target.sdd_res[:]
self._target = self.clf.sense(self.target)
raise Type2TagCommandError(
INVALID_PAGE_ERROR if self.target else nfc.tag.RECEIVE_ERROR)
if len(data) != 16:
log.debug("invalid response " + hexlify(data))
raise Type2TagCommandError(INVALID_RESPONSE_ERROR)
return data | python | def read(self, page):
"""Send a READ command to retrieve data from the tag.
The *page* argument specifies the offset in multiples of 4
bytes (i.e. page number 1 will return bytes 4 to 19). The data
returned is a byte array of length 16 or None if the block is
outside the readable memory range.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
log.debug("read pages {0} to {1}".format(page, page+3))
data = self.transceive("\x30"+chr(page % 256), timeout=0.005)
if len(data) == 1 and data[0] & 0xFA == 0x00:
log.debug("received nak response")
self.target.sel_req = self.target.sdd_res[:]
self._target = self.clf.sense(self.target)
raise Type2TagCommandError(
INVALID_PAGE_ERROR if self.target else nfc.tag.RECEIVE_ERROR)
if len(data) != 16:
log.debug("invalid response " + hexlify(data))
raise Type2TagCommandError(INVALID_RESPONSE_ERROR)
return data | [
"def",
"read",
"(",
"self",
",",
"page",
")",
":",
"log",
".",
"debug",
"(",
"\"read pages {0} to {1}\"",
".",
"format",
"(",
"page",
",",
"page",
"+",
"3",
")",
")",
"data",
"=",
"self",
".",
"transceive",
"(",
"\"\\x30\"",
"+",
"chr",
"(",
"page",
... | Send a READ command to retrieve data from the tag.
The *page* argument specifies the offset in multiples of 4
bytes (i.e. page number 1 will return bytes 4 to 19). The data
returned is a byte array of length 16 or None if the block is
outside the readable memory range.
Command execution errors raise :exc:`Type2TagCommandError`. | [
"Send",
"a",
"READ",
"command",
"to",
"retrieve",
"data",
"from",
"the",
"tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L468-L494 | train | 222,237 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.write | def write(self, page, data):
"""Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
if len(data) != 4:
raise ValueError("data must be a four byte string or array")
log.debug("write {0} to page {1}".format(hexlify(data), page))
rsp = self.transceive("\xA2" + chr(page % 256) + data)
if len(rsp) != 1:
log.debug("invalid response " + hexlify(data))
raise Type2TagCommandError(INVALID_RESPONSE_ERROR)
if rsp[0] != 0x0A: # NAK
log.debug("invalid page, received nak")
raise Type2TagCommandError(INVALID_PAGE_ERROR)
return True | python | def write(self, page, data):
"""Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
if len(data) != 4:
raise ValueError("data must be a four byte string or array")
log.debug("write {0} to page {1}".format(hexlify(data), page))
rsp = self.transceive("\xA2" + chr(page % 256) + data)
if len(rsp) != 1:
log.debug("invalid response " + hexlify(data))
raise Type2TagCommandError(INVALID_RESPONSE_ERROR)
if rsp[0] != 0x0A: # NAK
log.debug("invalid page, received nak")
raise Type2TagCommandError(INVALID_PAGE_ERROR)
return True | [
"def",
"write",
"(",
"self",
",",
"page",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"data must be a four byte string or array\"",
")",
"log",
".",
"debug",
"(",
"\"write {0} to page {1}\"",
".",
"form... | Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2TagCommandError`. | [
"Send",
"a",
"WRITE",
"command",
"to",
"store",
"data",
"on",
"the",
"tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L496-L520 | train | 222,238 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.sector_select | def sector_select(self, sector):
"""Send a SECTOR_SELECT command to switch the 1K address sector.
The command is only send to the tag if the *sector* number is
different from the currently selected sector number (set to 0
when the tag instance is created). If the command was
successful, the currently selected sector number is updated
and further :meth:`read` and :meth:`write` commands will be
relative to that sector.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
if sector != self._current_sector:
log.debug("select sector {0} (pages {1} to {2})".format(
sector, sector << 10, ((sector+1) << 8) - 1))
sector_select_1 = b'\xC2\xFF'
sector_select_2 = pack('Bxxx', sector)
rsp = self.transceive(sector_select_1)
if len(rsp) == 1 and rsp[0] == 0x0A:
try:
# command is passively ack'd, i.e. there's no response
# and we must make sure there's no retries attempted
self.transceive(sector_select_2, timeout=0.001, retries=0)
except Type2TagCommandError as error:
assert int(error) == TIMEOUT_ERROR # passive ack
else:
log.debug("sector {0} does not exist".format(sector))
raise Type2TagCommandError(INVALID_SECTOR_ERROR)
else:
log.debug("sector select is not supported for this tag")
raise Type2TagCommandError(INVALID_SECTOR_ERROR)
log.debug("sector {0} is now selected".format(sector))
self._current_sector = sector
return self._current_sector | python | def sector_select(self, sector):
"""Send a SECTOR_SELECT command to switch the 1K address sector.
The command is only send to the tag if the *sector* number is
different from the currently selected sector number (set to 0
when the tag instance is created). If the command was
successful, the currently selected sector number is updated
and further :meth:`read` and :meth:`write` commands will be
relative to that sector.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
if sector != self._current_sector:
log.debug("select sector {0} (pages {1} to {2})".format(
sector, sector << 10, ((sector+1) << 8) - 1))
sector_select_1 = b'\xC2\xFF'
sector_select_2 = pack('Bxxx', sector)
rsp = self.transceive(sector_select_1)
if len(rsp) == 1 and rsp[0] == 0x0A:
try:
# command is passively ack'd, i.e. there's no response
# and we must make sure there's no retries attempted
self.transceive(sector_select_2, timeout=0.001, retries=0)
except Type2TagCommandError as error:
assert int(error) == TIMEOUT_ERROR # passive ack
else:
log.debug("sector {0} does not exist".format(sector))
raise Type2TagCommandError(INVALID_SECTOR_ERROR)
else:
log.debug("sector select is not supported for this tag")
raise Type2TagCommandError(INVALID_SECTOR_ERROR)
log.debug("sector {0} is now selected".format(sector))
self._current_sector = sector
return self._current_sector | [
"def",
"sector_select",
"(",
"self",
",",
"sector",
")",
":",
"if",
"sector",
"!=",
"self",
".",
"_current_sector",
":",
"log",
".",
"debug",
"(",
"\"select sector {0} (pages {1} to {2})\"",
".",
"format",
"(",
"sector",
",",
"sector",
"<<",
"10",
",",
"(",
... | Send a SECTOR_SELECT command to switch the 1K address sector.
The command is only send to the tag if the *sector* number is
different from the currently selected sector number (set to 0
when the tag instance is created). If the command was
successful, the currently selected sector number is updated
and further :meth:`read` and :meth:`write` commands will be
relative to that sector.
Command execution errors raise :exc:`Type2TagCommandError`. | [
"Send",
"a",
"SECTOR_SELECT",
"command",
"to",
"switch",
"the",
"1K",
"address",
"sector",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L522-L559 | train | 222,239 |
nfcpy/nfcpy | src/nfc/tag/tt2.py | Type2Tag.transceive | def transceive(self, data, timeout=0.1, retries=2):
"""Send a Type 2 Tag command and receive the response.
:meth:`transceive` is a type 2 tag specific wrapper around the
:meth:`nfc.ContactlessFrontend.exchange` method. It can be
used to send custom commands as a sequence of *data* bytes to
the tag and receive the response data bytes. If *timeout*
seconds pass without a response, the operation is aborted and
:exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR
error code.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
log.debug(">> {0} ({1:f}s)".format(hexlify(data), timeout))
if not self.target:
# Sometimes we have to (re)sense the target during
# communication. If that failed (tag gone) then any
# further attempt to transceive() is the same as
# "unrecoverable timeout error".
raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR)
started = time.time()
for retry in range(1 + retries):
try:
data = self.clf.exchange(data, timeout)
break
except nfc.clf.CommunicationError as error:
reason = error.__class__.__name__
log.debug("%s after %d retries" % (reason, retry))
else:
if type(error) is nfc.clf.TimeoutError:
raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR)
if type(error) is nfc.clf.TransmissionError:
raise Type2TagCommandError(nfc.tag.RECEIVE_ERROR)
if type(error) is nfc.clf.ProtocolError:
raise Type2TagCommandError(nfc.tag.PROTOCOL_ERROR)
raise RuntimeError("unexpected " + repr(error))
elapsed = time.time() - started
log.debug("<< {0} ({1:f}s)".format(hexlify(data), elapsed))
return data | python | def transceive(self, data, timeout=0.1, retries=2):
"""Send a Type 2 Tag command and receive the response.
:meth:`transceive` is a type 2 tag specific wrapper around the
:meth:`nfc.ContactlessFrontend.exchange` method. It can be
used to send custom commands as a sequence of *data* bytes to
the tag and receive the response data bytes. If *timeout*
seconds pass without a response, the operation is aborted and
:exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR
error code.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
log.debug(">> {0} ({1:f}s)".format(hexlify(data), timeout))
if not self.target:
# Sometimes we have to (re)sense the target during
# communication. If that failed (tag gone) then any
# further attempt to transceive() is the same as
# "unrecoverable timeout error".
raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR)
started = time.time()
for retry in range(1 + retries):
try:
data = self.clf.exchange(data, timeout)
break
except nfc.clf.CommunicationError as error:
reason = error.__class__.__name__
log.debug("%s after %d retries" % (reason, retry))
else:
if type(error) is nfc.clf.TimeoutError:
raise Type2TagCommandError(nfc.tag.TIMEOUT_ERROR)
if type(error) is nfc.clf.TransmissionError:
raise Type2TagCommandError(nfc.tag.RECEIVE_ERROR)
if type(error) is nfc.clf.ProtocolError:
raise Type2TagCommandError(nfc.tag.PROTOCOL_ERROR)
raise RuntimeError("unexpected " + repr(error))
elapsed = time.time() - started
log.debug("<< {0} ({1:f}s)".format(hexlify(data), elapsed))
return data | [
"def",
"transceive",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"0.1",
",",
"retries",
"=",
"2",
")",
":",
"log",
".",
"debug",
"(",
"\">> {0} ({1:f}s)\"",
".",
"format",
"(",
"hexlify",
"(",
"data",
")",
",",
"timeout",
")",
")",
"if",
"not",
... | Send a Type 2 Tag command and receive the response.
:meth:`transceive` is a type 2 tag specific wrapper around the
:meth:`nfc.ContactlessFrontend.exchange` method. It can be
used to send custom commands as a sequence of *data* bytes to
the tag and receive the response data bytes. If *timeout*
seconds pass without a response, the operation is aborted and
:exc:`~nfc.tag.TagCommandError` raised with the TIMEOUT_ERROR
error code.
Command execution errors raise :exc:`Type2TagCommandError`. | [
"Send",
"a",
"Type",
"2",
"Tag",
"command",
"and",
"receive",
"the",
"response",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt2.py#L561-L603 | train | 222,240 |
nfcpy/nfcpy | src/nfc/llcp/socket.py | Socket.setsockopt | def setsockopt(self, option, value):
"""Set the value of the given socket option and return the
current value which may have been corrected if it was out of
bounds."""
return self.llc.setsockopt(self._tco, option, value) | python | def setsockopt(self, option, value):
"""Set the value of the given socket option and return the
current value which may have been corrected if it was out of
bounds."""
return self.llc.setsockopt(self._tco, option, value) | [
"def",
"setsockopt",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"return",
"self",
".",
"llc",
".",
"setsockopt",
"(",
"self",
".",
"_tco",
",",
"option",
",",
"value",
")"
] | Set the value of the given socket option and return the
current value which may have been corrected if it was out of
bounds. | [
"Set",
"the",
"value",
"of",
"the",
"given",
"socket",
"option",
"and",
"return",
"the",
"current",
"value",
"which",
"may",
"have",
"been",
"corrected",
"if",
"it",
"was",
"out",
"of",
"bounds",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L64-L68 | train | 222,241 |
nfcpy/nfcpy | src/nfc/llcp/socket.py | Socket.accept | def accept(self):
"""Accept a connection. The socket must be bound to an address
and listening for connections. The return value is a new
socket object usable to send and receive data on the
connection."""
socket = Socket(self._llc, None)
socket._tco = self.llc.accept(self._tco)
return socket | python | def accept(self):
"""Accept a connection. The socket must be bound to an address
and listening for connections. The return value is a new
socket object usable to send and receive data on the
connection."""
socket = Socket(self._llc, None)
socket._tco = self.llc.accept(self._tco)
return socket | [
"def",
"accept",
"(",
"self",
")",
":",
"socket",
"=",
"Socket",
"(",
"self",
".",
"_llc",
",",
"None",
")",
"socket",
".",
"_tco",
"=",
"self",
".",
"llc",
".",
"accept",
"(",
"self",
".",
"_tco",
")",
"return",
"socket"
] | Accept a connection. The socket must be bound to an address
and listening for connections. The return value is a new
socket object usable to send and receive data on the
connection. | [
"Accept",
"a",
"connection",
".",
"The",
"socket",
"must",
"be",
"bound",
"to",
"an",
"address",
"and",
"listening",
"for",
"connections",
".",
"The",
"return",
"value",
"is",
"a",
"new",
"socket",
"object",
"usable",
"to",
"send",
"and",
"receive",
"data"... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L102-L109 | train | 222,242 |
nfcpy/nfcpy | src/nfc/llcp/socket.py | Socket.send | def send(self, data, flags=0):
"""Send data to the socket. The socket must be connected to a remote
socket. Returns a boolean value that indicates success or
failure. A false value is typically an indication that the
socket or connection was closed.
"""
return self.llc.send(self._tco, data, flags) | python | def send(self, data, flags=0):
"""Send data to the socket. The socket must be connected to a remote
socket. Returns a boolean value that indicates success or
failure. A false value is typically an indication that the
socket or connection was closed.
"""
return self.llc.send(self._tco, data, flags) | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"flags",
"=",
"0",
")",
":",
"return",
"self",
".",
"llc",
".",
"send",
"(",
"self",
".",
"_tco",
",",
"data",
",",
"flags",
")"
] | Send data to the socket. The socket must be connected to a remote
socket. Returns a boolean value that indicates success or
failure. A false value is typically an indication that the
socket or connection was closed. | [
"Send",
"data",
"to",
"the",
"socket",
".",
"The",
"socket",
"must",
"be",
"connected",
"to",
"a",
"remote",
"socket",
".",
"Returns",
"a",
"boolean",
"value",
"that",
"indicates",
"success",
"or",
"failure",
".",
"A",
"false",
"value",
"is",
"typically",
... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L111-L118 | train | 222,243 |
nfcpy/nfcpy | src/nfc/llcp/socket.py | Socket.sendto | def sendto(self, data, addr, flags=0):
"""Send data to the socket. The socket should not be connected
to a remote socket, since the destination socket is specified
by addr. Returns a boolean value that indicates success
or failure. Failure to send is generally an indication that
the socket was closed."""
return self.llc.sendto(self._tco, data, addr, flags) | python | def sendto(self, data, addr, flags=0):
"""Send data to the socket. The socket should not be connected
to a remote socket, since the destination socket is specified
by addr. Returns a boolean value that indicates success
or failure. Failure to send is generally an indication that
the socket was closed."""
return self.llc.sendto(self._tco, data, addr, flags) | [
"def",
"sendto",
"(",
"self",
",",
"data",
",",
"addr",
",",
"flags",
"=",
"0",
")",
":",
"return",
"self",
".",
"llc",
".",
"sendto",
"(",
"self",
".",
"_tco",
",",
"data",
",",
"addr",
",",
"flags",
")"
] | Send data to the socket. The socket should not be connected
to a remote socket, since the destination socket is specified
by addr. Returns a boolean value that indicates success
or failure. Failure to send is generally an indication that
the socket was closed. | [
"Send",
"data",
"to",
"the",
"socket",
".",
"The",
"socket",
"should",
"not",
"be",
"connected",
"to",
"a",
"remote",
"socket",
"since",
"the",
"destination",
"socket",
"is",
"specified",
"by",
"addr",
".",
"Returns",
"a",
"boolean",
"value",
"that",
"indi... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L120-L126 | train | 222,244 |
nfcpy/nfcpy | src/nfc/ndef/bt_record.py | BluetoothConfigRecord.simple_pairing_hash | def simple_pairing_hash(self):
"""Simple Pairing Hash C. Received and transmitted as EIR type
0x0E. Set to None if not received or not to be transmitted.
Raises nfc.ndef.DecodeError if the received value or
nfc.ndef.EncodeError if the assigned value is not a sequence
of 16 octets."""
try:
if len(self.eir[0x0E]) != 16:
raise DecodeError("wrong length of simple pairing hash")
return bytearray(self.eir[0x0E])
except KeyError:
return None | python | def simple_pairing_hash(self):
"""Simple Pairing Hash C. Received and transmitted as EIR type
0x0E. Set to None if not received or not to be transmitted.
Raises nfc.ndef.DecodeError if the received value or
nfc.ndef.EncodeError if the assigned value is not a sequence
of 16 octets."""
try:
if len(self.eir[0x0E]) != 16:
raise DecodeError("wrong length of simple pairing hash")
return bytearray(self.eir[0x0E])
except KeyError:
return None | [
"def",
"simple_pairing_hash",
"(",
"self",
")",
":",
"try",
":",
"if",
"len",
"(",
"self",
".",
"eir",
"[",
"0x0E",
"]",
")",
"!=",
"16",
":",
"raise",
"DecodeError",
"(",
"\"wrong length of simple pairing hash\"",
")",
"return",
"bytearray",
"(",
"self",
... | Simple Pairing Hash C. Received and transmitted as EIR type
0x0E. Set to None if not received or not to be transmitted.
Raises nfc.ndef.DecodeError if the received value or
nfc.ndef.EncodeError if the assigned value is not a sequence
of 16 octets. | [
"Simple",
"Pairing",
"Hash",
"C",
".",
"Received",
"and",
"transmitted",
"as",
"EIR",
"type",
"0x0E",
".",
"Set",
"to",
"None",
"if",
"not",
"received",
"or",
"not",
"to",
"be",
"transmitted",
".",
"Raises",
"nfc",
".",
"ndef",
".",
"DecodeError",
"if",
... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/bt_record.py#L101-L112 | train | 222,245 |
nfcpy/nfcpy | src/nfc/ndef/bt_record.py | BluetoothConfigRecord.simple_pairing_rand | def simple_pairing_rand(self):
"""Simple Pairing Randomizer R. Received and transmitted as
EIR type 0x0F. Set to None if not received or not to be
transmitted. Raises nfc.ndef.DecodeError if the received value
or nfc.ndef.EncodeError if the assigned value is not a
sequence of 16 octets."""
try:
if len(self.eir[0x0F]) != 16:
raise DecodeError("wrong length of simple pairing hash")
return bytearray(self.eir[0x0F])
except KeyError:
return None | python | def simple_pairing_rand(self):
"""Simple Pairing Randomizer R. Received and transmitted as
EIR type 0x0F. Set to None if not received or not to be
transmitted. Raises nfc.ndef.DecodeError if the received value
or nfc.ndef.EncodeError if the assigned value is not a
sequence of 16 octets."""
try:
if len(self.eir[0x0F]) != 16:
raise DecodeError("wrong length of simple pairing hash")
return bytearray(self.eir[0x0F])
except KeyError:
return None | [
"def",
"simple_pairing_rand",
"(",
"self",
")",
":",
"try",
":",
"if",
"len",
"(",
"self",
".",
"eir",
"[",
"0x0F",
"]",
")",
"!=",
"16",
":",
"raise",
"DecodeError",
"(",
"\"wrong length of simple pairing hash\"",
")",
"return",
"bytearray",
"(",
"self",
... | Simple Pairing Randomizer R. Received and transmitted as
EIR type 0x0F. Set to None if not received or not to be
transmitted. Raises nfc.ndef.DecodeError if the received value
or nfc.ndef.EncodeError if the assigned value is not a
sequence of 16 octets. | [
"Simple",
"Pairing",
"Randomizer",
"R",
".",
"Received",
"and",
"transmitted",
"as",
"EIR",
"type",
"0x0F",
".",
"Set",
"to",
"None",
"if",
"not",
"received",
"or",
"not",
"to",
"be",
"transmitted",
".",
"Raises",
"nfc",
".",
"ndef",
".",
"DecodeError",
... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/bt_record.py#L124-L135 | train | 222,246 |
nfcpy/nfcpy | src/nfc/ndef/handover.py | HandoverRequestMessage.add_carrier | def add_carrier(self, carrier_record, power_state, aux_data_records=None):
"""Add a new carrier to the handover request message.
:param carrier_record: a record providing carrier information
:param power_state: a string describing the carrier power state
:param aux_data_records: list of auxiliary data records
:type carrier_record: :class:`nfc.ndef.Record`
:type power_state: :class:`str`
:type aux_data_records: :class:`~nfc.ndef.record.RecordList`
>>> hr = nfc.ndef.HandoverRequestMessage(version="1.2")
>>> hr.add_carrier(some_carrier_record, "active")
"""
carrier = Carrier(carrier_record, power_state)
if aux_data_records is not None:
for aux in RecordList(aux_data_records):
carrier.auxiliary_data_records.append(aux)
self.carriers.append(carrier) | python | def add_carrier(self, carrier_record, power_state, aux_data_records=None):
"""Add a new carrier to the handover request message.
:param carrier_record: a record providing carrier information
:param power_state: a string describing the carrier power state
:param aux_data_records: list of auxiliary data records
:type carrier_record: :class:`nfc.ndef.Record`
:type power_state: :class:`str`
:type aux_data_records: :class:`~nfc.ndef.record.RecordList`
>>> hr = nfc.ndef.HandoverRequestMessage(version="1.2")
>>> hr.add_carrier(some_carrier_record, "active")
"""
carrier = Carrier(carrier_record, power_state)
if aux_data_records is not None:
for aux in RecordList(aux_data_records):
carrier.auxiliary_data_records.append(aux)
self.carriers.append(carrier) | [
"def",
"add_carrier",
"(",
"self",
",",
"carrier_record",
",",
"power_state",
",",
"aux_data_records",
"=",
"None",
")",
":",
"carrier",
"=",
"Carrier",
"(",
"carrier_record",
",",
"power_state",
")",
"if",
"aux_data_records",
"is",
"not",
"None",
":",
"for",
... | Add a new carrier to the handover request message.
:param carrier_record: a record providing carrier information
:param power_state: a string describing the carrier power state
:param aux_data_records: list of auxiliary data records
:type carrier_record: :class:`nfc.ndef.Record`
:type power_state: :class:`str`
:type aux_data_records: :class:`~nfc.ndef.record.RecordList`
>>> hr = nfc.ndef.HandoverRequestMessage(version="1.2")
>>> hr.add_carrier(some_carrier_record, "active") | [
"Add",
"a",
"new",
"carrier",
"to",
"the",
"handover",
"request",
"message",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/handover.py#L172-L189 | train | 222,247 |
nfcpy/nfcpy | src/nfc/ndef/handover.py | HandoverSelectMessage.pretty | def pretty(self, indent=0):
"""Returns a string with a formatted representation that might
be considered pretty-printable."""
indent = indent * ' '
lines = list()
version_string = "{v.major}.{v.minor}".format(v=self.version)
lines.append(("handover version", version_string))
if self.error.reason:
lines.append(("error reason", self.error.reason))
lines.append(("error value", self.error.value))
for index, carrier in enumerate(self.carriers):
lines.append(("carrier {0}:".format(index+1),))
lines.append((indent + "power state", carrier.power_state))
if carrier.record.type == "urn:nfc:wkt:Hc":
carrier_type = carrier.record.carrier_type
carrier_data = carrier.record.carrier_data
lines.append((indent + "carrier type", carrier_type))
lines.append((indent + "carrier data", repr(carrier_data)))
else:
if carrier.type == "application/vnd.bluetooth.ep.oob":
carrier_record = BluetoothConfigRecord(carrier.record)
elif carrier.type == "application/vnd.wfa.wsc":
carrier_record = WifiConfigRecord(carrier.record)
else:
carrier_record = carrier.record
lines.append((indent + "carrier type", carrier.type))
pretty_lines = carrier_record.pretty(2).split('\n')
lines.extend([tuple(l.split(' = ')) for l in pretty_lines
if not l.strip().startswith("identifier")])
for record in carrier.auxiliary_data_records:
lines.append((indent + "auxiliary data",))
lines.append((2*indent + "record type", record.type))
lines.append((2*indent + "record data", repr(record.data)))
lwidth = max([len(line[0]) for line in lines])
lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines]
lines = [" = ".join(line) for line in lines]
return ("\n").join([indent + line for line in lines]) | python | def pretty(self, indent=0):
"""Returns a string with a formatted representation that might
be considered pretty-printable."""
indent = indent * ' '
lines = list()
version_string = "{v.major}.{v.minor}".format(v=self.version)
lines.append(("handover version", version_string))
if self.error.reason:
lines.append(("error reason", self.error.reason))
lines.append(("error value", self.error.value))
for index, carrier in enumerate(self.carriers):
lines.append(("carrier {0}:".format(index+1),))
lines.append((indent + "power state", carrier.power_state))
if carrier.record.type == "urn:nfc:wkt:Hc":
carrier_type = carrier.record.carrier_type
carrier_data = carrier.record.carrier_data
lines.append((indent + "carrier type", carrier_type))
lines.append((indent + "carrier data", repr(carrier_data)))
else:
if carrier.type == "application/vnd.bluetooth.ep.oob":
carrier_record = BluetoothConfigRecord(carrier.record)
elif carrier.type == "application/vnd.wfa.wsc":
carrier_record = WifiConfigRecord(carrier.record)
else:
carrier_record = carrier.record
lines.append((indent + "carrier type", carrier.type))
pretty_lines = carrier_record.pretty(2).split('\n')
lines.extend([tuple(l.split(' = ')) for l in pretty_lines
if not l.strip().startswith("identifier")])
for record in carrier.auxiliary_data_records:
lines.append((indent + "auxiliary data",))
lines.append((2*indent + "record type", record.type))
lines.append((2*indent + "record data", repr(record.data)))
lwidth = max([len(line[0]) for line in lines])
lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines]
lines = [" = ".join(line) for line in lines]
return ("\n").join([indent + line for line in lines]) | [
"def",
"pretty",
"(",
"self",
",",
"indent",
"=",
"0",
")",
":",
"indent",
"=",
"indent",
"*",
"' '",
"lines",
"=",
"list",
"(",
")",
"version_string",
"=",
"\"{v.major}.{v.minor}\"",
".",
"format",
"(",
"v",
"=",
"self",
".",
"version",
")",
"lines",
... | Returns a string with a formatted representation that might
be considered pretty-printable. | [
"Returns",
"a",
"string",
"with",
"a",
"formatted",
"representation",
"that",
"might",
"be",
"considered",
"pretty",
"-",
"printable",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/handover.py#L431-L468 | train | 222,248 |
nfcpy/nfcpy | src/nfc/dep.py | Target.activate | def activate(self, timeout=None, **options):
"""Activate DEP communication as a target."""
if timeout is None:
timeout = 1.0
gbt = options.get('gbt', '')[0:47]
lrt = min(max(0, options.get('lrt', 3)), 3)
rwt = min(max(0, options.get('rwt', 8)), 14)
pp = (lrt << 4) | (bool(gbt) << 1) | int(bool(self.nad))
nfcid3t = bytearray.fromhex("01FE") + os.urandom(6) + "ST"
atr_res = ATR_RES(nfcid3t, 0, 0, 0, rwt, pp, gbt)
atr_res = atr_res.encode()
target = nfc.clf.LocalTarget(atr_res=atr_res)
target.sens_res = bytearray.fromhex("0101")
target.sdd_res = bytearray.fromhex("08") + os.urandom(3)
target.sel_res = bytearray.fromhex("40")
target.sensf_res = bytearray.fromhex("01") + nfcid3t[0:8]
target.sensf_res += bytearray.fromhex("00000000 00000000 FFFF")
target = self.clf.listen(target, timeout)
if target and target.atr_req and target.dep_req:
log.debug("activated as " + str(target))
atr_req = ATR_REQ.decode(target.atr_req)
self.lrt = lrt
self.gbt = gbt
self.gbi = atr_req.gb
self.miu = atr_req.lr - 3
self.rwt = 4096/13.56E6 * pow(2, rwt)
self.did = atr_req.did if atr_req.did > 0 else None
self.acm = not (target.sens_res or target.sensf_res)
self.cmd = chr(len(target.dep_req)+1) + target.dep_req
if target.brty == "106A":
self.cmd = b"\xF0" + self.cmd
self.target = target
self.pcnt.rcvd["ATR"] += 1
self.pcnt.sent["ATR"] += 1
log.info("running as " + str(self))
return self.gbi | python | def activate(self, timeout=None, **options):
"""Activate DEP communication as a target."""
if timeout is None:
timeout = 1.0
gbt = options.get('gbt', '')[0:47]
lrt = min(max(0, options.get('lrt', 3)), 3)
rwt = min(max(0, options.get('rwt', 8)), 14)
pp = (lrt << 4) | (bool(gbt) << 1) | int(bool(self.nad))
nfcid3t = bytearray.fromhex("01FE") + os.urandom(6) + "ST"
atr_res = ATR_RES(nfcid3t, 0, 0, 0, rwt, pp, gbt)
atr_res = atr_res.encode()
target = nfc.clf.LocalTarget(atr_res=atr_res)
target.sens_res = bytearray.fromhex("0101")
target.sdd_res = bytearray.fromhex("08") + os.urandom(3)
target.sel_res = bytearray.fromhex("40")
target.sensf_res = bytearray.fromhex("01") + nfcid3t[0:8]
target.sensf_res += bytearray.fromhex("00000000 00000000 FFFF")
target = self.clf.listen(target, timeout)
if target and target.atr_req and target.dep_req:
log.debug("activated as " + str(target))
atr_req = ATR_REQ.decode(target.atr_req)
self.lrt = lrt
self.gbt = gbt
self.gbi = atr_req.gb
self.miu = atr_req.lr - 3
self.rwt = 4096/13.56E6 * pow(2, rwt)
self.did = atr_req.did if atr_req.did > 0 else None
self.acm = not (target.sens_res or target.sensf_res)
self.cmd = chr(len(target.dep_req)+1) + target.dep_req
if target.brty == "106A":
self.cmd = b"\xF0" + self.cmd
self.target = target
self.pcnt.rcvd["ATR"] += 1
self.pcnt.sent["ATR"] += 1
log.info("running as " + str(self))
return self.gbi | [
"def",
"activate",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"1.0",
"gbt",
"=",
"options",
".",
"get",
"(",
"'gbt'",
",",
"''",
")",
"[",
"0",
":",
"47",
"]... | Activate DEP communication as a target. | [
"Activate",
"DEP",
"communication",
"as",
"a",
"target",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/dep.py#L417-L460 | train | 222,249 |
nfcpy/nfcpy | src/nfc/ndef/message.py | Message.pretty | def pretty(self):
"""Returns a message representation that might be considered
pretty-printable."""
lines = list()
for index, record in enumerate(self._records):
lines.append(("record {0}".format(index+1),))
lines.append((" type", repr(record.type)))
lines.append((" name", repr(record.name)))
lines.append((" data", repr(record.data)))
lwidth = max([len(line[0]) for line in lines])
lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines]
lines = [" = ".join(line) for line in lines]
return ("\n").join([line for line in lines]) | python | def pretty(self):
"""Returns a message representation that might be considered
pretty-printable."""
lines = list()
for index, record in enumerate(self._records):
lines.append(("record {0}".format(index+1),))
lines.append((" type", repr(record.type)))
lines.append((" name", repr(record.name)))
lines.append((" data", repr(record.data)))
lwidth = max([len(line[0]) for line in lines])
lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines]
lines = [" = ".join(line) for line in lines]
return ("\n").join([line for line in lines]) | [
"def",
"pretty",
"(",
"self",
")",
":",
"lines",
"=",
"list",
"(",
")",
"for",
"index",
",",
"record",
"in",
"enumerate",
"(",
"self",
".",
"_records",
")",
":",
"lines",
".",
"append",
"(",
"(",
"\"record {0}\"",
".",
"format",
"(",
"index",
"+",
... | Returns a message representation that might be considered
pretty-printable. | [
"Returns",
"a",
"message",
"representation",
"that",
"might",
"be",
"considered",
"pretty",
"-",
"printable",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/message.py#L161-L173 | train | 222,250 |
nfcpy/nfcpy | src/nfc/tag/tt1_broadcom.py | Topaz.format | def format(self, version=None, wipe=None):
"""Format a Topaz tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a Topaz
tag creates a capability container and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set.
"""
return super(Topaz, self).format(version, wipe) | python | def format(self, version=None, wipe=None):
"""Format a Topaz tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a Topaz
tag creates a capability container and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set.
"""
return super(Topaz, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"Topaz",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Format a Topaz tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a Topaz
tag creates a capability container and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set. | [
"Format",
"a",
"Topaz",
"tag",
"for",
"NDEF",
"use",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1_broadcom.py#L40-L49 | train | 222,251 |
nfcpy/nfcpy | src/nfc/tag/tt1_broadcom.py | Topaz512.format | def format(self, version=None, wipe=None):
"""Format a Topaz-512 tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a
Topaz-512 tag creates a capability container, a Lock Control
and a Memory Control TLV, and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set.
"""
return super(Topaz512, self).format(version, wipe) | python | def format(self, version=None, wipe=None):
"""Format a Topaz-512 tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a
Topaz-512 tag creates a capability container, a Lock Control
and a Memory Control TLV, and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set.
"""
return super(Topaz512, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"Topaz512",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Format a Topaz-512 tag for NDEF use.
The implementation of :meth:`nfc.tag.Tag.format` for a
Topaz-512 tag creates a capability container, a Lock Control
and a Memory Control TLV, and an NDEF TLV with length
zero. Data bytes of the NDEF data area are left untouched
unless the wipe argument is set. | [
"Format",
"a",
"Topaz",
"-",
"512",
"tag",
"for",
"NDEF",
"use",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1_broadcom.py#L100-L110 | train | 222,252 |
nfcpy/nfcpy | src/nfc/tag/tt1.py | Type1Tag.read_all | def read_all(self):
"""Returns the 2 byte Header ROM and all 120 byte static memory.
"""
log.debug("read all static memory")
cmd = "\x00\x00\x00" + self.uid
return self.transceive(cmd) | python | def read_all(self):
"""Returns the 2 byte Header ROM and all 120 byte static memory.
"""
log.debug("read all static memory")
cmd = "\x00\x00\x00" + self.uid
return self.transceive(cmd) | [
"def",
"read_all",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"read all static memory\"",
")",
"cmd",
"=",
"\"\\x00\\x00\\x00\"",
"+",
"self",
".",
"uid",
"return",
"self",
".",
"transceive",
"(",
"cmd",
")"
] | Returns the 2 byte Header ROM and all 120 byte static memory. | [
"Returns",
"the",
"2",
"byte",
"Header",
"ROM",
"and",
"all",
"120",
"byte",
"static",
"memory",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1.py#L387-L392 | train | 222,253 |
nfcpy/nfcpy | src/nfc/clf/acr122.py | Device.listen_tta | def listen_tta(self, target, timeout):
"""Listen as Type A Target is not supported."""
info = "{device} does not support listen as Type A Target"
raise nfc.clf.UnsupportedTargetError(info.format(device=self)) | python | def listen_tta(self, target, timeout):
"""Listen as Type A Target is not supported."""
info = "{device} does not support listen as Type A Target"
raise nfc.clf.UnsupportedTargetError(info.format(device=self)) | [
"def",
"listen_tta",
"(",
"self",
",",
"target",
",",
"timeout",
")",
":",
"info",
"=",
"\"{device} does not support listen as Type A Target\"",
"raise",
"nfc",
".",
"clf",
".",
"UnsupportedTargetError",
"(",
"info",
".",
"format",
"(",
"device",
"=",
"self",
")... | Listen as Type A Target is not supported. | [
"Listen",
"as",
"Type",
"A",
"Target",
"is",
"not",
"supported",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/acr122.py#L109-L112 | train | 222,254 |
nfcpy/nfcpy | src/nfc/clf/acr122.py | Chipset.command | def command(self, cmd_code, cmd_data, timeout):
"""Send a host command and return the chip response.
"""
log.log(logging.DEBUG-1, self.CMD[cmd_code]+" "+hexlify(cmd_data))
frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame
frame = self.ccid_xfr_block(frame, timeout)
if not frame or len(frame) < 4:
log.error("insufficient data for decoding chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[0] == 0xD5 and frame[1] == cmd_code + 1):
log.error("received invalid chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[-2] == 0x90 and frame[-1] == 0x00):
log.error("received pseudo apdu with error status")
raise IOError(errno.EIO, os.strerror(errno.EIO))
return frame[2:-2] | python | def command(self, cmd_code, cmd_data, timeout):
"""Send a host command and return the chip response.
"""
log.log(logging.DEBUG-1, self.CMD[cmd_code]+" "+hexlify(cmd_data))
frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame
frame = self.ccid_xfr_block(frame, timeout)
if not frame or len(frame) < 4:
log.error("insufficient data for decoding chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[0] == 0xD5 and frame[1] == cmd_code + 1):
log.error("received invalid chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[-2] == 0x90 and frame[-1] == 0x00):
log.error("received pseudo apdu with error status")
raise IOError(errno.EIO, os.strerror(errno.EIO))
return frame[2:-2] | [
"def",
"command",
"(",
"self",
",",
"cmd_code",
",",
"cmd_data",
",",
"timeout",
")",
":",
"log",
".",
"log",
"(",
"logging",
".",
"DEBUG",
"-",
"1",
",",
"self",
".",
"CMD",
"[",
"cmd_code",
"]",
"+",
"\" \"",
"+",
"hexlify",
"(",
"cmd_data",
")",... | Send a host command and return the chip response. | [
"Send",
"a",
"host",
"command",
"and",
"return",
"the",
"chip",
"response",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/acr122.py#L223-L242 | train | 222,255 |
nfcpy/nfcpy | src/nfc/tag/tt4.py | Type4Tag.format | def format(self, version=None, wipe=None):
"""Erase the NDEF message on a Type 4 Tag.
The :meth:`format` method writes the length of the NDEF
message on a Type 4 Tag to zero, thus the tag will appear to
be empty. If the *wipe* argument is set to some integer then
:meth:`format` will also overwrite all user data with that
integer (mod 256).
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible; this requires
proprietary information from the manufacturer.
"""
return super(Type4Tag, self).format(version, wipe) | python | def format(self, version=None, wipe=None):
"""Erase the NDEF message on a Type 4 Tag.
The :meth:`format` method writes the length of the NDEF
message on a Type 4 Tag to zero, thus the tag will appear to
be empty. If the *wipe* argument is set to some integer then
:meth:`format` will also overwrite all user data with that
integer (mod 256).
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible; this requires
proprietary information from the manufacturer.
"""
return super(Type4Tag, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"Type4Tag",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Erase the NDEF message on a Type 4 Tag.
The :meth:`format` method writes the length of the NDEF
message on a Type 4 Tag to zero, thus the tag will appear to
be empty. If the *wipe* argument is set to some integer then
:meth:`format` will also overwrite all user data with that
integer (mod 256).
Despite it's name, the :meth:`format` method can not format a
blank tag to make it NDEF compatible; this requires
proprietary information from the manufacturer. | [
"Erase",
"the",
"NDEF",
"message",
"on",
"a",
"Type",
"4",
"Tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt4.py#L395-L409 | train | 222,256 |
nfcpy/nfcpy | src/nfc/tag/tt4.py | Type4Tag.transceive | def transceive(self, data, timeout=None):
"""Transmit arbitrary data and receive the response.
This is a low level method to send arbitrary data to the
tag. While it should almost always be better to use
:meth:`send_apdu` this is the only way to force a specific
timeout value (which is otherwise derived from the Tag's
answer to select). The *timeout* value is expected as a float
specifying the seconds to wait.
"""
log.debug(">> {0}".format(hexlify(data)))
data = self._dep.exchange(data, timeout)
log.debug("<< {0}".format(hexlify(data) if data else "None"))
return data | python | def transceive(self, data, timeout=None):
"""Transmit arbitrary data and receive the response.
This is a low level method to send arbitrary data to the
tag. While it should almost always be better to use
:meth:`send_apdu` this is the only way to force a specific
timeout value (which is otherwise derived from the Tag's
answer to select). The *timeout* value is expected as a float
specifying the seconds to wait.
"""
log.debug(">> {0}".format(hexlify(data)))
data = self._dep.exchange(data, timeout)
log.debug("<< {0}".format(hexlify(data) if data else "None"))
return data | [
"def",
"transceive",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\">> {0}\"",
".",
"format",
"(",
"hexlify",
"(",
"data",
")",
")",
")",
"data",
"=",
"self",
".",
"_dep",
".",
"exchange",
"(",
"data",... | Transmit arbitrary data and receive the response.
This is a low level method to send arbitrary data to the
tag. While it should almost always be better to use
:meth:`send_apdu` this is the only way to force a specific
timeout value (which is otherwise derived from the Tag's
answer to select). The *timeout* value is expected as a float
specifying the seconds to wait. | [
"Transmit",
"arbitrary",
"data",
"and",
"receive",
"the",
"response",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt4.py#L425-L439 | train | 222,257 |
nfcpy/nfcpy | src/nfc/tag/__init__.py | Tag.format | def format(self, version=None, wipe=None):
"""Format the tag to make it NDEF compatible or erase content.
The :meth:`format` method is highly dependent on the tag type,
product and present status, for example a tag that has been
made read-only with lock bits can no longer be formatted or
erased.
:meth:`format` creates the management information defined by
the NFC Forum to describes the NDEF data area on the tag, this
is also called NDEF mapping. The mapping may differ between
versions of the tag specifications, the mapping to apply can
be specified with the *version* argument as an 8-bit integer
composed of a major version number in the most significant 4
bit and the minor version number in the least significant 4
bit. If *version* is not specified then the highest possible
mapping version is used.
If formatting of the tag is possible, the default behavior of
:meth:`format` is to update only the management information
required to make the tag appear as NDEF compatible and empty,
previously existing data could still be read. If existing data
shall be overwritten, the *wipe* argument can be set to an
8-bit integer that will be written to all available bytes.
The :meth:`format` method returns :const:`True` if formatting
was successful, :const:`False` if it failed for some reason,
or :const:`None` if the present tag can not be formatted
either because the tag does not support formatting or it is
not implemented in nfcpy.
"""
if hasattr(self, "_format"):
args = "version={0!r}, wipe={1!r}"
args = args.format(version, wipe)
log.debug("format({0})".format(args))
status = self._format(version, wipe)
if status is True:
self._ndef = None
return status
else:
log.debug("this tag can not be formatted with nfcpy")
return None | python | def format(self, version=None, wipe=None):
"""Format the tag to make it NDEF compatible or erase content.
The :meth:`format` method is highly dependent on the tag type,
product and present status, for example a tag that has been
made read-only with lock bits can no longer be formatted or
erased.
:meth:`format` creates the management information defined by
the NFC Forum to describes the NDEF data area on the tag, this
is also called NDEF mapping. The mapping may differ between
versions of the tag specifications, the mapping to apply can
be specified with the *version* argument as an 8-bit integer
composed of a major version number in the most significant 4
bit and the minor version number in the least significant 4
bit. If *version* is not specified then the highest possible
mapping version is used.
If formatting of the tag is possible, the default behavior of
:meth:`format` is to update only the management information
required to make the tag appear as NDEF compatible and empty,
previously existing data could still be read. If existing data
shall be overwritten, the *wipe* argument can be set to an
8-bit integer that will be written to all available bytes.
The :meth:`format` method returns :const:`True` if formatting
was successful, :const:`False` if it failed for some reason,
or :const:`None` if the present tag can not be formatted
either because the tag does not support formatting or it is
not implemented in nfcpy.
"""
if hasattr(self, "_format"):
args = "version={0!r}, wipe={1!r}"
args = args.format(version, wipe)
log.debug("format({0})".format(args))
status = self._format(version, wipe)
if status is True:
self._ndef = None
return status
else:
log.debug("this tag can not be formatted with nfcpy")
return None | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_format\"",
")",
":",
"args",
"=",
"\"version={0!r}, wipe={1!r}\"",
"args",
"=",
"args",
".",
"format",
"(",
"version",
... | Format the tag to make it NDEF compatible or erase content.
The :meth:`format` method is highly dependent on the tag type,
product and present status, for example a tag that has been
made read-only with lock bits can no longer be formatted or
erased.
:meth:`format` creates the management information defined by
the NFC Forum to describes the NDEF data area on the tag, this
is also called NDEF mapping. The mapping may differ between
versions of the tag specifications, the mapping to apply can
be specified with the *version* argument as an 8-bit integer
composed of a major version number in the most significant 4
bit and the minor version number in the least significant 4
bit. If *version* is not specified then the highest possible
mapping version is used.
If formatting of the tag is possible, the default behavior of
:meth:`format` is to update only the management information
required to make the tag appear as NDEF compatible and empty,
previously existing data could still be read. If existing data
shall be overwritten, the *wipe* argument can be set to an
8-bit integer that will be written to all available bytes.
The :meth:`format` method returns :const:`True` if formatting
was successful, :const:`False` if it failed for some reason,
or :const:`None` if the present tag can not be formatted
either because the tag does not support formatting or it is
not implemented in nfcpy. | [
"Format",
"the",
"tag",
"to",
"make",
"it",
"NDEF",
"compatible",
"or",
"erase",
"content",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/__init__.py#L302-L344 | train | 222,258 |
nfcpy/nfcpy | src/nfc/tag/__init__.py | Tag.protect | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect a tag against future write or read access.
:meth:`protect` attempts to make a tag readonly for all
readers if *password* is :const:`None`, writeable only after
authentication if a *password* is provided, and readable only
after authentication if a *password* is provided and the
*read_protect* flag is set. The *password* must be a byte or
character sequence that provides sufficient key material for
the tag specific protect function (this is documented
separately for the individual tag types). As a special case,
if *password* is set to an empty string the :meth:`protect`
method uses a default manufacturer value if such is known.
The *protect_from* argument sets the first memory unit to be
protected. Memory units are tag type specific, for a Type 1 or
Type 2 Tag a memory unit is 4 byte, for a Type 3 Tag it is 16
byte, and for a Type 4 Tag it is the complete NDEF data area.
Note that the effect of protecting a tag without password can
normally not be reversed.
The return value of :meth:`protect` is either :const:`True` or
:const:`False` depending on whether the operation was
successful or not, or :const:`None` if the tag does not
support custom protection (or it is not implemented).
"""
if hasattr(self, "_protect"):
args = "password={0!r}, read_protect={1!r}, protect_from={2!r}"
args = args.format(password, read_protect, protect_from)
log.debug("protect({0})".format(args))
status = self._protect(password, read_protect, protect_from)
if status is True:
self._ndef = None
return status
else:
log.error("this tag can not be protected with nfcpy")
return None | python | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect a tag against future write or read access.
:meth:`protect` attempts to make a tag readonly for all
readers if *password* is :const:`None`, writeable only after
authentication if a *password* is provided, and readable only
after authentication if a *password* is provided and the
*read_protect* flag is set. The *password* must be a byte or
character sequence that provides sufficient key material for
the tag specific protect function (this is documented
separately for the individual tag types). As a special case,
if *password* is set to an empty string the :meth:`protect`
method uses a default manufacturer value if such is known.
The *protect_from* argument sets the first memory unit to be
protected. Memory units are tag type specific, for a Type 1 or
Type 2 Tag a memory unit is 4 byte, for a Type 3 Tag it is 16
byte, and for a Type 4 Tag it is the complete NDEF data area.
Note that the effect of protecting a tag without password can
normally not be reversed.
The return value of :meth:`protect` is either :const:`True` or
:const:`False` depending on whether the operation was
successful or not, or :const:`None` if the tag does not
support custom protection (or it is not implemented).
"""
if hasattr(self, "_protect"):
args = "password={0!r}, read_protect={1!r}, protect_from={2!r}"
args = args.format(password, read_protect, protect_from)
log.debug("protect({0})".format(args))
status = self._protect(password, read_protect, protect_from)
if status is True:
self._ndef = None
return status
else:
log.error("this tag can not be protected with nfcpy")
return None | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_protect\"",
")",
":",
"args",
"=",
"\"password={0!r}, read_protect={1!r}, protect_fr... | Protect a tag against future write or read access.
:meth:`protect` attempts to make a tag readonly for all
readers if *password* is :const:`None`, writeable only after
authentication if a *password* is provided, and readable only
after authentication if a *password* is provided and the
*read_protect* flag is set. The *password* must be a byte or
character sequence that provides sufficient key material for
the tag specific protect function (this is documented
separately for the individual tag types). As a special case,
if *password* is set to an empty string the :meth:`protect`
method uses a default manufacturer value if such is known.
The *protect_from* argument sets the first memory unit to be
protected. Memory units are tag type specific, for a Type 1 or
Type 2 Tag a memory unit is 4 byte, for a Type 3 Tag it is 16
byte, and for a Type 4 Tag it is the complete NDEF data area.
Note that the effect of protecting a tag without password can
normally not be reversed.
The return value of :meth:`protect` is either :const:`True` or
:const:`False` depending on whether the operation was
successful or not, or :const:`None` if the tag does not
support custom protection (or it is not implemented). | [
"Protect",
"a",
"tag",
"against",
"future",
"write",
"or",
"read",
"access",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/__init__.py#L346-L384 | train | 222,259 |
nfcpy/nfcpy | src/nfc/snep/client.py | SnepClient.get_records | def get_records(self, records=None, timeout=1.0):
"""Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Record` list decoded from the
response message octets returned by :meth:`get_octets`. Same
as::
import ndef
send_octets = ndef.message_encoder(records)
rcvd_octets = snep_client.get_octets(send_octets, timeout)
records = list(ndef.message_decoder(rcvd_octets))
"""
octets = b''.join(ndef.message_encoder(records)) if records else None
octets = self.get_octets(octets, timeout)
if octets and len(octets) >= 3:
return list(ndef.message_decoder(octets)) | python | def get_records(self, records=None, timeout=1.0):
"""Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Record` list decoded from the
response message octets returned by :meth:`get_octets`. Same
as::
import ndef
send_octets = ndef.message_encoder(records)
rcvd_octets = snep_client.get_octets(send_octets, timeout)
records = list(ndef.message_decoder(rcvd_octets))
"""
octets = b''.join(ndef.message_encoder(records)) if records else None
octets = self.get_octets(octets, timeout)
if octets and len(octets) >= 3:
return list(ndef.message_decoder(octets)) | [
"def",
"get_records",
"(",
"self",
",",
"records",
"=",
"None",
",",
"timeout",
"=",
"1.0",
")",
":",
"octets",
"=",
"b''",
".",
"join",
"(",
"ndef",
".",
"message_encoder",
"(",
"records",
")",
")",
"if",
"records",
"else",
"None",
"octets",
"=",
"s... | Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Record` list decoded from the
response message octets returned by :meth:`get_octets`. Same
as::
import ndef
send_octets = ndef.message_encoder(records)
rcvd_octets = snep_client.get_octets(send_octets, timeout)
records = list(ndef.message_decoder(rcvd_octets)) | [
"Get",
"NDEF",
"message",
"records",
"from",
"a",
"SNEP",
"Server",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L156-L176 | train | 222,260 |
nfcpy/nfcpy | src/nfc/snep/client.py | SnepClient.get_octets | def get_octets(self, octets=None, timeout=1.0):
"""Get NDEF message octets from a SNEP Server.
.. versionadded:: 0.13
If the client has not yet a data link connection with a SNEP
Server, it temporarily connects to the default SNEP Server,
sends the message octets, disconnects after the server
response, and returns the received message octets.
"""
if octets is None:
# Send NDEF Message with one empty Record.
octets = b'\xd0\x00\x00'
if not self.socket:
try:
self.connect('urn:nfc:sn:snep')
except nfc.llcp.ConnectRefused:
return None
else:
self.release_connection = True
else:
self.release_connection = False
try:
request = struct.pack('>BBLL', 0x10, 0x01, 4 + len(octets),
self.acceptable_length) + octets
if not send_request(self.socket, request, self.send_miu):
return None
response = recv_response(
self.socket, self.acceptable_length, timeout)
if response is not None:
if response[1] != 0x81:
raise SnepError(response[1])
return response[6:]
finally:
if self.release_connection:
self.close() | python | def get_octets(self, octets=None, timeout=1.0):
"""Get NDEF message octets from a SNEP Server.
.. versionadded:: 0.13
If the client has not yet a data link connection with a SNEP
Server, it temporarily connects to the default SNEP Server,
sends the message octets, disconnects after the server
response, and returns the received message octets.
"""
if octets is None:
# Send NDEF Message with one empty Record.
octets = b'\xd0\x00\x00'
if not self.socket:
try:
self.connect('urn:nfc:sn:snep')
except nfc.llcp.ConnectRefused:
return None
else:
self.release_connection = True
else:
self.release_connection = False
try:
request = struct.pack('>BBLL', 0x10, 0x01, 4 + len(octets),
self.acceptable_length) + octets
if not send_request(self.socket, request, self.send_miu):
return None
response = recv_response(
self.socket, self.acceptable_length, timeout)
if response is not None:
if response[1] != 0x81:
raise SnepError(response[1])
return response[6:]
finally:
if self.release_connection:
self.close() | [
"def",
"get_octets",
"(",
"self",
",",
"octets",
"=",
"None",
",",
"timeout",
"=",
"1.0",
")",
":",
"if",
"octets",
"is",
"None",
":",
"# Send NDEF Message with one empty Record.",
"octets",
"=",
"b'\\xd0\\x00\\x00'",
"if",
"not",
"self",
".",
"socket",
":",
... | Get NDEF message octets from a SNEP Server.
.. versionadded:: 0.13
If the client has not yet a data link connection with a SNEP
Server, it temporarily connects to the default SNEP Server,
sends the message octets, disconnects after the server
response, and returns the received message octets. | [
"Get",
"NDEF",
"message",
"octets",
"from",
"a",
"SNEP",
"Server",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L178-L221 | train | 222,261 |
nfcpy/nfcpy | src/nfc/snep/client.py | SnepClient.put | def put(self, ndef_message, timeout=1.0):
"""Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`.
"""
if not self.socket:
try:
self.connect('urn:nfc:sn:snep')
except nfc.llcp.ConnectRefused:
return False
else:
self.release_connection = True
else:
self.release_connection = False
try:
ndef_msgsize = struct.pack('>L', len(str(ndef_message)))
snep_request = b'\x10\x02' + ndef_msgsize + str(ndef_message)
if send_request(self.socket, snep_request, self.send_miu):
response = recv_response(self.socket, 0, timeout)
if response is not None:
if response[1] != 0x81:
raise SnepError(response[1])
return True
return False
finally:
if self.release_connection:
self.close() | python | def put(self, ndef_message, timeout=1.0):
"""Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`.
"""
if not self.socket:
try:
self.connect('urn:nfc:sn:snep')
except nfc.llcp.ConnectRefused:
return False
else:
self.release_connection = True
else:
self.release_connection = False
try:
ndef_msgsize = struct.pack('>L', len(str(ndef_message)))
snep_request = b'\x10\x02' + ndef_msgsize + str(ndef_message)
if send_request(self.socket, snep_request, self.send_miu):
response = recv_response(self.socket, 0, timeout)
if response is not None:
if response[1] != 0x81:
raise SnepError(response[1])
return True
return False
finally:
if self.release_connection:
self.close() | [
"def",
"put",
"(",
"self",
",",
"ndef_message",
",",
"timeout",
"=",
"1.0",
")",
":",
"if",
"not",
"self",
".",
"socket",
":",
"try",
":",
"self",
".",
"connect",
"(",
"'urn:nfc:sn:snep'",
")",
"except",
"nfc",
".",
"llcp",
".",
"ConnectRefused",
":",
... | Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`. | [
"Send",
"an",
"NDEF",
"message",
"to",
"the",
"server",
".",
"Temporarily",
"connects",
"to",
"the",
"default",
"SNEP",
"server",
"if",
"the",
"client",
"is",
"not",
"yet",
"connected",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L223-L252 | train | 222,262 |
nfcpy/nfcpy | src/nfc/snep/client.py | SnepClient.put_records | def put_records(self, records, timeout=1.0):
"""Send NDEF message records to a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded
and then send via :meth:`put_octets`. Same as::
import ndef
octets = ndef.message_encoder(records)
snep_client.put_octets(octets, timeout)
"""
octets = b''.join(ndef.message_encoder(records))
return self.put_octets(octets, timeout) | python | def put_records(self, records, timeout=1.0):
"""Send NDEF message records to a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded
and then send via :meth:`put_octets`. Same as::
import ndef
octets = ndef.message_encoder(records)
snep_client.put_octets(octets, timeout)
"""
octets = b''.join(ndef.message_encoder(records))
return self.put_octets(octets, timeout) | [
"def",
"put_records",
"(",
"self",
",",
"records",
",",
"timeout",
"=",
"1.0",
")",
":",
"octets",
"=",
"b''",
".",
"join",
"(",
"ndef",
".",
"message_encoder",
"(",
"records",
")",
")",
"return",
"self",
".",
"put_octets",
"(",
"octets",
",",
"timeout... | Send NDEF message records to a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded
and then send via :meth:`put_octets`. Same as::
import ndef
octets = ndef.message_encoder(records)
snep_client.put_octets(octets, timeout) | [
"Send",
"NDEF",
"message",
"records",
"to",
"a",
"SNEP",
"Server",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L254-L268 | train | 222,263 |
nfcpy/nfcpy | src/nfc/clf/rcs380.py | Device.sense_ttb | def sense_ttb(self, target):
"""Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps.
"""
log.debug("polling for NFC-B technology")
if target.brty not in ("106B", "212B", "424B"):
message = "unsupported bitrate {0}".format(target.brty)
raise nfc.clf.UnsupportedTargetError(message)
self.chipset.in_set_rf(target.brty)
self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)
self.chipset.in_set_protocol(initial_guard_time=20, add_sof=1,
check_sof=1, add_eof=1, check_eof=1)
sensb_req = (target.sensb_req if target.sensb_req else
bytearray.fromhex("050010"))
log.debug("send SENSB_REQ " + hexlify(sensb_req))
try:
sensb_res = self.chipset.in_comm_rf(sensb_req, 30)
except CommunicationError as error:
if error != "RECEIVE_TIMEOUT_ERROR":
log.debug(error)
return None
if len(sensb_res) >= 12 and sensb_res[0] == 0x50:
log.debug("rcvd SENSB_RES " + hexlify(sensb_res))
return nfc.clf.RemoteTarget(target.brty, sensb_res=sensb_res) | python | def sense_ttb(self, target):
"""Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps.
"""
log.debug("polling for NFC-B technology")
if target.brty not in ("106B", "212B", "424B"):
message = "unsupported bitrate {0}".format(target.brty)
raise nfc.clf.UnsupportedTargetError(message)
self.chipset.in_set_rf(target.brty)
self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)
self.chipset.in_set_protocol(initial_guard_time=20, add_sof=1,
check_sof=1, add_eof=1, check_eof=1)
sensb_req = (target.sensb_req if target.sensb_req else
bytearray.fromhex("050010"))
log.debug("send SENSB_REQ " + hexlify(sensb_req))
try:
sensb_res = self.chipset.in_comm_rf(sensb_req, 30)
except CommunicationError as error:
if error != "RECEIVE_TIMEOUT_ERROR":
log.debug(error)
return None
if len(sensb_res) >= 12 and sensb_res[0] == 0x50:
log.debug("rcvd SENSB_RES " + hexlify(sensb_res))
return nfc.clf.RemoteTarget(target.brty, sensb_res=sensb_res) | [
"def",
"sense_ttb",
"(",
"self",
",",
"target",
")",
":",
"log",
".",
"debug",
"(",
"\"polling for NFC-B technology\"",
")",
"if",
"target",
".",
"brty",
"not",
"in",
"(",
"\"106B\"",
",",
"\"212B\"",
",",
"\"424B\"",
")",
":",
"message",
"=",
"\"unsupport... | Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps. | [
"Sense",
"for",
"a",
"Type",
"B",
"Target",
"is",
"supported",
"for",
"106",
"212",
"and",
"424",
"kbps",
".",
"However",
"there",
"may",
"not",
"be",
"any",
"target",
"that",
"understands",
"the",
"activation",
"command",
"in",
"other",
"than",
"106",
"... | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs380.py#L452-L482 | train | 222,264 |
nfcpy/nfcpy | src/nfc/clf/rcs380.py | Device.sense_ttf | def sense_ttf(self, target):
"""Sense for a Type F Target is supported for 212 and 424 kbps.
"""
log.debug("polling for NFC-F technology")
if target.brty not in ("212F", "424F"):
message = "unsupported bitrate {0}".format(target.brty)
raise nfc.clf.UnsupportedTargetError(message)
self.chipset.in_set_rf(target.brty)
self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)
self.chipset.in_set_protocol(initial_guard_time=24)
sensf_req = (target.sensf_req if target.sensf_req else
bytearray.fromhex("00FFFF0100"))
log.debug("send SENSF_REQ " + hexlify(sensf_req))
try:
frame = chr(len(sensf_req)+1) + sensf_req
frame = self.chipset.in_comm_rf(frame, 10)
except CommunicationError as error:
if error != "RECEIVE_TIMEOUT_ERROR":
log.debug(error)
return None
if len(frame) >= 18 and frame[0] == len(frame) and frame[1] == 1:
log.debug("rcvd SENSF_RES " + hexlify(frame[1:]))
return nfc.clf.RemoteTarget(target.brty, sensf_res=frame[1:]) | python | def sense_ttf(self, target):
"""Sense for a Type F Target is supported for 212 and 424 kbps.
"""
log.debug("polling for NFC-F technology")
if target.brty not in ("212F", "424F"):
message = "unsupported bitrate {0}".format(target.brty)
raise nfc.clf.UnsupportedTargetError(message)
self.chipset.in_set_rf(target.brty)
self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)
self.chipset.in_set_protocol(initial_guard_time=24)
sensf_req = (target.sensf_req if target.sensf_req else
bytearray.fromhex("00FFFF0100"))
log.debug("send SENSF_REQ " + hexlify(sensf_req))
try:
frame = chr(len(sensf_req)+1) + sensf_req
frame = self.chipset.in_comm_rf(frame, 10)
except CommunicationError as error:
if error != "RECEIVE_TIMEOUT_ERROR":
log.debug(error)
return None
if len(frame) >= 18 and frame[0] == len(frame) and frame[1] == 1:
log.debug("rcvd SENSF_RES " + hexlify(frame[1:]))
return nfc.clf.RemoteTarget(target.brty, sensf_res=frame[1:]) | [
"def",
"sense_ttf",
"(",
"self",
",",
"target",
")",
":",
"log",
".",
"debug",
"(",
"\"polling for NFC-F technology\"",
")",
"if",
"target",
".",
"brty",
"not",
"in",
"(",
"\"212F\"",
",",
"\"424F\"",
")",
":",
"message",
"=",
"\"unsupported bitrate {0}\"",
... | Sense for a Type F Target is supported for 212 and 424 kbps. | [
"Sense",
"for",
"a",
"Type",
"F",
"Target",
"is",
"supported",
"for",
"212",
"and",
"424",
"kbps",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs380.py#L484-L512 | train | 222,265 |
nfcpy/nfcpy | src/nfc/clf/rcs380.py | Device.listen_ttf | def listen_ttf(self, target, timeout):
"""Listen as Type F Target is supported for either 212 or 424 kbps."""
if target.brty not in ('212F', '424F'):
info = "unsupported target bitrate: %r" % target.brty
raise nfc.clf.UnsupportedTargetError(info)
if target.sensf_res is None:
raise ValueError("sensf_res is required")
if len(target.sensf_res) != 19:
raise ValueError("sensf_res must be 19 byte")
self.chipset.tg_set_rf(target.brty)
self.chipset.tg_set_protocol(self.chipset.tg_set_protocol_defaults)
self.chipset.tg_set_protocol(rf_off_error=False)
recv_timeout = min(int(1000 * timeout), 0xFFFF)
time_to_return = time.time() + timeout
transmit_data = sensf_req = sensf_res = None
while recv_timeout > 0:
if transmit_data:
log.debug("%s send %s", target.brty, hexlify(transmit_data))
log.debug("%s wait recv %d ms", target.brty, recv_timeout)
try:
data = self.chipset.tg_comm_rf(recv_timeout=recv_timeout,
transmit_data=transmit_data)
except CommunicationError as error:
log.debug(error)
continue
finally:
recv_timeout = int((time_to_return - time.time()) * 1E3)
transmit_data = None
assert target.brty == ('106A', '212F', '424F')[data[0]-11]
log.debug("%s rcvd %s", target.brty, hexlify(buffer(data, 7)))
if len(data) > 7 and len(data)-7 == data[7]:
if sensf_req and data[9:17] == target.sensf_res[1:9]:
self.chipset.tg_set_protocol(rf_off_error=True)
target = nfc.clf.LocalTarget(target.brty)
target.sensf_req = sensf_req
target.sensf_res = sensf_res
target.tt3_cmd = data[8:]
return target
if len(data) == 13 and data[7] == 6 and data[8] == 0:
(sensf_req, sensf_res) = (data[8:], target.sensf_res[:])
if (((sensf_req[1] == 255 or sensf_req[1] == sensf_res[17]) and
(sensf_req[2] == 255 or sensf_req[2] == sensf_res[18]))):
transmit_data = sensf_res[0:17]
if sensf_req[3] == 1:
transmit_data += sensf_res[17:19]
if sensf_req[3] == 2:
transmit_data += b"\x00"
transmit_data += chr(1 << (target.brty == "424F"))
transmit_data = chr(len(transmit_data)+1) + transmit_data | python | def listen_ttf(self, target, timeout):
"""Listen as Type F Target is supported for either 212 or 424 kbps."""
if target.brty not in ('212F', '424F'):
info = "unsupported target bitrate: %r" % target.brty
raise nfc.clf.UnsupportedTargetError(info)
if target.sensf_res is None:
raise ValueError("sensf_res is required")
if len(target.sensf_res) != 19:
raise ValueError("sensf_res must be 19 byte")
self.chipset.tg_set_rf(target.brty)
self.chipset.tg_set_protocol(self.chipset.tg_set_protocol_defaults)
self.chipset.tg_set_protocol(rf_off_error=False)
recv_timeout = min(int(1000 * timeout), 0xFFFF)
time_to_return = time.time() + timeout
transmit_data = sensf_req = sensf_res = None
while recv_timeout > 0:
if transmit_data:
log.debug("%s send %s", target.brty, hexlify(transmit_data))
log.debug("%s wait recv %d ms", target.brty, recv_timeout)
try:
data = self.chipset.tg_comm_rf(recv_timeout=recv_timeout,
transmit_data=transmit_data)
except CommunicationError as error:
log.debug(error)
continue
finally:
recv_timeout = int((time_to_return - time.time()) * 1E3)
transmit_data = None
assert target.brty == ('106A', '212F', '424F')[data[0]-11]
log.debug("%s rcvd %s", target.brty, hexlify(buffer(data, 7)))
if len(data) > 7 and len(data)-7 == data[7]:
if sensf_req and data[9:17] == target.sensf_res[1:9]:
self.chipset.tg_set_protocol(rf_off_error=True)
target = nfc.clf.LocalTarget(target.brty)
target.sensf_req = sensf_req
target.sensf_res = sensf_res
target.tt3_cmd = data[8:]
return target
if len(data) == 13 and data[7] == 6 and data[8] == 0:
(sensf_req, sensf_res) = (data[8:], target.sensf_res[:])
if (((sensf_req[1] == 255 or sensf_req[1] == sensf_res[17]) and
(sensf_req[2] == 255 or sensf_req[2] == sensf_res[18]))):
transmit_data = sensf_res[0:17]
if sensf_req[3] == 1:
transmit_data += sensf_res[17:19]
if sensf_req[3] == 2:
transmit_data += b"\x00"
transmit_data += chr(1 << (target.brty == "424F"))
transmit_data = chr(len(transmit_data)+1) + transmit_data | [
"def",
"listen_ttf",
"(",
"self",
",",
"target",
",",
"timeout",
")",
":",
"if",
"target",
".",
"brty",
"not",
"in",
"(",
"'212F'",
",",
"'424F'",
")",
":",
"info",
"=",
"\"unsupported target bitrate: %r\"",
"%",
"target",
".",
"brty",
"raise",
"nfc",
".... | Listen as Type F Target is supported for either 212 or 424 kbps. | [
"Listen",
"as",
"Type",
"F",
"Target",
"is",
"supported",
"for",
"either",
"212",
"or",
"424",
"kbps",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs380.py#L671-L726 | train | 222,266 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaStandard.request_response | def request_response(self):
"""Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polling command, transitions to Mode 1 with Authentication1,
to Mode 2 with Authentication2, and Mode 3 with any of the
card issuance commands. The :meth:`request_response` method
returns the mode as an integer.
Command execution errors raise
:exc:`~nfc.tag.TagCommandError`.
"""
a, b, e = self.pmm[3] & 7, self.pmm[3] >> 3 & 7, self.pmm[3] >> 6
timeout = 302E-6 * (b + 1 + a + 1) * 4**e
data = self.send_cmd_recv_rsp(0x04, '', timeout, check_status=False)
if len(data) != 1:
log.debug("insufficient data received from tag")
raise tt3.Type3TagCommandError(tt3.DATA_SIZE_ERROR)
return data[0] | python | def request_response(self):
"""Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polling command, transitions to Mode 1 with Authentication1,
to Mode 2 with Authentication2, and Mode 3 with any of the
card issuance commands. The :meth:`request_response` method
returns the mode as an integer.
Command execution errors raise
:exc:`~nfc.tag.TagCommandError`.
"""
a, b, e = self.pmm[3] & 7, self.pmm[3] >> 3 & 7, self.pmm[3] >> 6
timeout = 302E-6 * (b + 1 + a + 1) * 4**e
data = self.send_cmd_recv_rsp(0x04, '', timeout, check_status=False)
if len(data) != 1:
log.debug("insufficient data received from tag")
raise tt3.Type3TagCommandError(tt3.DATA_SIZE_ERROR)
return data[0] | [
"def",
"request_response",
"(",
"self",
")",
":",
"a",
",",
"b",
",",
"e",
"=",
"self",
".",
"pmm",
"[",
"3",
"]",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"3",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"6",
... | Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polling command, transitions to Mode 1 with Authentication1,
to Mode 2 with Authentication2, and Mode 3 with any of the
card issuance commands. The :meth:`request_response` method
returns the mode as an integer.
Command execution errors raise
:exc:`~nfc.tag.TagCommandError`. | [
"Verify",
"that",
"a",
"card",
"is",
"still",
"present",
"and",
"get",
"its",
"operating",
"mode",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L258-L279 | train | 222,267 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaStandard.search_service_code | def search_service_code(self, service_index):
"""Search for a service code that corresponds to an index.
The Search Service Code command provides access to the
iterable list of services and areas within the activated
system. The *service_index* argument may be any value from 0
to 0xffff. As long as there is a service or area found for a
given *service_index*, the information returned is a tuple
with either one or two 16-bit integer elements. Two integers
are returned for an area definition, the first is the area
code and the second is the largest possible service index for
the area. One integer, the service code, is returned for a
service definition. The return value is :const:`None` if the
*service_index* was not found.
For example, to print all services and areas of the active
system: ::
for i in xrange(0x10000):
area_or_service = tag.search_service_code(i)
if area_or_service is None:
break
elif len(area_or_service) == 1:
sc = area_or_service[0]
print(nfc.tag.tt3.ServiceCode(sc >> 6, sc & 0x3f))
elif len(area_or_service) == 2:
area_code, area_last = area_or_service
print("Area {0:04x}--{0:04x}".format(area_code, area_last))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("search service code index {0}".format(service_index))
# The maximum response time is given by the value of PMM[3].
# Some cards (like RC-S860 with IC RC-S915) encode a value
# that is too short, thus we use at lest 2 ms.
a, e = self.pmm[3] & 7, self.pmm[3] >> 6
timeout = max(302E-6 * (a + 1) * 4**e, 0.002)
data = pack("<H", service_index)
data = self.send_cmd_recv_rsp(0x0A, data, timeout, check_status=False)
if data != "\xFF\xFF":
unpack_format = "<H" if len(data) == 2 else "<HH"
return unpack(unpack_format, data) | python | def search_service_code(self, service_index):
"""Search for a service code that corresponds to an index.
The Search Service Code command provides access to the
iterable list of services and areas within the activated
system. The *service_index* argument may be any value from 0
to 0xffff. As long as there is a service or area found for a
given *service_index*, the information returned is a tuple
with either one or two 16-bit integer elements. Two integers
are returned for an area definition, the first is the area
code and the second is the largest possible service index for
the area. One integer, the service code, is returned for a
service definition. The return value is :const:`None` if the
*service_index* was not found.
For example, to print all services and areas of the active
system: ::
for i in xrange(0x10000):
area_or_service = tag.search_service_code(i)
if area_or_service is None:
break
elif len(area_or_service) == 1:
sc = area_or_service[0]
print(nfc.tag.tt3.ServiceCode(sc >> 6, sc & 0x3f))
elif len(area_or_service) == 2:
area_code, area_last = area_or_service
print("Area {0:04x}--{0:04x}".format(area_code, area_last))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("search service code index {0}".format(service_index))
# The maximum response time is given by the value of PMM[3].
# Some cards (like RC-S860 with IC RC-S915) encode a value
# that is too short, thus we use at lest 2 ms.
a, e = self.pmm[3] & 7, self.pmm[3] >> 6
timeout = max(302E-6 * (a + 1) * 4**e, 0.002)
data = pack("<H", service_index)
data = self.send_cmd_recv_rsp(0x0A, data, timeout, check_status=False)
if data != "\xFF\xFF":
unpack_format = "<H" if len(data) == 2 else "<HH"
return unpack(unpack_format, data) | [
"def",
"search_service_code",
"(",
"self",
",",
"service_index",
")",
":",
"log",
".",
"debug",
"(",
"\"search service code index {0}\"",
".",
"format",
"(",
"service_index",
")",
")",
"# The maximum response time is given by the value of PMM[3].",
"# Some cards (like RC-S860... | Search for a service code that corresponds to an index.
The Search Service Code command provides access to the
iterable list of services and areas within the activated
system. The *service_index* argument may be any value from 0
to 0xffff. As long as there is a service or area found for a
given *service_index*, the information returned is a tuple
with either one or two 16-bit integer elements. Two integers
are returned for an area definition, the first is the area
code and the second is the largest possible service index for
the area. One integer, the service code, is returned for a
service definition. The return value is :const:`None` if the
*service_index* was not found.
For example, to print all services and areas of the active
system: ::
for i in xrange(0x10000):
area_or_service = tag.search_service_code(i)
if area_or_service is None:
break
elif len(area_or_service) == 1:
sc = area_or_service[0]
print(nfc.tag.tt3.ServiceCode(sc >> 6, sc & 0x3f))
elif len(area_or_service) == 2:
area_code, area_last = area_or_service
print("Area {0:04x}--{0:04x}".format(area_code, area_last))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Search",
"for",
"a",
"service",
"code",
"that",
"corresponds",
"to",
"an",
"index",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L281-L323 | train | 222,268 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaStandard.request_system_code | def request_system_code(self):
"""Return all system codes that are registered in the card.
A card has one or more system codes that correspond to logical
partitions (systems). Each system has a system code that could
be used in a polling command to activate that system. The
system codes responded by the card are returned as a list of
16-bit integers. ::
for system_code in tag.request_system_code():
print("System {0:04X}".format(system_code))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("request system code list")
a, e = self.pmm[3] & 7, self.pmm[3] >> 6
timeout = max(302E-6 * (a + 1) * 4**e, 0.002)
data = self.send_cmd_recv_rsp(0x0C, '', timeout, check_status=False)
if len(data) != 1 + data[0] * 2:
log.debug("insufficient data received from tag")
raise tt3.Type3TagCommandError(tt3.DATA_SIZE_ERROR)
return [unpack(">H", data[i:i+2])[0] for i in range(1, len(data), 2)] | python | def request_system_code(self):
"""Return all system codes that are registered in the card.
A card has one or more system codes that correspond to logical
partitions (systems). Each system has a system code that could
be used in a polling command to activate that system. The
system codes responded by the card are returned as a list of
16-bit integers. ::
for system_code in tag.request_system_code():
print("System {0:04X}".format(system_code))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("request system code list")
a, e = self.pmm[3] & 7, self.pmm[3] >> 6
timeout = max(302E-6 * (a + 1) * 4**e, 0.002)
data = self.send_cmd_recv_rsp(0x0C, '', timeout, check_status=False)
if len(data) != 1 + data[0] * 2:
log.debug("insufficient data received from tag")
raise tt3.Type3TagCommandError(tt3.DATA_SIZE_ERROR)
return [unpack(">H", data[i:i+2])[0] for i in range(1, len(data), 2)] | [
"def",
"request_system_code",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"request system code list\"",
")",
"a",
",",
"e",
"=",
"self",
".",
"pmm",
"[",
"3",
"]",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"6",
"timeout",
"=",
... | Return all system codes that are registered in the card.
A card has one or more system codes that correspond to logical
partitions (systems). Each system has a system code that could
be used in a polling command to activate that system. The
system codes responded by the card are returned as a list of
16-bit integers. ::
for system_code in tag.request_system_code():
print("System {0:04X}".format(system_code))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Return",
"all",
"system",
"codes",
"that",
"are",
"registered",
"in",
"the",
"card",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L325-L347 | train | 222,269 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLite.protect | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect a FeliCa Lite Tag.
A FeliCa Lite Tag can be provisioned with a custom password
(or the default manufacturer key if the password is an empty
string or bytearray) to ensure that data retrieved by future
read operations, after authentication, is genuine. Read
protection is not supported.
A non-empty *password* must provide at least 128 bit key
material, in other words it must be a string or bytearray of
length 16 or more.
The memory unit for the value of *protect_from* is 16 byte,
thus with ``protect_from=2`` bytes 0 to 31 are not protected.
If *protect_from* is zero (the default value) and the Tag has
valid NDEF management data, the NDEF RW Flag is set to read
only.
"""
return super(FelicaLite, self).protect(
password, read_protect, protect_from) | python | def protect(self, password=None, read_protect=False, protect_from=0):
"""Protect a FeliCa Lite Tag.
A FeliCa Lite Tag can be provisioned with a custom password
(or the default manufacturer key if the password is an empty
string or bytearray) to ensure that data retrieved by future
read operations, after authentication, is genuine. Read
protection is not supported.
A non-empty *password* must provide at least 128 bit key
material, in other words it must be a string or bytearray of
length 16 or more.
The memory unit for the value of *protect_from* is 16 byte,
thus with ``protect_from=2`` bytes 0 to 31 are not protected.
If *protect_from* is zero (the default value) and the Tag has
valid NDEF management data, the NDEF RW Flag is set to read
only.
"""
return super(FelicaLite, self).protect(
password, read_protect, protect_from) | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"None",
",",
"read_protect",
"=",
"False",
",",
"protect_from",
"=",
"0",
")",
":",
"return",
"super",
"(",
"FelicaLite",
",",
"self",
")",
".",
"protect",
"(",
"password",
",",
"read_protect",
",",
... | Protect a FeliCa Lite Tag.
A FeliCa Lite Tag can be provisioned with a custom password
(or the default manufacturer key if the password is an empty
string or bytearray) to ensure that data retrieved by future
read operations, after authentication, is genuine. Read
protection is not supported.
A non-empty *password* must provide at least 128 bit key
material, in other words it must be a string or bytearray of
length 16 or more.
The memory unit for the value of *protect_from* is 16 byte,
thus with ``protect_from=2`` bytes 0 to 31 are not protected.
If *protect_from* is zero (the default value) and the Tag has
valid NDEF management data, the NDEF RW Flag is set to read
only. | [
"Protect",
"a",
"FeliCa",
"Lite",
"Tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L492-L513 | train | 222,270 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLite.format | def format(self, version=0x10, wipe=None):
"""Format a FeliCa Lite Tag for NDEF.
"""
return super(FelicaLite, self).format(version, wipe) | python | def format(self, version=0x10, wipe=None):
"""Format a FeliCa Lite Tag for NDEF.
"""
return super(FelicaLite, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"0x10",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"FelicaLite",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Format a FeliCa Lite Tag for NDEF. | [
"Format",
"a",
"FeliCa",
"Lite",
"Tag",
"for",
"NDEF",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L626-L630 | train | 222,271 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLite.read_without_mac | def read_without_mac(self, *blocks):
"""Read a number of data blocks without integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF).
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("read {0} block(s) without mac".format(len(blocks)))
service_list = [tt3.ServiceCode(0, 0b001011)]
block_list = [tt3.BlockCode(n) for n in blocks]
return self.read_without_encryption(service_list, block_list) | python | def read_without_mac(self, *blocks):
"""Read a number of data blocks without integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF).
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("read {0} block(s) without mac".format(len(blocks)))
service_list = [tt3.ServiceCode(0, 0b001011)]
block_list = [tt3.BlockCode(n) for n in blocks]
return self.read_without_encryption(service_list, block_list) | [
"def",
"read_without_mac",
"(",
"self",
",",
"*",
"blocks",
")",
":",
"log",
".",
"debug",
"(",
"\"read {0} block(s) without mac\"",
".",
"format",
"(",
"len",
"(",
"blocks",
")",
")",
")",
"service_list",
"=",
"[",
"tt3",
".",
"ServiceCode",
"(",
"0",
"... | Read a number of data blocks without integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF).
Tag command errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Read",
"a",
"number",
"of",
"data",
"blocks",
"without",
"integrity",
"check",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L680-L693 | train | 222,272 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLite.read_with_mac | def read_with_mac(self, *blocks):
"""Read a number of data blocks with integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF). Along with the requested block data the
tag returns a message authentication code that is verified
before data is returned. If verification fails the return
value of :meth:`read_with_mac` is None.
A :exc:`RuntimeError` exception is raised if the tag was not
authenticated before calling this method.
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("read {0} block(s) with mac".format(len(blocks)))
if self._sk is None or self._iv is None:
raise RuntimeError("authentication required")
service_list = [tt3.ServiceCode(0, 0b001011)]
block_list = [tt3.BlockCode(n) for n in blocks]
block_list.append(tt3.BlockCode(0x81))
data = self.read_without_encryption(service_list, block_list)
data, mac = data[0:-16], data[-16:-8]
if mac != self.generate_mac(data, self._sk, self._iv):
log.warning("mac verification failed")
else:
return data | python | def read_with_mac(self, *blocks):
"""Read a number of data blocks with integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF). Along with the requested block data the
tag returns a message authentication code that is verified
before data is returned. If verification fails the return
value of :meth:`read_with_mac` is None.
A :exc:`RuntimeError` exception is raised if the tag was not
authenticated before calling this method.
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("read {0} block(s) with mac".format(len(blocks)))
if self._sk is None or self._iv is None:
raise RuntimeError("authentication required")
service_list = [tt3.ServiceCode(0, 0b001011)]
block_list = [tt3.BlockCode(n) for n in blocks]
block_list.append(tt3.BlockCode(0x81))
data = self.read_without_encryption(service_list, block_list)
data, mac = data[0:-16], data[-16:-8]
if mac != self.generate_mac(data, self._sk, self._iv):
log.warning("mac verification failed")
else:
return data | [
"def",
"read_with_mac",
"(",
"self",
",",
"*",
"blocks",
")",
":",
"log",
".",
"debug",
"(",
"\"read {0} block(s) with mac\"",
".",
"format",
"(",
"len",
"(",
"blocks",
")",
")",
")",
"if",
"self",
".",
"_sk",
"is",
"None",
"or",
"self",
".",
"_iv",
... | Read a number of data blocks with integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF). Along with the requested block data the
tag returns a message authentication code that is verified
before data is returned. If verification fails the return
value of :meth:`read_with_mac` is None.
A :exc:`RuntimeError` exception is raised if the tag was not
authenticated before calling this method.
Tag command errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Read",
"a",
"number",
"of",
"data",
"blocks",
"with",
"integrity",
"check",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L695-L725 | train | 222,273 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLite.write_without_mac | def write_without_mac(self, data, block):
"""Write a data block without integrity check.
This is the standard write method for a FeliCa Lite. The
16-byte string or bytearray *data* is written to the numbered
*block* in service 0x0009 (NDEF write service). ::
data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F
try: tag.write_without_mac(data, 5) # write block 5
except nfc.tag.TagCommandError:
print("something went wrong")
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
# Write a single data block without a mac. Write with mac is
# only supported by FeliCa Lite-S.
assert len(data) == 16 and type(block) is int
log.debug("write 1 block without mac".format())
sc_list = [tt3.ServiceCode(0, 0b001001)]
bc_list = [tt3.BlockCode(block)]
self.write_without_encryption(sc_list, bc_list, data) | python | def write_without_mac(self, data, block):
"""Write a data block without integrity check.
This is the standard write method for a FeliCa Lite. The
16-byte string or bytearray *data* is written to the numbered
*block* in service 0x0009 (NDEF write service). ::
data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F
try: tag.write_without_mac(data, 5) # write block 5
except nfc.tag.TagCommandError:
print("something went wrong")
Tag command errors raise :exc:`~nfc.tag.TagCommandError`.
"""
# Write a single data block without a mac. Write with mac is
# only supported by FeliCa Lite-S.
assert len(data) == 16 and type(block) is int
log.debug("write 1 block without mac".format())
sc_list = [tt3.ServiceCode(0, 0b001001)]
bc_list = [tt3.BlockCode(block)]
self.write_without_encryption(sc_list, bc_list, data) | [
"def",
"write_without_mac",
"(",
"self",
",",
"data",
",",
"block",
")",
":",
"# Write a single data block without a mac. Write with mac is",
"# only supported by FeliCa Lite-S.",
"assert",
"len",
"(",
"data",
")",
"==",
"16",
"and",
"type",
"(",
"block",
")",
"is",
... | Write a data block without integrity check.
This is the standard write method for a FeliCa Lite. The
16-byte string or bytearray *data* is written to the numbered
*block* in service 0x0009 (NDEF write service). ::
data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F
try: tag.write_without_mac(data, 5) # write block 5
except nfc.tag.TagCommandError:
print("something went wrong")
Tag command errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Write",
"a",
"data",
"block",
"without",
"integrity",
"check",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L727-L748 | train | 222,274 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLiteS.authenticate | def authenticate(self, password):
"""Mutually authenticate with a FeliCa Lite-S Tag.
FeliCa Lite-S supports enhanced security functions, one of
them is the mutual authentication performed by this
method. The first part of mutual authentication is to
authenticate the tag with :meth:`FelicaLite.authenticate`. If
successful, the shared session key is used to generate the
integrity check value for write operation to update a specific
memory block. If that was successful then the tag is ensured
that the reader has the correct card key.
After successful authentication the
:meth:`~FelicaLite.read_with_mac` and :meth:`write_with_mac`
methods can be used to read and write data such that it can
not be falsified on transmission.
"""
if super(FelicaLiteS, self).authenticate(password):
# At this point we have achieved internal authentication,
# i.e we know that the tag has the same card key as in
# password. We now reset the authentication status and do
# external authentication to assure the tag that we have
# the right card key.
self._authenticated = False
self.read_from_ndef_service = self.read_without_mac
self.write_to_ndef_service = self.write_without_mac
# To authenticate to the tag we write a 01h into the
# ext_auth byte of the state block (block 0x92). The other
# bytes of the state block can be all set to zero.
self.write_with_mac("\x01" + 15*"\0", 0x92)
# Now read the state block and check the value of the
# ext_auth to see if we are authenticated. If it's 01h
# then we are, otherwise not.
if self.read_with_mac(0x92)[0] == 0x01:
log.debug("mutual authentication completed")
self._authenticated = True
self.read_from_ndef_service = self.read_with_mac
self.write_to_ndef_service = self.write_with_mac
else:
log.debug("mutual authentication failed")
return self._authenticated | python | def authenticate(self, password):
"""Mutually authenticate with a FeliCa Lite-S Tag.
FeliCa Lite-S supports enhanced security functions, one of
them is the mutual authentication performed by this
method. The first part of mutual authentication is to
authenticate the tag with :meth:`FelicaLite.authenticate`. If
successful, the shared session key is used to generate the
integrity check value for write operation to update a specific
memory block. If that was successful then the tag is ensured
that the reader has the correct card key.
After successful authentication the
:meth:`~FelicaLite.read_with_mac` and :meth:`write_with_mac`
methods can be used to read and write data such that it can
not be falsified on transmission.
"""
if super(FelicaLiteS, self).authenticate(password):
# At this point we have achieved internal authentication,
# i.e we know that the tag has the same card key as in
# password. We now reset the authentication status and do
# external authentication to assure the tag that we have
# the right card key.
self._authenticated = False
self.read_from_ndef_service = self.read_without_mac
self.write_to_ndef_service = self.write_without_mac
# To authenticate to the tag we write a 01h into the
# ext_auth byte of the state block (block 0x92). The other
# bytes of the state block can be all set to zero.
self.write_with_mac("\x01" + 15*"\0", 0x92)
# Now read the state block and check the value of the
# ext_auth to see if we are authenticated. If it's 01h
# then we are, otherwise not.
if self.read_with_mac(0x92)[0] == 0x01:
log.debug("mutual authentication completed")
self._authenticated = True
self.read_from_ndef_service = self.read_with_mac
self.write_to_ndef_service = self.write_with_mac
else:
log.debug("mutual authentication failed")
return self._authenticated | [
"def",
"authenticate",
"(",
"self",
",",
"password",
")",
":",
"if",
"super",
"(",
"FelicaLiteS",
",",
"self",
")",
".",
"authenticate",
"(",
"password",
")",
":",
"# At this point we have achieved internal authentication,",
"# i.e we know that the tag has the same card k... | Mutually authenticate with a FeliCa Lite-S Tag.
FeliCa Lite-S supports enhanced security functions, one of
them is the mutual authentication performed by this
method. The first part of mutual authentication is to
authenticate the tag with :meth:`FelicaLite.authenticate`. If
successful, the shared session key is used to generate the
integrity check value for write operation to update a specific
memory block. If that was successful then the tag is ensured
that the reader has the correct card key.
After successful authentication the
:meth:`~FelicaLite.read_with_mac` and :meth:`write_with_mac`
methods can be used to read and write data such that it can
not be falsified on transmission. | [
"Mutually",
"authenticate",
"with",
"a",
"FeliCa",
"Lite",
"-",
"S",
"Tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L882-L926 | train | 222,275 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | FelicaLiteS.write_with_mac | def write_with_mac(self, data, block):
"""Write one data block with additional integrity check.
If prior to calling this method the tag was not authenticated,
a :exc:`RuntimeError` exception is raised.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
# Write a single data block protected with a mac. The card
# will only accept the write if it computed the same mac.
log.debug("write 1 block with mac")
if len(data) != 16:
raise ValueError("data must be 16 octets")
if type(block) is not int:
raise ValueError("block number must be int")
if self._sk is None or self._iv is None:
raise RuntimeError("tag must be authenticated first")
# The write count is the first three byte of the wcnt block.
wcnt = str(self.read_without_mac(0x90)[0:3])
log.debug("write count is 0x{0}".format(wcnt[::-1].encode("hex")))
# We must generate the mac_a block to write the data. The data
# to encrypt to the mac is composed of write count and block
# numbers (8 byte) and the data we want to write. The mac for
# write must be generated with the key flipped (sk2 || sk1).
def flip(sk):
return sk[8:16] + sk[0:8]
data = wcnt + "\x00" + chr(block) + "\x00\x91\x00" + data
maca = self.generate_mac(data, flip(self._sk), self._iv) + wcnt+5*"\0"
# Now we can write the data block with our computed mac to the
# desired block and the maca block. Write without encryption
# means that the data is not encrypted with a service key.
sc_list = [tt3.ServiceCode(0, 0b001001)]
bc_list = [tt3.BlockCode(block), tt3.BlockCode(0x91)]
self.write_without_encryption(sc_list, bc_list, data[8:24] + maca) | python | def write_with_mac(self, data, block):
"""Write one data block with additional integrity check.
If prior to calling this method the tag was not authenticated,
a :exc:`RuntimeError` exception is raised.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
# Write a single data block protected with a mac. The card
# will only accept the write if it computed the same mac.
log.debug("write 1 block with mac")
if len(data) != 16:
raise ValueError("data must be 16 octets")
if type(block) is not int:
raise ValueError("block number must be int")
if self._sk is None or self._iv is None:
raise RuntimeError("tag must be authenticated first")
# The write count is the first three byte of the wcnt block.
wcnt = str(self.read_without_mac(0x90)[0:3])
log.debug("write count is 0x{0}".format(wcnt[::-1].encode("hex")))
# We must generate the mac_a block to write the data. The data
# to encrypt to the mac is composed of write count and block
# numbers (8 byte) and the data we want to write. The mac for
# write must be generated with the key flipped (sk2 || sk1).
def flip(sk):
return sk[8:16] + sk[0:8]
data = wcnt + "\x00" + chr(block) + "\x00\x91\x00" + data
maca = self.generate_mac(data, flip(self._sk), self._iv) + wcnt+5*"\0"
# Now we can write the data block with our computed mac to the
# desired block and the maca block. Write without encryption
# means that the data is not encrypted with a service key.
sc_list = [tt3.ServiceCode(0, 0b001001)]
bc_list = [tt3.BlockCode(block), tt3.BlockCode(0x91)]
self.write_without_encryption(sc_list, bc_list, data[8:24] + maca) | [
"def",
"write_with_mac",
"(",
"self",
",",
"data",
",",
"block",
")",
":",
"# Write a single data block protected with a mac. The card",
"# will only accept the write if it computed the same mac.",
"log",
".",
"debug",
"(",
"\"write 1 block with mac\"",
")",
"if",
"len",
"(",... | Write one data block with additional integrity check.
If prior to calling this method the tag was not authenticated,
a :exc:`RuntimeError` exception is raised.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Write",
"one",
"data",
"block",
"with",
"additional",
"integrity",
"check",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L928-L966 | train | 222,276 |
nfcpy/nfcpy | src/nfc/ndef/record.py | Record._read | def _read(self, f):
"""Parse an NDEF record from a file-like object."""
try:
self.header = ord(f.read(1))
except TypeError:
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
mbf = bool(self.header & 0x80)
mef = bool(self.header & 0x40)
cff = bool(self.header & 0x20)
srf = bool(self.header & 0x10)
ilf = bool(self.header & 0x08)
tnf = self.header & 0x07
try:
type_length = ord(f.read(1))
if srf: # short record
data_length = ord(f.read(1))
else: # 32-bit length
data_length = struct.unpack('>L', f.read(4))[0]
if ilf: # id length present
name_length = ord(f.read(1))
else:
name_length = 0
except (TypeError, struct.error):
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
try:
record_type = f.read(type_length)
assert len(record_type) == type_length
record_name = f.read(name_length)
assert len(record_name) == name_length
record_data = f.read(data_length)
assert len(record_data) == data_length
except AssertionError:
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
if tnf in (0, 5, 6) and len(record_type) > 0:
s = "ndef type name format {0} doesn't allow a type string"
raise FormatError( s.format(tnf) )
if tnf in (1, 2, 3, 4) and len(record_type) == 0:
s = "ndef type name format {0} requires a type string"
raise FormatError( s.format(tnf) )
if tnf == 0 and len(record_data) > 0:
s = "ndef type name format {0} doesn't allow a payload"
raise FormatError( s.format(tnf) )
self._message_begin, self._message_end = mbf, mef
self._type = bytearray(type_name_prefix[tnf] + record_type)
self._name = bytearray(record_name)
self._data = bytearray(record_data)
log.debug("parsed {0}".format(repr(self))) | python | def _read(self, f):
"""Parse an NDEF record from a file-like object."""
try:
self.header = ord(f.read(1))
except TypeError:
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
mbf = bool(self.header & 0x80)
mef = bool(self.header & 0x40)
cff = bool(self.header & 0x20)
srf = bool(self.header & 0x10)
ilf = bool(self.header & 0x08)
tnf = self.header & 0x07
try:
type_length = ord(f.read(1))
if srf: # short record
data_length = ord(f.read(1))
else: # 32-bit length
data_length = struct.unpack('>L', f.read(4))[0]
if ilf: # id length present
name_length = ord(f.read(1))
else:
name_length = 0
except (TypeError, struct.error):
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
try:
record_type = f.read(type_length)
assert len(record_type) == type_length
record_name = f.read(name_length)
assert len(record_name) == name_length
record_data = f.read(data_length)
assert len(record_data) == data_length
except AssertionError:
log.debug("buffer underflow at offset {0}".format(f.tell()))
raise LengthError("insufficient data to parse")
if tnf in (0, 5, 6) and len(record_type) > 0:
s = "ndef type name format {0} doesn't allow a type string"
raise FormatError( s.format(tnf) )
if tnf in (1, 2, 3, 4) and len(record_type) == 0:
s = "ndef type name format {0} requires a type string"
raise FormatError( s.format(tnf) )
if tnf == 0 and len(record_data) > 0:
s = "ndef type name format {0} doesn't allow a payload"
raise FormatError( s.format(tnf) )
self._message_begin, self._message_end = mbf, mef
self._type = bytearray(type_name_prefix[tnf] + record_type)
self._name = bytearray(record_name)
self._data = bytearray(record_data)
log.debug("parsed {0}".format(repr(self))) | [
"def",
"_read",
"(",
"self",
",",
"f",
")",
":",
"try",
":",
"self",
".",
"header",
"=",
"ord",
"(",
"f",
".",
"read",
"(",
"1",
")",
")",
"except",
"TypeError",
":",
"log",
".",
"debug",
"(",
"\"buffer underflow at offset {0}\"",
".",
"format",
"(",... | Parse an NDEF record from a file-like object. | [
"Parse",
"an",
"NDEF",
"record",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/record.py#L91-L146 | train | 222,277 |
nfcpy/nfcpy | src/nfc/ndef/record.py | Record._write | def _write(self, f):
"""Serialize an NDEF record to a file-like object."""
log.debug("writing ndef record at offset {0}".format(f.tell()))
record_type = self.type
record_name = self.name
record_data = self.data
if record_type == '':
header_flags = 0; record_name = ''; record_data = ''
elif record_type.startswith("urn:nfc:wkt:"):
header_flags = 1; record_type = record_type[12:]
elif re.match(r'[a-zA-Z0-9-]+/[a-zA-Z0-9-+.]+', record_type):
header_flags = 2; record_type = record_type
elif re.match(r'[a-zA-Z][a-zA-Z0-9+-.]*://', record_type):
header_flags = 3; record_type = record_type
elif record_type.startswith("urn:nfc:ext:"):
header_flags = 4; record_type = record_type[12:]
elif record_type == 'unknown':
header_flags = 5; record_type = ''
elif record_type == 'unchanged':
header_flags = 6; record_type = ''
type_length = len(record_type)
data_length = len(record_data)
name_length = len(record_name)
if self._message_begin:
header_flags |= 0x80
if self._message_end:
header_flags |= 0x40
if data_length < 256:
header_flags |= 0x10
if name_length > 0:
header_flags |= 0x08
if data_length < 256:
f.write(struct.pack(">BBB", header_flags, type_length, data_length))
else:
f.write(struct.pack(">BBL", header_flags, type_length, data_length))
if name_length > 0:
f.write(struct.pack(">B", name_length))
f.write(record_type)
f.write(record_name)
f.write(record_data) | python | def _write(self, f):
"""Serialize an NDEF record to a file-like object."""
log.debug("writing ndef record at offset {0}".format(f.tell()))
record_type = self.type
record_name = self.name
record_data = self.data
if record_type == '':
header_flags = 0; record_name = ''; record_data = ''
elif record_type.startswith("urn:nfc:wkt:"):
header_flags = 1; record_type = record_type[12:]
elif re.match(r'[a-zA-Z0-9-]+/[a-zA-Z0-9-+.]+', record_type):
header_flags = 2; record_type = record_type
elif re.match(r'[a-zA-Z][a-zA-Z0-9+-.]*://', record_type):
header_flags = 3; record_type = record_type
elif record_type.startswith("urn:nfc:ext:"):
header_flags = 4; record_type = record_type[12:]
elif record_type == 'unknown':
header_flags = 5; record_type = ''
elif record_type == 'unchanged':
header_flags = 6; record_type = ''
type_length = len(record_type)
data_length = len(record_data)
name_length = len(record_name)
if self._message_begin:
header_flags |= 0x80
if self._message_end:
header_flags |= 0x40
if data_length < 256:
header_flags |= 0x10
if name_length > 0:
header_flags |= 0x08
if data_length < 256:
f.write(struct.pack(">BBB", header_flags, type_length, data_length))
else:
f.write(struct.pack(">BBL", header_flags, type_length, data_length))
if name_length > 0:
f.write(struct.pack(">B", name_length))
f.write(record_type)
f.write(record_name)
f.write(record_data) | [
"def",
"_write",
"(",
"self",
",",
"f",
")",
":",
"log",
".",
"debug",
"(",
"\"writing ndef record at offset {0}\"",
".",
"format",
"(",
"f",
".",
"tell",
"(",
")",
")",
")",
"record_type",
"=",
"self",
".",
"type",
"record_name",
"=",
"self",
".",
"na... | Serialize an NDEF record to a file-like object. | [
"Serialize",
"an",
"NDEF",
"record",
"to",
"a",
"file",
"-",
"like",
"object",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/ndef/record.py#L148-L193 | train | 222,278 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | ServiceCode.pack | def pack(self):
"""Pack the service code for transmission. Returns a 2 byte string."""
sn, sa = self.number, self.attribute
return pack("<H", (sn & 0x3ff) << 6 | (sa & 0x3f)) | python | def pack(self):
"""Pack the service code for transmission. Returns a 2 byte string."""
sn, sa = self.number, self.attribute
return pack("<H", (sn & 0x3ff) << 6 | (sa & 0x3f)) | [
"def",
"pack",
"(",
"self",
")",
":",
"sn",
",",
"sa",
"=",
"self",
".",
"number",
",",
"self",
".",
"attribute",
"return",
"pack",
"(",
"\"<H\"",
",",
"(",
"sn",
"&",
"0x3ff",
")",
"<<",
"6",
"|",
"(",
"sa",
"&",
"0x3f",
")",
")"
] | Pack the service code for transmission. Returns a 2 byte string. | [
"Pack",
"the",
"service",
"code",
"for",
"transmission",
".",
"Returns",
"a",
"2",
"byte",
"string",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L97-L100 | train | 222,279 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | BlockCode.pack | def pack(self):
"""Pack the block code for transmission. Returns a 2-3 byte string."""
bn, am, sx = self.number, self.access, self.service
return chr(bool(bn < 256) << 7 | (am & 0x7) << 4 | (sx & 0xf)) + \
(chr(bn) if bn < 256 else pack("<H", bn)) | python | def pack(self):
"""Pack the block code for transmission. Returns a 2-3 byte string."""
bn, am, sx = self.number, self.access, self.service
return chr(bool(bn < 256) << 7 | (am & 0x7) << 4 | (sx & 0xf)) + \
(chr(bn) if bn < 256 else pack("<H", bn)) | [
"def",
"pack",
"(",
"self",
")",
":",
"bn",
",",
"am",
",",
"sx",
"=",
"self",
".",
"number",
",",
"self",
".",
"access",
",",
"self",
".",
"service",
"return",
"chr",
"(",
"bool",
"(",
"bn",
"<",
"256",
")",
"<<",
"7",
"|",
"(",
"am",
"&",
... | Pack the block code for transmission. Returns a 2-3 byte string. | [
"Pack",
"the",
"block",
"code",
"for",
"transmission",
".",
"Returns",
"a",
"2",
"-",
"3",
"byte",
"string",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L129-L133 | train | 222,280 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.dump_service | def dump_service(self, sc):
"""Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number of data blocks because a range
of data blocks with equal content is reduced to fewer lines of
output.
"""
def lprint(fmt, data, index):
ispchr = lambda x: x >= 32 and x <= 126 # noqa: E731
def print_bytes(octets):
return ' '.join(['%02x' % x for x in octets])
def print_chars(octets):
return ''.join([chr(x) if ispchr(x) else '.' for x in octets])
return fmt.format(index, print_bytes(data), print_chars(data))
data_line_fmt = "{0:04X}: {1} |{2}|"
same_line_fmt = "{0:<4s} {1} |{2}|"
lines = list()
last_data = None
same_data = 0
for i in itertools.count(): # pragma: no branch
assert i < 0x10000
try:
this_data = self.read_without_encryption([sc], [BlockCode(i)])
except Type3TagCommandError:
i = i - 1
break
if this_data == last_data:
same_data += 1
else:
if same_data > 1:
lines.append(lprint(same_line_fmt, last_data, "*"))
lines.append(lprint(data_line_fmt, this_data, i))
last_data = this_data
same_data = 0
if same_data > 1:
lines.append(lprint(same_line_fmt, last_data, "*"))
if same_data > 0:
lines.append(lprint(data_line_fmt, this_data, i))
return lines | python | def dump_service(self, sc):
"""Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number of data blocks because a range
of data blocks with equal content is reduced to fewer lines of
output.
"""
def lprint(fmt, data, index):
ispchr = lambda x: x >= 32 and x <= 126 # noqa: E731
def print_bytes(octets):
return ' '.join(['%02x' % x for x in octets])
def print_chars(octets):
return ''.join([chr(x) if ispchr(x) else '.' for x in octets])
return fmt.format(index, print_bytes(data), print_chars(data))
data_line_fmt = "{0:04X}: {1} |{2}|"
same_line_fmt = "{0:<4s} {1} |{2}|"
lines = list()
last_data = None
same_data = 0
for i in itertools.count(): # pragma: no branch
assert i < 0x10000
try:
this_data = self.read_without_encryption([sc], [BlockCode(i)])
except Type3TagCommandError:
i = i - 1
break
if this_data == last_data:
same_data += 1
else:
if same_data > 1:
lines.append(lprint(same_line_fmt, last_data, "*"))
lines.append(lprint(data_line_fmt, this_data, i))
last_data = this_data
same_data = 0
if same_data > 1:
lines.append(lprint(same_line_fmt, last_data, "*"))
if same_data > 0:
lines.append(lprint(data_line_fmt, this_data, i))
return lines | [
"def",
"dump_service",
"(",
"self",
",",
"sc",
")",
":",
"def",
"lprint",
"(",
"fmt",
",",
"data",
",",
"index",
")",
":",
"ispchr",
"=",
"lambda",
"x",
":",
"x",
">=",
"32",
"and",
"x",
"<=",
"126",
"# noqa: E731",
"def",
"print_bytes",
"(",
"octe... | Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number of data blocks because a range
of data blocks with equal content is reduced to fewer lines of
output. | [
"Read",
"all",
"data",
"blocks",
"of",
"a",
"given",
"service",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L284-L335 | train | 222,281 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.format | def format(self, version=None, wipe=None):
"""Format and blank an NFC Forum Type 3 Tag.
A generic NFC Forum Type 3 Tag can be (re)formatted if it is
in either one of blank, initialized or readwrite state. By
formatting, all contents of the attribute information block is
overwritten with values determined. The number of user data
blocks is determined by reading all memory until an error
response. Similarily, the maximum number of data block that
can be read or written with a single command is determined by
sending successively increased read and write commands. The
current data length is set to zero. The NDEF mapping version
is set to the latest known version number (1.0), unless the
*version* argument is provided and it's major version number
corresponds to one of the known major version numbers.
By default, no data other than the attribute block is
modified. To overwrite user data the *wipe* argument must be
set to an integer value. The lower 8 bits of that value are
written to all data bytes that follow the attribute block.
"""
return super(Type3Tag, self).format(version, wipe) | python | def format(self, version=None, wipe=None):
"""Format and blank an NFC Forum Type 3 Tag.
A generic NFC Forum Type 3 Tag can be (re)formatted if it is
in either one of blank, initialized or readwrite state. By
formatting, all contents of the attribute information block is
overwritten with values determined. The number of user data
blocks is determined by reading all memory until an error
response. Similarily, the maximum number of data block that
can be read or written with a single command is determined by
sending successively increased read and write commands. The
current data length is set to zero. The NDEF mapping version
is set to the latest known version number (1.0), unless the
*version* argument is provided and it's major version number
corresponds to one of the known major version numbers.
By default, no data other than the attribute block is
modified. To overwrite user data the *wipe* argument must be
set to an integer value. The lower 8 bits of that value are
written to all data bytes that follow the attribute block.
"""
return super(Type3Tag, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"None",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"Type3Tag",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | Format and blank an NFC Forum Type 3 Tag.
A generic NFC Forum Type 3 Tag can be (re)formatted if it is
in either one of blank, initialized or readwrite state. By
formatting, all contents of the attribute information block is
overwritten with values determined. The number of user data
blocks is determined by reading all memory until an error
response. Similarily, the maximum number of data block that
can be read or written with a single command is determined by
sending successively increased read and write commands. The
current data length is set to zero. The NDEF mapping version
is set to the latest known version number (1.0), unless the
*version* argument is provided and it's major version number
corresponds to one of the known major version numbers.
By default, no data other than the attribute block is
modified. To overwrite user data the *wipe* argument must be
set to an integer value. The lower 8 bits of that value are
written to all data bytes that follow the attribute block. | [
"Format",
"and",
"blank",
"an",
"NFC",
"Forum",
"Type",
"3",
"Tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L337-L359 | train | 222,282 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.polling | def polling(self, system_code=0xffff, request_code=0, time_slots=0):
"""Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
card can have multiple systems. The first system that matches
*system_code* will be activated. A value of 0xff for any of
the two bytes works as a wildcard, thus 0xffff activates the
very first system in the card. The card identification data
returned are the Manufacture ID (IDm) and Manufacture
Parameter (PMm).
The *request_code* tells the card whether it should return
additional information. The default value 0 requests no
additional information. Request code 1 means that the card
shall also return the system code, so polling for system code
0xffff with request code 1 can be used to identify the first
system on the card. Request code 2 asks for communication
performance data, more precisely a bitmap of possible
communication speeds. Not all cards provide that information.
The number of *time_slots* determines whether there's a chance
to receive a response if multiple Type 3 Tags are in the
field. For the reader the number of time slots determines the
amount of time to wait for a response. Any Type 3 Tag in the
field, i.e. powered by the field, will choose a random time
slot to respond. With the default *time_slots* value 0 there
will only be one time slot available for all responses and
multiple responses would produce a collision. More time slots
reduce the chance of collisions (but may result in an
application working with a tag that was just accidentially
close enough). Only specific values should be used for
*time_slots*, those are 0, 1, 3, 7, and 15. Other values may
produce unexpected results depending on the tag product.
:meth:`polling` returns either the tuple (IDm, PMm) or the
tuple (IDm, PMm, *additional information*) depending on the
response lengt, all as bytearrays.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("polling for system 0x{0:04x}".format(system_code))
if time_slots not in (0, 1, 3, 7, 15):
log.debug("invalid number of time slots: {0}".format(time_slots))
raise ValueError("invalid number of time slots")
if request_code not in (0, 1, 2):
log.debug("invalid request code value: {0}".format(request_code))
raise ValueError("invalid request code for polling")
timeout = 0.003625 + time_slots * 0.001208
data = pack(">HBB", system_code, request_code, time_slots)
data = self.send_cmd_recv_rsp(0x00, data, timeout, send_idm=False)
if len(data) != (16 if request_code == 0 else 18):
log.debug("unexpected polling response length")
raise Type3TagCommandError(DATA_SIZE_ERROR)
return (data[0:8], data[8:16]) if len(data) == 16 else \
(data[0:8], data[8:16], data[16:18]) | python | def polling(self, system_code=0xffff, request_code=0, time_slots=0):
"""Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
card can have multiple systems. The first system that matches
*system_code* will be activated. A value of 0xff for any of
the two bytes works as a wildcard, thus 0xffff activates the
very first system in the card. The card identification data
returned are the Manufacture ID (IDm) and Manufacture
Parameter (PMm).
The *request_code* tells the card whether it should return
additional information. The default value 0 requests no
additional information. Request code 1 means that the card
shall also return the system code, so polling for system code
0xffff with request code 1 can be used to identify the first
system on the card. Request code 2 asks for communication
performance data, more precisely a bitmap of possible
communication speeds. Not all cards provide that information.
The number of *time_slots* determines whether there's a chance
to receive a response if multiple Type 3 Tags are in the
field. For the reader the number of time slots determines the
amount of time to wait for a response. Any Type 3 Tag in the
field, i.e. powered by the field, will choose a random time
slot to respond. With the default *time_slots* value 0 there
will only be one time slot available for all responses and
multiple responses would produce a collision. More time slots
reduce the chance of collisions (but may result in an
application working with a tag that was just accidentially
close enough). Only specific values should be used for
*time_slots*, those are 0, 1, 3, 7, and 15. Other values may
produce unexpected results depending on the tag product.
:meth:`polling` returns either the tuple (IDm, PMm) or the
tuple (IDm, PMm, *additional information*) depending on the
response lengt, all as bytearrays.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
log.debug("polling for system 0x{0:04x}".format(system_code))
if time_slots not in (0, 1, 3, 7, 15):
log.debug("invalid number of time slots: {0}".format(time_slots))
raise ValueError("invalid number of time slots")
if request_code not in (0, 1, 2):
log.debug("invalid request code value: {0}".format(request_code))
raise ValueError("invalid request code for polling")
timeout = 0.003625 + time_slots * 0.001208
data = pack(">HBB", system_code, request_code, time_slots)
data = self.send_cmd_recv_rsp(0x00, data, timeout, send_idm=False)
if len(data) != (16 if request_code == 0 else 18):
log.debug("unexpected polling response length")
raise Type3TagCommandError(DATA_SIZE_ERROR)
return (data[0:8], data[8:16]) if len(data) == 16 else \
(data[0:8], data[8:16], data[16:18]) | [
"def",
"polling",
"(",
"self",
",",
"system_code",
"=",
"0xffff",
",",
"request_code",
"=",
"0",
",",
"time_slots",
"=",
"0",
")",
":",
"log",
".",
"debug",
"(",
"\"polling for system 0x{0:04x}\"",
".",
"format",
"(",
"system_code",
")",
")",
"if",
"time_s... | Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
card can have multiple systems. The first system that matches
*system_code* will be activated. A value of 0xff for any of
the two bytes works as a wildcard, thus 0xffff activates the
very first system in the card. The card identification data
returned are the Manufacture ID (IDm) and Manufacture
Parameter (PMm).
The *request_code* tells the card whether it should return
additional information. The default value 0 requests no
additional information. Request code 1 means that the card
shall also return the system code, so polling for system code
0xffff with request code 1 can be used to identify the first
system on the card. Request code 2 asks for communication
performance data, more precisely a bitmap of possible
communication speeds. Not all cards provide that information.
The number of *time_slots* determines whether there's a chance
to receive a response if multiple Type 3 Tags are in the
field. For the reader the number of time slots determines the
amount of time to wait for a response. Any Type 3 Tag in the
field, i.e. powered by the field, will choose a random time
slot to respond. With the default *time_slots* value 0 there
will only be one time slot available for all responses and
multiple responses would produce a collision. More time slots
reduce the chance of collisions (but may result in an
application working with a tag that was just accidentially
close enough). Only specific values should be used for
*time_slots*, those are 0, 1, 3, 7, and 15. Other values may
produce unexpected results depending on the tag product.
:meth:`polling` returns either the tuple (IDm, PMm) or the
tuple (IDm, PMm, *additional information*) depending on the
response lengt, all as bytearrays.
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Aquire",
"and",
"identify",
"a",
"card",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L452-L513 | train | 222,283 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.read_from_ndef_service | def read_from_ndef_service(self, *blocks):
"""Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block numbers
to read. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of reading 32 byte data from from blocks 1 and 8.::
data = tag.read_from_ndef_service(1, 8)
data = tag.read_from_ndef_service(*list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
if self.sys == 0x12FC:
sc_list = [ServiceCode(0, 0b001011)]
bc_list = [BlockCode(n) for n in blocks]
return self.read_without_encryption(sc_list, bc_list) | python | def read_from_ndef_service(self, *blocks):
"""Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block numbers
to read. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of reading 32 byte data from from blocks 1 and 8.::
data = tag.read_from_ndef_service(1, 8)
data = tag.read_from_ndef_service(*list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
if self.sys == 0x12FC:
sc_list = [ServiceCode(0, 0b001011)]
bc_list = [BlockCode(n) for n in blocks]
return self.read_without_encryption(sc_list, bc_list) | [
"def",
"read_from_ndef_service",
"(",
"self",
",",
"*",
"blocks",
")",
":",
"if",
"self",
".",
"sys",
"==",
"0x12FC",
":",
"sc_list",
"=",
"[",
"ServiceCode",
"(",
"0",
",",
"0b001011",
")",
"]",
"bc_list",
"=",
"[",
"BlockCode",
"(",
"n",
")",
"for"... | Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block numbers
to read. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of reading 32 byte data from from blocks 1 and 8.::
data = tag.read_from_ndef_service(1, 8)
data = tag.read_from_ndef_service(*list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Read",
"block",
"data",
"from",
"an",
"NDEF",
"compatible",
"tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L568-L587 | train | 222,284 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.write_without_encryption | def write_without_encryption(self, service_list, block_list, data):
"""Write data blocks to unencrypted services.
This method sends a Write Without Encryption command to the
tag. The data blocks to overwrite are indicated by a sequence
of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter
*block_list*. Each block code must reference one of the
:class:`~nfc.tag.tt3.ServiceCode` objects in the iterable
*service_list*. If any of the blocks or services do not exist,
the tag will stop processing at that point and return a two
byte error status. The status bytes become the
:attr:`~nfc.tag.TagCommandError.errno` value of the
:exc:`~nfc.tag.TagCommandError` exception. The *data* to write
must be a byte string or array of length ``16 *
len(block_list)``.
As an example, the following code writes ``16 * "\\xAA"`` to
block 5 of service 16, ``16 * "\\xBB"`` to block 0 of service
80 and ``16 * "\\xCC"`` to block 1 of service 80 (all services
are writeable without key)::
sc1 = nfc.tag.tt3.ServiceCode(16, 0x09)
sc2 = nfc.tag.tt3.ServiceCode(80, 0x09)
bc1 = nfc.tag.tt3.BlockCode(5, service=0)
bc2 = nfc.tag.tt3.BlockCode(0, service=1)
bc3 = nfc.tag.tt3.BlockCode(1, service=1)
sc_list = [sc1, sc2]
bc_list = [bc1, bc2, bc3]
data = 16 * "\\xAA" + 16 * "\\xBB" + 16 * "\\xCC"
try:
data = tag.write_without_encryption(sc_list, bc_list, data)
except nfc.tag.TagCommandError as e:
if e.errno > 0x00FF:
print("the tag returned an error status")
else:
print("command failed with some other error")
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
a, b, e = self.pmm[6] & 7, self.pmm[6] >> 3 & 7, self.pmm[6] >> 6
timeout = 302.1E-6 * ((b + 1) * len(block_list) + a + 1) * 4**e
data = (chr(len(service_list))
+ ''.join([sc.pack() for sc in service_list])
+ chr(len(block_list))
+ ''.join([bc.pack() for bc in block_list])
+ data)
log.debug("write w/o encryption service/block list: {0} / {1}".format(
' '.join([hexlify(sc.pack()) for sc in service_list]),
' '.join([hexlify(bc.pack()) for bc in block_list])))
self.send_cmd_recv_rsp(0x08, data, timeout) | python | def write_without_encryption(self, service_list, block_list, data):
"""Write data blocks to unencrypted services.
This method sends a Write Without Encryption command to the
tag. The data blocks to overwrite are indicated by a sequence
of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter
*block_list*. Each block code must reference one of the
:class:`~nfc.tag.tt3.ServiceCode` objects in the iterable
*service_list*. If any of the blocks or services do not exist,
the tag will stop processing at that point and return a two
byte error status. The status bytes become the
:attr:`~nfc.tag.TagCommandError.errno` value of the
:exc:`~nfc.tag.TagCommandError` exception. The *data* to write
must be a byte string or array of length ``16 *
len(block_list)``.
As an example, the following code writes ``16 * "\\xAA"`` to
block 5 of service 16, ``16 * "\\xBB"`` to block 0 of service
80 and ``16 * "\\xCC"`` to block 1 of service 80 (all services
are writeable without key)::
sc1 = nfc.tag.tt3.ServiceCode(16, 0x09)
sc2 = nfc.tag.tt3.ServiceCode(80, 0x09)
bc1 = nfc.tag.tt3.BlockCode(5, service=0)
bc2 = nfc.tag.tt3.BlockCode(0, service=1)
bc3 = nfc.tag.tt3.BlockCode(1, service=1)
sc_list = [sc1, sc2]
bc_list = [bc1, bc2, bc3]
data = 16 * "\\xAA" + 16 * "\\xBB" + 16 * "\\xCC"
try:
data = tag.write_without_encryption(sc_list, bc_list, data)
except nfc.tag.TagCommandError as e:
if e.errno > 0x00FF:
print("the tag returned an error status")
else:
print("command failed with some other error")
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
a, b, e = self.pmm[6] & 7, self.pmm[6] >> 3 & 7, self.pmm[6] >> 6
timeout = 302.1E-6 * ((b + 1) * len(block_list) + a + 1) * 4**e
data = (chr(len(service_list))
+ ''.join([sc.pack() for sc in service_list])
+ chr(len(block_list))
+ ''.join([bc.pack() for bc in block_list])
+ data)
log.debug("write w/o encryption service/block list: {0} / {1}".format(
' '.join([hexlify(sc.pack()) for sc in service_list]),
' '.join([hexlify(bc.pack()) for bc in block_list])))
self.send_cmd_recv_rsp(0x08, data, timeout) | [
"def",
"write_without_encryption",
"(",
"self",
",",
"service_list",
",",
"block_list",
",",
"data",
")",
":",
"a",
",",
"b",
",",
"e",
"=",
"self",
".",
"pmm",
"[",
"6",
"]",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"6",
"]",
">>",
"3",
"&",
"7... | Write data blocks to unencrypted services.
This method sends a Write Without Encryption command to the
tag. The data blocks to overwrite are indicated by a sequence
of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter
*block_list*. Each block code must reference one of the
:class:`~nfc.tag.tt3.ServiceCode` objects in the iterable
*service_list*. If any of the blocks or services do not exist,
the tag will stop processing at that point and return a two
byte error status. The status bytes become the
:attr:`~nfc.tag.TagCommandError.errno` value of the
:exc:`~nfc.tag.TagCommandError` exception. The *data* to write
must be a byte string or array of length ``16 *
len(block_list)``.
As an example, the following code writes ``16 * "\\xAA"`` to
block 5 of service 16, ``16 * "\\xBB"`` to block 0 of service
80 and ``16 * "\\xCC"`` to block 1 of service 80 (all services
are writeable without key)::
sc1 = nfc.tag.tt3.ServiceCode(16, 0x09)
sc2 = nfc.tag.tt3.ServiceCode(80, 0x09)
bc1 = nfc.tag.tt3.BlockCode(5, service=0)
bc2 = nfc.tag.tt3.BlockCode(0, service=1)
bc3 = nfc.tag.tt3.BlockCode(1, service=1)
sc_list = [sc1, sc2]
bc_list = [bc1, bc2, bc3]
data = 16 * "\\xAA" + 16 * "\\xBB" + 16 * "\\xCC"
try:
data = tag.write_without_encryption(sc_list, bc_list, data)
except nfc.tag.TagCommandError as e:
if e.errno > 0x00FF:
print("the tag returned an error status")
else:
print("command failed with some other error")
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Write",
"data",
"blocks",
"to",
"unencrypted",
"services",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L589-L642 | train | 222,285 |
nfcpy/nfcpy | src/nfc/tag/tt3.py | Type3Tag.write_to_ndef_service | def write_to_ndef_service(self, data, *blocks):
"""Write block data to an NDEF compatible tag.
This is a convinience method to write block data to a tag that
has system code 0x12FC (NDEF). For other tags this method
simply does nothing. The *data* to write must be a string or
bytearray with length equal ``16 * len(blocks)``. All
parameters following *data* are interpreted as block numbers
to write. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of writing 32 byte zeros into blocks 1 and 8.::
tag.write_to_ndef_service(32 * "\\0", 1, 8)
tag.write_to_ndef_service(32 * "\\0", *list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
if self.sys == 0x12FC:
sc_list = [ServiceCode(0, 0b001001)]
bc_list = [BlockCode(n) for n in blocks]
self.write_without_encryption(sc_list, bc_list, data) | python | def write_to_ndef_service(self, data, *blocks):
"""Write block data to an NDEF compatible tag.
This is a convinience method to write block data to a tag that
has system code 0x12FC (NDEF). For other tags this method
simply does nothing. The *data* to write must be a string or
bytearray with length equal ``16 * len(blocks)``. All
parameters following *data* are interpreted as block numbers
to write. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of writing 32 byte zeros into blocks 1 and 8.::
tag.write_to_ndef_service(32 * "\\0", 1, 8)
tag.write_to_ndef_service(32 * "\\0", *list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
"""
if self.sys == 0x12FC:
sc_list = [ServiceCode(0, 0b001001)]
bc_list = [BlockCode(n) for n in blocks]
self.write_without_encryption(sc_list, bc_list, data) | [
"def",
"write_to_ndef_service",
"(",
"self",
",",
"data",
",",
"*",
"blocks",
")",
":",
"if",
"self",
".",
"sys",
"==",
"0x12FC",
":",
"sc_list",
"=",
"[",
"ServiceCode",
"(",
"0",
",",
"0b001001",
")",
"]",
"bc_list",
"=",
"[",
"BlockCode",
"(",
"n"... | Write block data to an NDEF compatible tag.
This is a convinience method to write block data to a tag that
has system code 0x12FC (NDEF). For other tags this method
simply does nothing. The *data* to write must be a string or
bytearray with length equal ``16 * len(blocks)``. All
parameters following *data* are interpreted as block numbers
to write. To actually pass a list of block numbers requires
unpacking. The following example calls would have the same
effect of writing 32 byte zeros into blocks 1 and 8.::
tag.write_to_ndef_service(32 * "\\0", 1, 8)
tag.write_to_ndef_service(32 * "\\0", *list(1, 8))
Command execution errors raise :exc:`~nfc.tag.TagCommandError`. | [
"Write",
"block",
"data",
"to",
"an",
"NDEF",
"compatible",
"tag",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L644-L665 | train | 222,286 |
nfcpy/nfcpy | src/nfc/clf/__init__.py | ContactlessFrontend.close | def close(self):
"""Close the contacless reader device."""
with self.lock:
if self.device is not None:
try:
self.device.close()
except IOError:
pass
self.device = None | python | def close(self):
"""Close the contacless reader device."""
with self.lock:
if self.device is not None:
try:
self.device.close()
except IOError:
pass
self.device = None | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"device",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"device",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"pass",
"self",
".",
"device",
"=... | Close the contacless reader device. | [
"Close",
"the",
"contacless",
"reader",
"device",
"."
] | 6649146d1afdd5e82b2b6b1ea00aa58d50785117 | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/__init__.py#L155-L163 | train | 222,287 |
cloudnativelabs/kube-shell | kubeshell/parser.py | Parser.build | def build(self, root, schema):
""" Build the syntax tree for kubectl command line """
if schema.get("subcommands") and schema["subcommands"]:
for subcmd, childSchema in schema["subcommands"].items():
child = CommandTree(node=subcmd)
child = self.build(child, childSchema)
root.children.append(child)
# {args: {}, options: {}, help: ""}
root.help = schema.get("help")
for name, desc in schema.get("options").items():
if root.node == "kubectl": # register global flags
self.globalFlags.append(Option(name, desc["help"]))
root.localFlags.append(Option(name, desc["help"]))
for arg in schema.get("args"):
node = CommandTree(node=arg)
root.children.append(node)
return root | python | def build(self, root, schema):
""" Build the syntax tree for kubectl command line """
if schema.get("subcommands") and schema["subcommands"]:
for subcmd, childSchema in schema["subcommands"].items():
child = CommandTree(node=subcmd)
child = self.build(child, childSchema)
root.children.append(child)
# {args: {}, options: {}, help: ""}
root.help = schema.get("help")
for name, desc in schema.get("options").items():
if root.node == "kubectl": # register global flags
self.globalFlags.append(Option(name, desc["help"]))
root.localFlags.append(Option(name, desc["help"]))
for arg in schema.get("args"):
node = CommandTree(node=arg)
root.children.append(node)
return root | [
"def",
"build",
"(",
"self",
",",
"root",
",",
"schema",
")",
":",
"if",
"schema",
".",
"get",
"(",
"\"subcommands\"",
")",
"and",
"schema",
"[",
"\"subcommands\"",
"]",
":",
"for",
"subcmd",
",",
"childSchema",
"in",
"schema",
"[",
"\"subcommands\"",
"]... | Build the syntax tree for kubectl command line | [
"Build",
"the",
"syntax",
"tree",
"for",
"kubectl",
"command",
"line"
] | adc801d165e87fe62f82b074ec49996954c3fbe8 | https://github.com/cloudnativelabs/kube-shell/blob/adc801d165e87fe62f82b074ec49996954c3fbe8/kubeshell/parser.py#L45-L61 | train | 222,288 |
cloudnativelabs/kube-shell | kubeshell/parser.py | Parser.parse_tokens | def parse_tokens(self, tokens):
""" Parse a sequence of tokens
returns tuple of (parsed tokens, suggestions)
"""
if len(tokens) == 1:
return list(), tokens, {"kubectl": self.ast.help}
else:
tokens.reverse()
parsed, unparsed, suggestions = self.treewalk(self.ast, parsed=list(), unparsed=tokens)
if not suggestions and unparsed:
# TODO: @vogxn: This is hack until we include expected value types for each option and argument.
# Whenver we recieve no suggestions but are left with unparsed tokens we pop the value and walk the
# tree again without values
logger.debug("unparsed tokens remain, possible value encountered")
unparsed.pop()
parsed.reverse()
unparsed.extend(parsed)
logger.debug("resuming treewalk with tokens: %s", unparsed)
return self.treewalk(self.ast, parsed=list(), unparsed=unparsed)
else:
return parsed, unparsed, suggestions | python | def parse_tokens(self, tokens):
""" Parse a sequence of tokens
returns tuple of (parsed tokens, suggestions)
"""
if len(tokens) == 1:
return list(), tokens, {"kubectl": self.ast.help}
else:
tokens.reverse()
parsed, unparsed, suggestions = self.treewalk(self.ast, parsed=list(), unparsed=tokens)
if not suggestions and unparsed:
# TODO: @vogxn: This is hack until we include expected value types for each option and argument.
# Whenver we recieve no suggestions but are left with unparsed tokens we pop the value and walk the
# tree again without values
logger.debug("unparsed tokens remain, possible value encountered")
unparsed.pop()
parsed.reverse()
unparsed.extend(parsed)
logger.debug("resuming treewalk with tokens: %s", unparsed)
return self.treewalk(self.ast, parsed=list(), unparsed=unparsed)
else:
return parsed, unparsed, suggestions | [
"def",
"parse_tokens",
"(",
"self",
",",
"tokens",
")",
":",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
":",
"return",
"list",
"(",
")",
",",
"tokens",
",",
"{",
"\"kubectl\"",
":",
"self",
".",
"ast",
".",
"help",
"}",
"else",
":",
"tokens",
".... | Parse a sequence of tokens
returns tuple of (parsed tokens, suggestions) | [
"Parse",
"a",
"sequence",
"of",
"tokens"
] | adc801d165e87fe62f82b074ec49996954c3fbe8 | https://github.com/cloudnativelabs/kube-shell/blob/adc801d165e87fe62f82b074ec49996954c3fbe8/kubeshell/parser.py#L69-L90 | train | 222,289 |
cloudnativelabs/kube-shell | kubeshell/parser.py | Parser.treewalk | def treewalk(self, root, parsed, unparsed):
""" Recursively walks the syntax tree at root and returns
the items parsed, unparsed and possible suggestions """
suggestions = dict()
if not unparsed:
logger.debug("no tokens left unparsed. returning %s, %s", parsed, suggestions)
return parsed, unparsed, suggestions
token = unparsed.pop().strip()
logger.debug("begin parsing at %s w/ tokens: %s", root.node, unparsed)
if root.node == token:
logger.debug("root node: %s matches next token:%s", root.node, token)
parsed.append(token)
if self.peekForOption(unparsed): # check for localFlags and globalFlags
logger.debug("option(s) upcoming %s", unparsed)
parsed_opts, unparsed, suggestions = self.evalOptions(root, list(), unparsed[:])
if parsed_opts:
logger.debug("parsed option(s): %s", parsed_opts)
parsed.extend(parsed_opts)
if unparsed and not self.peekForOption(unparsed): # unparsed bits without options
logger.debug("begin subtree %s parsing", root.node)
for child in root.children:
parsed_subtree, unparsed, suggestions = self.treewalk(child, list(), unparsed[:])
if parsed_subtree: # subtree returned further parsed tokens
parsed.extend(parsed_subtree)
logger.debug("subtree at: %s has matches. %s, %s", child.node, parsed, unparsed)
break
else:
# no matches found in command tree
# return children of root as suggestions
logger.debug("no matches in subtree: %s. returning children as suggestions", root.node)
for child in root.children:
suggestions[child.node] = child.help
else:
logger.debug("no token or option match")
unparsed.append(token)
return parsed, unparsed, suggestions | python | def treewalk(self, root, parsed, unparsed):
""" Recursively walks the syntax tree at root and returns
the items parsed, unparsed and possible suggestions """
suggestions = dict()
if not unparsed:
logger.debug("no tokens left unparsed. returning %s, %s", parsed, suggestions)
return parsed, unparsed, suggestions
token = unparsed.pop().strip()
logger.debug("begin parsing at %s w/ tokens: %s", root.node, unparsed)
if root.node == token:
logger.debug("root node: %s matches next token:%s", root.node, token)
parsed.append(token)
if self.peekForOption(unparsed): # check for localFlags and globalFlags
logger.debug("option(s) upcoming %s", unparsed)
parsed_opts, unparsed, suggestions = self.evalOptions(root, list(), unparsed[:])
if parsed_opts:
logger.debug("parsed option(s): %s", parsed_opts)
parsed.extend(parsed_opts)
if unparsed and not self.peekForOption(unparsed): # unparsed bits without options
logger.debug("begin subtree %s parsing", root.node)
for child in root.children:
parsed_subtree, unparsed, suggestions = self.treewalk(child, list(), unparsed[:])
if parsed_subtree: # subtree returned further parsed tokens
parsed.extend(parsed_subtree)
logger.debug("subtree at: %s has matches. %s, %s", child.node, parsed, unparsed)
break
else:
# no matches found in command tree
# return children of root as suggestions
logger.debug("no matches in subtree: %s. returning children as suggestions", root.node)
for child in root.children:
suggestions[child.node] = child.help
else:
logger.debug("no token or option match")
unparsed.append(token)
return parsed, unparsed, suggestions | [
"def",
"treewalk",
"(",
"self",
",",
"root",
",",
"parsed",
",",
"unparsed",
")",
":",
"suggestions",
"=",
"dict",
"(",
")",
"if",
"not",
"unparsed",
":",
"logger",
".",
"debug",
"(",
"\"no tokens left unparsed. returning %s, %s\"",
",",
"parsed",
",",
"sugg... | Recursively walks the syntax tree at root and returns
the items parsed, unparsed and possible suggestions | [
"Recursively",
"walks",
"the",
"syntax",
"tree",
"at",
"root",
"and",
"returns",
"the",
"items",
"parsed",
"unparsed",
"and",
"possible",
"suggestions"
] | adc801d165e87fe62f82b074ec49996954c3fbe8 | https://github.com/cloudnativelabs/kube-shell/blob/adc801d165e87fe62f82b074ec49996954c3fbe8/kubeshell/parser.py#L92-L128 | train | 222,290 |
cloudnativelabs/kube-shell | kubeshell/parser.py | Parser.evalOptions | def evalOptions(self, root, parsed, unparsed):
""" Evaluate only the options and return flags as suggestions """
logger.debug("parsing options at tree: %s with p:%s, u:%s", root.node, parsed, unparsed)
suggestions = dict()
token = unparsed.pop().strip()
parts = token.partition('=')
if parts[-1] != '': # parsing for --option=value type input
token = parts[0]
allFlags = root.localFlags + self.globalFlags
for flag in allFlags:
if flag.name == token:
logger.debug("matched token: %s with flag: %s", token, flag.name)
parsed.append(token)
if self.peekForOption(unparsed): # recursively look for further options
parsed, unparsed, suggestions = self.evalOptions(root, parsed, unparsed[:])
# elif token == "--namespace":
# namespaces = [('default', None), ('minikube', None), ('gitlab', None)] # self.kube_client.get_resource("namespace")
# suggestions = dict(namespaces)
break
else:
logger.debug("no flags match, returning allFlags suggestions")
for flag in allFlags:
suggestions[flag.name] = flag.helptext
if suggestions: # incomplete parse, replace token
logger.debug("incomplete option: %s provided. returning suggestions", token)
unparsed.append(token)
return parsed, unparsed, suggestions | python | def evalOptions(self, root, parsed, unparsed):
""" Evaluate only the options and return flags as suggestions """
logger.debug("parsing options at tree: %s with p:%s, u:%s", root.node, parsed, unparsed)
suggestions = dict()
token = unparsed.pop().strip()
parts = token.partition('=')
if parts[-1] != '': # parsing for --option=value type input
token = parts[0]
allFlags = root.localFlags + self.globalFlags
for flag in allFlags:
if flag.name == token:
logger.debug("matched token: %s with flag: %s", token, flag.name)
parsed.append(token)
if self.peekForOption(unparsed): # recursively look for further options
parsed, unparsed, suggestions = self.evalOptions(root, parsed, unparsed[:])
# elif token == "--namespace":
# namespaces = [('default', None), ('minikube', None), ('gitlab', None)] # self.kube_client.get_resource("namespace")
# suggestions = dict(namespaces)
break
else:
logger.debug("no flags match, returning allFlags suggestions")
for flag in allFlags:
suggestions[flag.name] = flag.helptext
if suggestions: # incomplete parse, replace token
logger.debug("incomplete option: %s provided. returning suggestions", token)
unparsed.append(token)
return parsed, unparsed, suggestions | [
"def",
"evalOptions",
"(",
"self",
",",
"root",
",",
"parsed",
",",
"unparsed",
")",
":",
"logger",
".",
"debug",
"(",
"\"parsing options at tree: %s with p:%s, u:%s\"",
",",
"root",
".",
"node",
",",
"parsed",
",",
"unparsed",
")",
"suggestions",
"=",
"dict",... | Evaluate only the options and return flags as suggestions | [
"Evaluate",
"only",
"the",
"options",
"and",
"return",
"flags",
"as",
"suggestions"
] | adc801d165e87fe62f82b074ec49996954c3fbe8 | https://github.com/cloudnativelabs/kube-shell/blob/adc801d165e87fe62f82b074ec49996954c3fbe8/kubeshell/parser.py#L136-L165 | train | 222,291 |
olofk/fusesoc | fusesoc/utils.py | setup_logging | def setup_logging(level, monchrome=False, log_file=None):
'''
Utility function for setting up logging.
'''
# Logging to file
if log_file:
logging.basicConfig(filename=log_file, filemode='w',
level=logging.DEBUG)
# Pretty color terminal logging
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter("%(levelname)s: %(message)s", monchrome)
ch.setFormatter(formatter)
# Which packages do we want to log from.
packages = ('__main__', 'fusesoc',)
for package in packages:
logger = logging.getLogger(package)
logger.addHandler(ch)
logger.setLevel(level)
# Warning only packages
warning_only_packages = []
for package in warning_only_packages:
logger = logging.getLogger(package)
logger.addHandler(ch)
logger.setLevel(logging.WARNING)
logger.debug('Setup logging at level {}.'.format(level)) | python | def setup_logging(level, monchrome=False, log_file=None):
'''
Utility function for setting up logging.
'''
# Logging to file
if log_file:
logging.basicConfig(filename=log_file, filemode='w',
level=logging.DEBUG)
# Pretty color terminal logging
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter("%(levelname)s: %(message)s", monchrome)
ch.setFormatter(formatter)
# Which packages do we want to log from.
packages = ('__main__', 'fusesoc',)
for package in packages:
logger = logging.getLogger(package)
logger.addHandler(ch)
logger.setLevel(level)
# Warning only packages
warning_only_packages = []
for package in warning_only_packages:
logger = logging.getLogger(package)
logger.addHandler(ch)
logger.setLevel(logging.WARNING)
logger.debug('Setup logging at level {}.'.format(level)) | [
"def",
"setup_logging",
"(",
"level",
",",
"monchrome",
"=",
"False",
",",
"log_file",
"=",
"None",
")",
":",
"# Logging to file",
"if",
"log_file",
":",
"logging",
".",
"basicConfig",
"(",
"filename",
"=",
"log_file",
",",
"filemode",
"=",
"'w'",
",",
"le... | Utility function for setting up logging. | [
"Utility",
"function",
"for",
"setting",
"up",
"logging",
"."
] | e30c6a30f6e4c2f4a568b3e8f53edce64b4481cd | https://github.com/olofk/fusesoc/blob/e30c6a30f6e4c2f4a568b3e8f53edce64b4481cd/fusesoc/utils.py#L84-L110 | train | 222,292 |
olofk/fusesoc | fusesoc/edalizer.py | Ttptttg.generate | def generate(self, cache_root):
"""Run a parametrized generator
Args:
cache_root (str): The directory where to store the generated cores
Returns:
list: Cores created by the generator
"""
generator_cwd = os.path.join(cache_root, 'generated', self.vlnv.sanitized_name)
generator_input_file = os.path.join(generator_cwd, self.name+'_input.yml')
logger.info('Generating ' + str(self.vlnv))
if not os.path.exists(generator_cwd):
os.makedirs(generator_cwd)
with open(generator_input_file, 'w') as f:
f.write(yaml.dump(self.generator_input))
args = [os.path.join(os.path.abspath(self.generator.root), self.generator.command),
generator_input_file]
if self.generator.interpreter:
args[0:0] = [self.generator.interpreter]
Launcher(args[0], args[1:],
cwd=generator_cwd).run()
cores = []
logger.debug("Looking for generated cores in " + generator_cwd)
for root, dirs, files in os.walk(generator_cwd):
for f in files:
if f.endswith('.core'):
try:
cores.append(Core(os.path.join(root, f)))
except SyntaxError as e:
w = "Failed to parse generated core file " + f + ": " + e.msg
raise RuntimeError(w)
logger.debug("Found " + ', '.join(str(c.name) for c in cores))
return cores | python | def generate(self, cache_root):
"""Run a parametrized generator
Args:
cache_root (str): The directory where to store the generated cores
Returns:
list: Cores created by the generator
"""
generator_cwd = os.path.join(cache_root, 'generated', self.vlnv.sanitized_name)
generator_input_file = os.path.join(generator_cwd, self.name+'_input.yml')
logger.info('Generating ' + str(self.vlnv))
if not os.path.exists(generator_cwd):
os.makedirs(generator_cwd)
with open(generator_input_file, 'w') as f:
f.write(yaml.dump(self.generator_input))
args = [os.path.join(os.path.abspath(self.generator.root), self.generator.command),
generator_input_file]
if self.generator.interpreter:
args[0:0] = [self.generator.interpreter]
Launcher(args[0], args[1:],
cwd=generator_cwd).run()
cores = []
logger.debug("Looking for generated cores in " + generator_cwd)
for root, dirs, files in os.walk(generator_cwd):
for f in files:
if f.endswith('.core'):
try:
cores.append(Core(os.path.join(root, f)))
except SyntaxError as e:
w = "Failed to parse generated core file " + f + ": " + e.msg
raise RuntimeError(w)
logger.debug("Found " + ', '.join(str(c.name) for c in cores))
return cores | [
"def",
"generate",
"(",
"self",
",",
"cache_root",
")",
":",
"generator_cwd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache_root",
",",
"'generated'",
",",
"self",
".",
"vlnv",
".",
"sanitized_name",
")",
"generator_input_file",
"=",
"os",
".",
"path",
... | Run a parametrized generator
Args:
cache_root (str): The directory where to store the generated cores
Returns:
list: Cores created by the generator | [
"Run",
"a",
"parametrized",
"generator"
] | e30c6a30f6e4c2f4a568b3e8f53edce64b4481cd | https://github.com/olofk/fusesoc/blob/e30c6a30f6e4c2f4a568b3e8f53edce64b4481cd/fusesoc/edalizer.py#L165-L203 | train | 222,293 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/fields.py | Field._range_check | def _range_check(self, value, min_value, max_value):
'''
Utility method to check that the given value is between min_value and max_value.
'''
if value < min_value or value > max_value:
raise ValueError('%s out of range - %s is not between %s and %s' % (self.__class__.__name__, value, min_value, max_value)) | python | def _range_check(self, value, min_value, max_value):
'''
Utility method to check that the given value is between min_value and max_value.
'''
if value < min_value or value > max_value:
raise ValueError('%s out of range - %s is not between %s and %s' % (self.__class__.__name__, value, min_value, max_value)) | [
"def",
"_range_check",
"(",
"self",
",",
"value",
",",
"min_value",
",",
"max_value",
")",
":",
"if",
"value",
"<",
"min_value",
"or",
"value",
">",
"max_value",
":",
"raise",
"ValueError",
"(",
"'%s out of range - %s is not between %s and %s'",
"%",
"(",
"self"... | Utility method to check that the given value is between min_value and max_value. | [
"Utility",
"method",
"to",
"check",
"that",
"the",
"given",
"value",
"is",
"between",
"min_value",
"and",
"max_value",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/fields.py#L52-L57 | train | 222,294 |
Infinidat/infi.clickhouse_orm | scripts/generate_ref.py | _get_default_arg | def _get_default_arg(args, defaults, arg_index):
""" Method that determines if an argument has default value or not,
and if yes what is the default value for the argument
:param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
:param defaults: array of default values, eg: (42, 'something')
:param arg_index: index of the argument in the argument array for which,
this function checks if a default value exists or not. And if default value
exists it would return the default value. Example argument: 1
:return: Tuple of whether there is a default or not, and if yes the default
value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)
"""
if not defaults:
return DefaultArgSpec(False, None)
args_with_no_defaults = len(args) - len(defaults)
if arg_index < args_with_no_defaults:
return DefaultArgSpec(False, None)
else:
value = defaults[arg_index - args_with_no_defaults]
if (type(value) is str):
value = '"%s"' % value
return DefaultArgSpec(True, value) | python | def _get_default_arg(args, defaults, arg_index):
""" Method that determines if an argument has default value or not,
and if yes what is the default value for the argument
:param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
:param defaults: array of default values, eg: (42, 'something')
:param arg_index: index of the argument in the argument array for which,
this function checks if a default value exists or not. And if default value
exists it would return the default value. Example argument: 1
:return: Tuple of whether there is a default or not, and if yes the default
value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)
"""
if not defaults:
return DefaultArgSpec(False, None)
args_with_no_defaults = len(args) - len(defaults)
if arg_index < args_with_no_defaults:
return DefaultArgSpec(False, None)
else:
value = defaults[arg_index - args_with_no_defaults]
if (type(value) is str):
value = '"%s"' % value
return DefaultArgSpec(True, value) | [
"def",
"_get_default_arg",
"(",
"args",
",",
"defaults",
",",
"arg_index",
")",
":",
"if",
"not",
"defaults",
":",
"return",
"DefaultArgSpec",
"(",
"False",
",",
"None",
")",
"args_with_no_defaults",
"=",
"len",
"(",
"args",
")",
"-",
"len",
"(",
"defaults... | Method that determines if an argument has default value or not,
and if yes what is the default value for the argument
:param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
:param defaults: array of default values, eg: (42, 'something')
:param arg_index: index of the argument in the argument array for which,
this function checks if a default value exists or not. And if default value
exists it would return the default value. Example argument: 1
:return: Tuple of whether there is a default or not, and if yes the default
value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42) | [
"Method",
"that",
"determines",
"if",
"an",
"argument",
"has",
"default",
"value",
"or",
"not",
"and",
"if",
"yes",
"what",
"is",
"the",
"default",
"value",
"for",
"the",
"argument"
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/scripts/generate_ref.py#L7-L30 | train | 222,295 |
Infinidat/infi.clickhouse_orm | scripts/generate_ref.py | get_method_sig | def get_method_sig(method):
""" Given a function, it returns a string that pretty much looks how the
function signature would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature.
eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
"""
# The return value of ArgSpec is a bit weird, as the list of arguments and
# list of defaults are returned in separate array.
# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
# varargs=None, keywords=None, defaults=(42, 'something'))
argspec = inspect.getargspec(method)
arg_index=0
args = []
# Use the args and defaults array returned by argspec and find out
# which arguments has default
for arg in argspec.args:
default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)
if default_arg.has_default:
val = default_arg.default_value
if isinstance(val, basestring):
val = '"' + val + '"'
args.append("%s=%s" % (arg, val))
else:
args.append(arg)
arg_index += 1
if argspec.varargs:
args.append('*' + argspec.varargs)
if argspec.keywords:
args.append('**' + argspec.keywords)
return "%s(%s)" % (method.__name__, ", ".join(args[1:])) | python | def get_method_sig(method):
""" Given a function, it returns a string that pretty much looks how the
function signature would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature.
eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
"""
# The return value of ArgSpec is a bit weird, as the list of arguments and
# list of defaults are returned in separate array.
# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
# varargs=None, keywords=None, defaults=(42, 'something'))
argspec = inspect.getargspec(method)
arg_index=0
args = []
# Use the args and defaults array returned by argspec and find out
# which arguments has default
for arg in argspec.args:
default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)
if default_arg.has_default:
val = default_arg.default_value
if isinstance(val, basestring):
val = '"' + val + '"'
args.append("%s=%s" % (arg, val))
else:
args.append(arg)
arg_index += 1
if argspec.varargs:
args.append('*' + argspec.varargs)
if argspec.keywords:
args.append('**' + argspec.keywords)
return "%s(%s)" % (method.__name__, ", ".join(args[1:])) | [
"def",
"get_method_sig",
"(",
"method",
")",
":",
"# The return value of ArgSpec is a bit weird, as the list of arguments and",
"# list of defaults are returned in separate array.",
"# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],",
"# varargs=None, keywords=None, defaults=(42, 'somet... | Given a function, it returns a string that pretty much looks how the
function signature would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature.
eg: "my_method(first_argArg, second_arg=42, third_arg='something')" | [
"Given",
"a",
"function",
"it",
"returns",
"a",
"string",
"that",
"pretty",
"much",
"looks",
"how",
"the",
"function",
"signature",
"would",
"be",
"written",
"in",
"python",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/scripts/generate_ref.py#L32-L65 | train | 222,296 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/query.py | AggregateQuerySet.group_by | def group_by(self, *args):
"""
This method lets you specify the grouping fields explicitly. The `args` must
be names of grouping fields or calculated fields that this queryset was
created with.
"""
for name in args:
assert name in self._fields or name in self._calculated_fields, \
'Cannot group by `%s` since it is not included in the query' % name
qs = copy(self)
qs._grouping_fields = args
return qs | python | def group_by(self, *args):
"""
This method lets you specify the grouping fields explicitly. The `args` must
be names of grouping fields or calculated fields that this queryset was
created with.
"""
for name in args:
assert name in self._fields or name in self._calculated_fields, \
'Cannot group by `%s` since it is not included in the query' % name
qs = copy(self)
qs._grouping_fields = args
return qs | [
"def",
"group_by",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"name",
"in",
"args",
":",
"assert",
"name",
"in",
"self",
".",
"_fields",
"or",
"name",
"in",
"self",
".",
"_calculated_fields",
",",
"'Cannot group by `%s` since it is not included in the query... | This method lets you specify the grouping fields explicitly. The `args` must
be names of grouping fields or calculated fields that this queryset was
created with. | [
"This",
"method",
"lets",
"you",
"specify",
"the",
"grouping",
"fields",
"explicitly",
".",
"The",
"args",
"must",
"be",
"names",
"of",
"grouping",
"fields",
"or",
"calculated",
"fields",
"that",
"this",
"queryset",
"was",
"created",
"with",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/query.py#L554-L565 | train | 222,297 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/query.py | AggregateQuerySet.select_fields_as_sql | def select_fields_as_sql(self):
"""
Returns the selected fields or expressions as a SQL string.
"""
return comma_join(list(self._fields) + ['%s AS %s' % (v, k) for k, v in self._calculated_fields.items()]) | python | def select_fields_as_sql(self):
"""
Returns the selected fields or expressions as a SQL string.
"""
return comma_join(list(self._fields) + ['%s AS %s' % (v, k) for k, v in self._calculated_fields.items()]) | [
"def",
"select_fields_as_sql",
"(",
"self",
")",
":",
"return",
"comma_join",
"(",
"list",
"(",
"self",
".",
"_fields",
")",
"+",
"[",
"'%s AS %s'",
"%",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_calculated_fields",
".",
"it... | Returns the selected fields or expressions as a SQL string. | [
"Returns",
"the",
"selected",
"fields",
"or",
"expressions",
"as",
"a",
"SQL",
"string",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/query.py#L579-L583 | train | 222,298 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/query.py | AggregateQuerySet.count | def count(self):
"""
Returns the number of rows after aggregation.
"""
sql = u'SELECT count() FROM (%s)' % self.as_sql()
raw = self._database.raw(sql)
return int(raw) if raw else 0 | python | def count(self):
"""
Returns the number of rows after aggregation.
"""
sql = u'SELECT count() FROM (%s)' % self.as_sql()
raw = self._database.raw(sql)
return int(raw) if raw else 0 | [
"def",
"count",
"(",
"self",
")",
":",
"sql",
"=",
"u'SELECT count() FROM (%s)'",
"%",
"self",
".",
"as_sql",
"(",
")",
"raw",
"=",
"self",
".",
"_database",
".",
"raw",
"(",
"sql",
")",
"return",
"int",
"(",
"raw",
")",
"if",
"raw",
"else",
"0"
] | Returns the number of rows after aggregation. | [
"Returns",
"the",
"number",
"of",
"rows",
"after",
"aggregation",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/query.py#L588-L594 | train | 222,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.