id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,100 | nabla-c0d3/sslyze | sslyze/plugins/utils/trust_store/trust_store_repository.py | TrustStoresRepository.update_default | def update_default(cls) -> 'TrustStoresRepository':
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | python | def update_default(cls) -> 'TrustStoresRepository':
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | [
"def",
"update_default",
"(",
"cls",
")",
"->",
"'TrustStoresRepository'",
":",
"temp_path",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"# Download the latest trust stores",
"archive_path",
"=",
"join",
"(",
"temp_path",
",",
"'trust_stores_as_pem.tar.gz'",
")",
"urlretrie... | Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory. | [
"Update",
"the",
"default",
"trust",
"stores",
"used",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store_repository.py#L123-L146 |
241,101 | nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | OpenSslCipherSuitesPlugin._get_preferred_cipher_suite | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
"""Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze.
"""
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | python | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | [
"def",
"_get_preferred_cipher_suite",
"(",
"cls",
",",
"server_connectivity_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version",
":",
"OpenSslVersionEnum",
",",
"accepted_cipher_list",
":",
"List",
"[",
"'AcceptedCipherSuite'",
"]",
")",
"->",
"Optional",
"[",
"'Ac... | Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze. | [
"Try",
"to",
"detect",
"the",
"server",
"s",
"preferred",
"cipher",
"suite",
"among",
"all",
"cipher",
"suites",
"supported",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L283-L330 |
241,102 | nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | CipherSuite.name | def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | python | def name(self) -> str:
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"OPENSSL_TO_RFC_NAMES_MAPPING",
"[",
"self",
".",
"ssl_version",
"]",
".",
"get",
"(",
"self",
".",
"openssl_name",
",",
"self",
".",
"openssl_name",
")"
] | OpenSSL uses a different naming convention than the corresponding RFCs. | [
"OpenSSL",
"uses",
"a",
"different",
"naming",
"convention",
"than",
"the",
"corresponding",
"RFCs",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L366-L369 |
241,103 | nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.queue_scan_command | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
"""Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
"""
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | python | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | [
"def",
"queue_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"None",
":",
"# Ensure we have the right processes and queues in place for this hostname",
"self",
".",
"_check_and_create_proc... | Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server. | [
"Queue",
"a",
"scan",
"command",
"targeting",
"a",
"specific",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L83-L102 |
241,104 | nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.get_results | def get_results(self) -> Iterable[PluginScanResult]:
"""Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead.
"""
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | python | def get_results(self) -> Iterable[PluginScanResult]:
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | [
"def",
"get_results",
"(",
"self",
")",
"->",
"Iterable",
"[",
"PluginScanResult",
"]",
":",
"# Put a 'None' sentinel in the queue to let the each process know when every task has been completed",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_get_current_processes_nb",
"(",
... | Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead. | [
"Return",
"the",
"result",
"of",
"previously",
"queued",
"scan",
"commands",
";",
"new",
"commands",
"cannot",
"be",
"queued",
"once",
"this",
"is",
"called",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L135-L172 |
241,105 | nabla-c0d3/sslyze | sslyze/utils/worker_process.py | WorkerProcess.run | def run(self) -> None:
"""The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates.
"""
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | python | def run(self) -> None:
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"from",
"sslyze",
".",
"concurrent_scanner",
"import",
"PluginRaisedExceptionScanResult",
"# Start processing task in the priority queue first",
"current_queue_in",
"=",
"self",
".",
"priority_queue_in",
"while",
"True",
... | The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates. | [
"The",
"process",
"will",
"first",
"complete",
"tasks",
"it",
"gets",
"from",
"self",
".",
"queue_in",
".",
"Once",
"it",
"gets",
"notified",
"that",
"all",
"the",
"tasks",
"have",
"been",
"completed",
"it",
"terminates",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/worker_process.py#L26-L58 |
241,106 | nabla-c0d3/sslyze | sslyze/utils/connection_helpers.py | ProxyTunnelingConnectionHelper.connect_socket | def connect_socket(self, sock: socket.socket) -> None:
"""Setup HTTP tunneling with the configured proxy.
"""
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | python | def connect_socket(self, sock: socket.socket) -> None:
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | [
"def",
"connect_socket",
"(",
"self",
",",
"sock",
":",
"socket",
".",
"socket",
")",
"->",
"None",
":",
"# Setup HTTP tunneling",
"try",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"_tunnel_host",
",",
"self",
".",
"_tunnel_port",
")",
")",
"exc... | Setup HTTP tunneling with the configured proxy. | [
"Setup",
"HTTP",
"tunneling",
"with",
"the",
"configured",
"proxy",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/connection_helpers.py#L63-L85 |
241,107 | nabla-c0d3/sslyze | sslyze/server_connectivity_info.py | ServerConnectivityInfo.get_preconfigured_ssl_connection | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
"""Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans.
"""
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | python | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | [
"def",
"get_preconfigured_ssl_connection",
"(",
"self",
",",
"override_ssl_version",
":",
"Optional",
"[",
"OpenSslVersionEnum",
"]",
"=",
"None",
",",
"ssl_verify_locations",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"should_use_legacy_openssl",
":",
"Opt... | Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans. | [
"Get",
"an",
"SSLConnection",
"instance",
"with",
"the",
"right",
"SSL",
"configuration",
"for",
"successfully",
"connecting",
"to",
"the",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/server_connectivity_info.py#L70-L114 |
241,108 | nabla-c0d3/sslyze | sslyze/cli/command_line_parser.py | CommandLineParser._add_plugin_options | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
"""Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser.
"""
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | python | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | [
"def",
"_add_plugin_options",
"(",
"self",
",",
"available_plugins",
":",
"Set",
"[",
"Type",
"[",
"Plugin",
"]",
"]",
")",
"->",
"None",
":",
"for",
"plugin_class",
"in",
"available_plugins",
":",
"# Add the current plugin's commands to the parser",
"group",
"=",
... | Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser. | [
"Recovers",
"the",
"list",
"of",
"command",
"line",
"options",
"implemented",
"by",
"the",
"available",
"plugins",
"and",
"adds",
"them",
"to",
"the",
"command",
"line",
"parser",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/command_line_parser.py#L428-L437 |
241,109 | nabla-c0d3/sslyze | setup.py | get_long_description | def get_long_description():
"""Convert the README file into the long description.
"""
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | python | def get_long_description():
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | [
"def",
"get_long_description",
"(",
")",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"root_path",
",",
"'README.md'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"long_description",
"=",
"f",
".",
"read",
"(",
")",
"return",
"lon... | Convert the README file into the long description. | [
"Convert",
"the",
"README",
"file",
"into",
"the",
"long",
"description",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L23-L28 |
241,110 | nabla-c0d3/sslyze | setup.py | get_include_files | def get_include_files():
""""Get the list of trust stores so they properly packaged when doing a cx_freeze build.
"""
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | python | def get_include_files():
"plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | [
"def",
"get_include_files",
"(",
")",
":",
"plugin_data_files",
"=",
"[",
"]",
"trust_stores_pem_path",
"=",
"path",
".",
"join",
"(",
"root_path",
",",
"'sslyze'",
",",
"'plugins'",
",",
"'utils'",
",",
"'trust_store'",
",",
"'pem_files'",
")",
"for",
"file",... | Get the list of trust stores so they properly packaged when doing a cx_freeze build. | [
"Get",
"the",
"list",
"of",
"trust",
"stores",
"so",
"they",
"properly",
"packaged",
"when",
"doing",
"a",
"cx_freeze",
"build",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L31-L41 |
241,111 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_dns_subject_alternative_names | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | python | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | [
"def",
"get_dns_subject_alternative_names",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"List",
"[",
"str",
"]",
":",
"subj_alt_names",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"try",
":",
"san_ext",
"=",
"certi... | Retrieve all the DNS entries of the Subject Alternative Name extension. | [
"Retrieve",
"all",
"the",
"DNS",
"entries",
"of",
"the",
"Subject",
"Alternative",
"Name",
"extension",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L24-L33 |
241,112 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.matches_hostname | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
"""Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | python | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | [
"def",
"matches_hostname",
"(",
"cls",
",",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
",",
"hostname",
":",
"str",
")",
"->",
"None",
":",
"# Extract the names from the certificate to create the properly-formatted dictionary",
"certificate_names",... | Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname. | [
"Verify",
"that",
"the",
"certificate",
"was",
"issued",
"for",
"the",
"given",
"hostname",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L36-L48 |
241,113 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_name_as_short_text | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
"""Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
"""
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | python | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | [
"def",
"get_name_as_short_text",
"(",
"cls",
",",
"name_field",
":",
"cryptography",
".",
"x509",
".",
"Name",
")",
"->",
"str",
":",
"# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one",
"common_names",
"=",
"cls",
".",
"get_common_names",
... | Convert a name field returned by the cryptography module to a string suitable for displaying it to the user. | [
"Convert",
"a",
"name",
"field",
"returned",
"by",
"the",
"cryptography",
"module",
"to",
"a",
"string",
"suitable",
"for",
"displaying",
"it",
"to",
"the",
"user",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L51-L61 |
241,114 | nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.has_ocsp_must_staple_extension | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
"""Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
"""
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | python | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | [
"def",
"has_ocsp_must_staple_extension",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"bool",
":",
"has_ocsp_must_staple",
"=",
"False",
"try",
":",
"tls_feature_ext",
"=",
"certificate",
".",
"extensions",
".",
"get_extension... | Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066. | [
"Return",
"True",
"if",
"the",
"certificate",
"has",
"the",
"OCSP",
"Must",
"-",
"Staple",
"extension",
"defined",
"in",
"RFC",
"6066",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L95-L108 |
241,115 | nabla-c0d3/sslyze | sslyze/utils/tls_wrapped_protocol_helpers.py | HttpsHelper.send_request | def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | python | def send_request(self, ssl_client: SslClient) -> str:
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | [
"def",
"send_request",
"(",
"self",
",",
"ssl_client",
":",
"SslClient",
")",
"->",
"str",
":",
"try",
":",
"ssl_client",
".",
"write",
"(",
"HttpRequestGenerator",
".",
"get_request",
"(",
"self",
".",
"_hostname",
")",
")",
"# Parse the response and print the ... | Send an HTTP GET to the server and return the HTTP status code. | [
"Send",
"an",
"HTTP",
"GET",
"to",
"the",
"server",
"and",
"return",
"the",
"HTTP",
"status",
"code",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/tls_wrapped_protocol_helpers.py#L65-L90 |
241,116 | nabla-c0d3/sslyze | sslyze/plugins/plugins_repository.py | PluginsRepository.get_plugin_class_for_command | def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]:
"""Get the class of the plugin implementing the supplied scan command.
"""
return self._scan_command_classes_to_plugin_classes[scan_command.__class__] | python | def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]:
return self._scan_command_classes_to_plugin_classes[scan_command.__class__] | [
"def",
"get_plugin_class_for_command",
"(",
"self",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"Type",
"[",
"Plugin",
"]",
":",
"return",
"self",
".",
"_scan_command_classes_to_plugin_classes",
"[",
"scan_command",
".",
"__class__",
"]"
] | Get the class of the plugin implementing the supplied scan command. | [
"Get",
"the",
"class",
"of",
"the",
"plugin",
"implementing",
"the",
"supplied",
"scan",
"command",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugins_repository.py#L44-L47 |
241,117 | nabla-c0d3/sslyze | sslyze/utils/http_response_parser.py | HttpResponseParser._parse | def _parse(read_method: Callable) -> HTTPResponse:
"""Trick to standardize the API between sockets and SSLConnection objects.
"""
response = read_method(4096)
while b'HTTP/' not in response or b'\r\n\r\n' not in response:
# Parse until the end of the headers
response += read_method(4096)
fake_sock = _FakeSocket(response)
response = HTTPResponse(fake_sock) # type: ignore
response.begin()
return response | python | def _parse(read_method: Callable) -> HTTPResponse:
response = read_method(4096)
while b'HTTP/' not in response or b'\r\n\r\n' not in response:
# Parse until the end of the headers
response += read_method(4096)
fake_sock = _FakeSocket(response)
response = HTTPResponse(fake_sock) # type: ignore
response.begin()
return response | [
"def",
"_parse",
"(",
"read_method",
":",
"Callable",
")",
"->",
"HTTPResponse",
":",
"response",
"=",
"read_method",
"(",
"4096",
")",
"while",
"b'HTTP/'",
"not",
"in",
"response",
"or",
"b'\\r\\n\\r\\n'",
"not",
"in",
"response",
":",
"# Parse until the end of... | Trick to standardize the API between sockets and SSLConnection objects. | [
"Trick",
"to",
"standardize",
"the",
"API",
"between",
"sockets",
"and",
"SSLConnection",
"objects",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/http_response_parser.py#L26-L37 |
241,118 | nabla-c0d3/sslyze | sslyze/utils/thread_pool.py | _work_function | def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None:
"""Work function expected to run within threads.
"""
while True:
job = job_q.get()
if isinstance(job, _ThreadPoolSentinel):
# All the work is done, get out
result_q.put(_ThreadPoolSentinel())
error_q.put(_ThreadPoolSentinel())
job_q.task_done()
break
work_function = job[0]
args = job[1]
try:
result = work_function(*args)
except Exception as e:
error_q.put((job, e))
else:
result_q.put((job, result))
finally:
job_q.task_done() | python | def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None:
while True:
job = job_q.get()
if isinstance(job, _ThreadPoolSentinel):
# All the work is done, get out
result_q.put(_ThreadPoolSentinel())
error_q.put(_ThreadPoolSentinel())
job_q.task_done()
break
work_function = job[0]
args = job[1]
try:
result = work_function(*args)
except Exception as e:
error_q.put((job, e))
else:
result_q.put((job, result))
finally:
job_q.task_done() | [
"def",
"_work_function",
"(",
"job_q",
":",
"Queue",
",",
"result_q",
":",
"Queue",
",",
"error_q",
":",
"Queue",
")",
"->",
"None",
":",
"while",
"True",
":",
"job",
"=",
"job_q",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"job",
",",
"_ThreadPo... | Work function expected to run within threads. | [
"Work",
"function",
"expected",
"to",
"run",
"within",
"threads",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/thread_pool.py#L93-L115 |
241,119 | nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_with_session_id | def _resume_with_session_id(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum
) -> bool:
"""Perform one session resumption using Session IDs.
"""
session1 = self._resume_ssl_session(server_info, ssl_version_to_use)
try:
# Recover the session ID
session1_id = self._extract_session_id(session1)
except IndexError:
# Session ID not assigned
return False
if session1_id == '':
# Session ID empty
return False
# Try to resume that SSL session
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1)
try:
# Recover the session ID
session2_id = self._extract_session_id(session2)
except IndexError:
# Session ID not assigned
return False
# Finally, compare the two Session IDs
if session1_id != session2_id:
# Session ID assigned but not accepted
return False
return True | python | def _resume_with_session_id(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum
) -> bool:
session1 = self._resume_ssl_session(server_info, ssl_version_to_use)
try:
# Recover the session ID
session1_id = self._extract_session_id(session1)
except IndexError:
# Session ID not assigned
return False
if session1_id == '':
# Session ID empty
return False
# Try to resume that SSL session
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1)
try:
# Recover the session ID
session2_id = self._extract_session_id(session2)
except IndexError:
# Session ID not assigned
return False
# Finally, compare the two Session IDs
if session1_id != session2_id:
# Session ID assigned but not accepted
return False
return True | [
"def",
"_resume_with_session_id",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
")",
"->",
"bool",
":",
"session1",
"=",
"self",
".",
"_resume_ssl_session",
"(",
"server_info",
",",
"ssl_version_t... | Perform one session resumption using Session IDs. | [
"Perform",
"one",
"session",
"resumption",
"using",
"Session",
"IDs",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L151-L184 |
241,120 | nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_with_session_ticket | def _resume_with_session_ticket(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
) -> TslSessionTicketSupportEnum:
"""Perform one session resumption using TLS Session Tickets.
"""
# Connect to the server and keep the SSL session
try:
session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True)
except SslHandshakeRejected:
if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3:
return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED
else:
raise
try:
# Recover the TLS ticket
session1_tls_ticket = self._extract_tls_session_ticket(session1)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Try to resume that session using the TLS ticket
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True)
try:
# Recover the TLS ticket
session2_tls_ticket = self._extract_tls_session_ticket(session2)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Finally, compare the two TLS Tickets
if session1_tls_ticket != session2_tls_ticket:
return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED
return TslSessionTicketSupportEnum.SUCCEEDED | python | def _resume_with_session_ticket(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
) -> TslSessionTicketSupportEnum:
# Connect to the server and keep the SSL session
try:
session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True)
except SslHandshakeRejected:
if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3:
return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED
else:
raise
try:
# Recover the TLS ticket
session1_tls_ticket = self._extract_tls_session_ticket(session1)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Try to resume that session using the TLS ticket
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True)
try:
# Recover the TLS ticket
session2_tls_ticket = self._extract_tls_session_ticket(session2)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Finally, compare the two TLS Tickets
if session1_tls_ticket != session2_tls_ticket:
return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED
return TslSessionTicketSupportEnum.SUCCEEDED | [
"def",
"_resume_with_session_ticket",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
",",
")",
"->",
"TslSessionTicketSupportEnum",
":",
"# Connect to the server and keep the SSL session",
"try",
":",
"ses... | Perform one session resumption using TLS Session Tickets. | [
"Perform",
"one",
"session",
"resumption",
"using",
"TLS",
"Session",
"Tickets",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L186-L220 |
241,121 | nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._extract_session_id | def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set.
"""
session_string = ((ssl_session.as_text()).split('Session-ID:'))[1]
session_id = (session_string.split('Session-ID-ctx:'))[0].strip()
return session_id | python | def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str:
session_string = ((ssl_session.as_text()).split('Session-ID:'))[1]
session_id = (session_string.split('Session-ID-ctx:'))[0].strip()
return session_id | [
"def",
"_extract_session_id",
"(",
"ssl_session",
":",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
")",
"->",
"str",
":",
"session_string",
"=",
"(",
"(",
"ssl_session",
".",
"as_text",
"(",
")",
")",
".",
"split",
"(",
"'Session-ID:'",
")",
")",
"[",
"1... | Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set. | [
"Extract",
"the",
"SSL",
"session",
"ID",
"from",
"a",
"SSL",
"session",
"object",
"or",
"raises",
"IndexError",
"if",
"the",
"session",
"ID",
"was",
"not",
"set",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L223-L228 |
241,122 | nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._extract_tls_session_ticket | def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set.
"""
session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
session_tls_ticket = (session_string.split('Compression:'))[0]
return session_tls_ticket | python | def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
session_tls_ticket = (session_string.split('Compression:'))[0]
return session_tls_ticket | [
"def",
"_extract_tls_session_ticket",
"(",
"ssl_session",
":",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
")",
"->",
"str",
":",
"session_string",
"=",
"(",
"(",
"ssl_session",
".",
"as_text",
"(",
")",
")",
".",
"split",
"(",
"'TLS session ticket:'",
")",
... | Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set. | [
"Extract",
"the",
"TLS",
"session",
"ticket",
"from",
"a",
"SSL",
"session",
"object",
"or",
"raises",
"IndexError",
"if",
"the",
"ticket",
"was",
"not",
"set",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L231-L236 |
241,123 | nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_ssl_session | def _resume_ssl_session(
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
ssl_session: Optional[nassl._nassl.SSL_SESSION] = None,
should_enable_tls_ticket: bool = False
) -> nassl._nassl.SSL_SESSION:
"""Connect to the server and returns the session object that was assigned for that connection.
If ssl_session is given, tries to resume that session.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use)
if not should_enable_tls_ticket:
# Need to disable TLS tickets to test session IDs, according to rfc5077:
# If a ticket is presented by the client, the server MUST NOT attempt
# to use the Session ID in the ClientHello for stateful session resumption
ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets.
if ssl_session:
ssl_connection.ssl_client.set_session(ssl_session)
try:
# Perform the SSL handshake
ssl_connection.connect()
new_session = ssl_connection.ssl_client.get_session() # Get session data
finally:
ssl_connection.close()
return new_session | python | def _resume_ssl_session(
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
ssl_session: Optional[nassl._nassl.SSL_SESSION] = None,
should_enable_tls_ticket: bool = False
) -> nassl._nassl.SSL_SESSION:
ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use)
if not should_enable_tls_ticket:
# Need to disable TLS tickets to test session IDs, according to rfc5077:
# If a ticket is presented by the client, the server MUST NOT attempt
# to use the Session ID in the ClientHello for stateful session resumption
ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets.
if ssl_session:
ssl_connection.ssl_client.set_session(ssl_session)
try:
# Perform the SSL handshake
ssl_connection.connect()
new_session = ssl_connection.ssl_client.get_session() # Get session data
finally:
ssl_connection.close()
return new_session | [
"def",
"_resume_ssl_session",
"(",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
",",
"ssl_session",
":",
"Optional",
"[",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
"]",
"=",
"None",
",",
"should_enable_tls_ticke... | Connect to the server and returns the session object that was assigned for that connection.
If ssl_session is given, tries to resume that session. | [
"Connect",
"to",
"the",
"server",
"and",
"returns",
"the",
"session",
"object",
"that",
"was",
"assigned",
"for",
"that",
"connection",
".",
"If",
"ssl_session",
"is",
"given",
"tries",
"to",
"resume",
"that",
"session",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L239-L265 |
241,124 | nabla-c0d3/sslyze | sslyze/cli/json_output.py | _object_to_json_dict | def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
"""Convert an object to a dictionary suitable for the JSON output.
"""
if isinstance(obj, Enum):
# Properly serialize Enums (such as OpenSslVersionEnum)
result = obj.name
elif isinstance(obj, ObjectIdentifier):
# Use dotted string representation for OIDs
result = obj.dotted_string
elif isinstance(obj, x509._Certificate):
# Properly serialize certificates
certificate = obj
result = { # type: ignore
# Add general info
'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),
# Add some of the fields of the cert
'subject': CertificateUtils.get_name_as_text(certificate.subject),
'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
'serialNumber': str(certificate.serial_number),
'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
'signatureAlgorithm': certificate.signature_hash_algorithm.name,
'publicKey': {
'algorithm': CertificateUtils.get_public_key_type(certificate)
},
}
dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
if dns_alt_names:
result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore
# Add some info about the public key
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore
result['publicKey']['curve'] = public_key.curve.name # type: ignore
else:
result['publicKey']['size'] = str(public_key.key_size)
result['publicKey']['exponent'] = str(public_key.public_numbers().e)
elif isinstance(obj, object):
# Some objects (like str) don't have a __dict__
if hasattr(obj, '__dict__'):
result = {}
for key, value in obj.__dict__.items():
# Remove private attributes
if key.startswith('_'):
continue
result[key] = _object_to_json_dict(value)
else:
# Simple object like a bool
result = obj
else:
raise TypeError('Unknown type: {}'.format(repr(obj)))
return result | python | def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
if isinstance(obj, Enum):
# Properly serialize Enums (such as OpenSslVersionEnum)
result = obj.name
elif isinstance(obj, ObjectIdentifier):
# Use dotted string representation for OIDs
result = obj.dotted_string
elif isinstance(obj, x509._Certificate):
# Properly serialize certificates
certificate = obj
result = { # type: ignore
# Add general info
'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),
# Add some of the fields of the cert
'subject': CertificateUtils.get_name_as_text(certificate.subject),
'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
'serialNumber': str(certificate.serial_number),
'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
'signatureAlgorithm': certificate.signature_hash_algorithm.name,
'publicKey': {
'algorithm': CertificateUtils.get_public_key_type(certificate)
},
}
dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
if dns_alt_names:
result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore
# Add some info about the public key
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore
result['publicKey']['curve'] = public_key.curve.name # type: ignore
else:
result['publicKey']['size'] = str(public_key.key_size)
result['publicKey']['exponent'] = str(public_key.public_numbers().e)
elif isinstance(obj, object):
# Some objects (like str) don't have a __dict__
if hasattr(obj, '__dict__'):
result = {}
for key, value in obj.__dict__.items():
# Remove private attributes
if key.startswith('_'):
continue
result[key] = _object_to_json_dict(value)
else:
# Simple object like a bool
result = obj
else:
raise TypeError('Unknown type: {}'.format(repr(obj)))
return result | [
"def",
"_object_to_json_dict",
"(",
"obj",
":",
"Any",
")",
"->",
"Union",
"[",
"bool",
",",
"int",
",",
"float",
",",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Enum",
")",
":",
"# Properly ser... | Convert an object to a dictionary suitable for the JSON output. | [
"Convert",
"an",
"object",
"to",
"a",
"dictionary",
"suitable",
"for",
"the",
"JSON",
"output",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/json_output.py#L84-L145 |
241,125 | nabla-c0d3/sslyze | sslyze/plugins/certificate_info_plugin.py | CertificateInfoPlugin._get_and_verify_certificate_chain | def _get_and_verify_certificate_chain(
server_info: ServerConnectivityInfo,
trust_store: TrustStore
) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
"""Connects to the target server and uses the supplied trust store to validate the server's certificate.
Returns the server's certificate and OCSP response.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)
# Enable OCSP stapling
ssl_connection.ssl_client.set_tlsext_status_ocsp()
try: # Perform the SSL handshake
ssl_connection.connect()
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
except ClientCertificateRequested: # The server asked for a client cert
# We can get the server cert anyway
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
finally:
ssl_connection.close()
# Parse the certificates using the cryptography module
parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
for x509_cert in x509_cert_chain]
return parsed_x509_chain, verify_str, ocsp_response | python | def _get_and_verify_certificate_chain(
server_info: ServerConnectivityInfo,
trust_store: TrustStore
) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)
# Enable OCSP stapling
ssl_connection.ssl_client.set_tlsext_status_ocsp()
try: # Perform the SSL handshake
ssl_connection.connect()
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
except ClientCertificateRequested: # The server asked for a client cert
# We can get the server cert anyway
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
finally:
ssl_connection.close()
# Parse the certificates using the cryptography module
parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
for x509_cert in x509_cert_chain]
return parsed_x509_chain, verify_str, ocsp_response | [
"def",
"_get_and_verify_certificate_chain",
"(",
"server_info",
":",
"ServerConnectivityInfo",
",",
"trust_store",
":",
"TrustStore",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Certificate",
"]",
",",
"str",
",",
"Optional",
"[",
"OcspResponse",
"]",
"]",
":",
"ssl_... | Connects to the target server and uses the supplied trust store to validate the server's certificate.
Returns the server's certificate and OCSP response. | [
"Connects",
"to",
"the",
"target",
"server",
"and",
"uses",
"the",
"supplied",
"trust",
"store",
"to",
"validate",
"the",
"server",
"s",
"certificate",
".",
"Returns",
"the",
"server",
"s",
"certificate",
"and",
"OCSP",
"response",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/certificate_info_plugin.py#L171-L202 |
241,126 | nabla-c0d3/sslyze | sslyze/plugins/plugin_base.py | PluginScanCommand.get_description | def get_description(cls) -> str:
"""The description is expected to be the command class' docstring.
"""
if cls.__doc__ is None:
raise ValueError('No docstring found for {}'.format(cls.__name__))
return cls.__doc__.strip() | python | def get_description(cls) -> str:
if cls.__doc__ is None:
raise ValueError('No docstring found for {}'.format(cls.__name__))
return cls.__doc__.strip() | [
"def",
"get_description",
"(",
"cls",
")",
"->",
"str",
":",
"if",
"cls",
".",
"__doc__",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No docstring found for {}'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")",
"return",
"cls",
".",
"__doc__",
... | The description is expected to be the command class' docstring. | [
"The",
"description",
"is",
"expected",
"to",
"be",
"the",
"command",
"class",
"docstring",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugin_base.py#L30-L35 |
241,127 | kennethreitz/inbox.py | inbox.py | Inbox.serve | def serve(self, port=None, address=None):
"""Serves the SMTP server on the given port and address."""
port = port or self.port
address = address or self.address
log.info('Starting SMTP server at {0}:{1}'.format(address, port))
server = InboxServer(self.collator, (address, port), None)
try:
asyncore.loop()
except KeyboardInterrupt:
log.info('Cleaning up') | python | def serve(self, port=None, address=None):
port = port or self.port
address = address or self.address
log.info('Starting SMTP server at {0}:{1}'.format(address, port))
server = InboxServer(self.collator, (address, port), None)
try:
asyncore.loop()
except KeyboardInterrupt:
log.info('Cleaning up') | [
"def",
"serve",
"(",
"self",
",",
"port",
"=",
"None",
",",
"address",
"=",
"None",
")",
":",
"port",
"=",
"port",
"or",
"self",
".",
"port",
"address",
"=",
"address",
"or",
"self",
".",
"address",
"log",
".",
"info",
"(",
"'Starting SMTP server at {0... | Serves the SMTP server on the given port and address. | [
"Serves",
"the",
"SMTP",
"server",
"on",
"the",
"given",
"port",
"and",
"address",
"."
] | 493f8d9834a41ac9012f13da5693697efdcb1826 | https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L41-L53 |
241,128 | kennethreitz/inbox.py | inbox.py | Inbox.dispatch | def dispatch(self):
"""Command-line dispatch."""
parser = argparse.ArgumentParser(description='Run an Inbox server.')
parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to')
parser.add_argument('port', metavar='port', type=int, help='port to bind to')
args = parser.parse_args()
self.serve(port=args.port, address=args.addr) | python | def dispatch(self):
parser = argparse.ArgumentParser(description='Run an Inbox server.')
parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to')
parser.add_argument('port', metavar='port', type=int, help='port to bind to')
args = parser.parse_args()
self.serve(port=args.port, address=args.addr) | [
"def",
"dispatch",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run an Inbox server.'",
")",
"parser",
".",
"add_argument",
"(",
"'addr'",
",",
"metavar",
"=",
"'addr'",
",",
"type",
"=",
"str",
",",
"... | Command-line dispatch. | [
"Command",
"-",
"line",
"dispatch",
"."
] | 493f8d9834a41ac9012f13da5693697efdcb1826 | https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L55-L64 |
241,129 | securestate/termineter | lib/c1219/data.py | format_ltime | def format_ltime(endianess, tm_format, data):
"""
Return data formatted into a human readable time stamp.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bytes data: The packed and machine-formatted data to parse
:rtype: str
"""
if tm_format == 0:
return ''
elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type
y = data[0]
year = '????'
if 90 <= y <= 99:
year = '19' + str(y)
elif 0 <= y <= 9:
year = '200' + str(y)
elif 10 <= y <= 89:
year = '20' + str(y)
month = data[1]
day = data[2]
hour = data[3]
minute = data[4]
second = data[5]
elif tm_format == 3 or tm_format == 4:
if tm_format == 3:
u_time = float(struct.unpack(endianess + 'I', data[0:4])[0])
second = float(data[4])
final_time = time.gmtime((u_time * 60) + second)
elif tm_format == 4:
final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0]))
year = str(final_time.tm_year)
month = str(final_time.tm_mon)
day = str(final_time.tm_mday)
hour = str(final_time.tm_hour)
minute = str(final_time.tm_min)
second = str(final_time.tm_sec)
return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second) | python | def format_ltime(endianess, tm_format, data):
if tm_format == 0:
return ''
elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type
y = data[0]
year = '????'
if 90 <= y <= 99:
year = '19' + str(y)
elif 0 <= y <= 9:
year = '200' + str(y)
elif 10 <= y <= 89:
year = '20' + str(y)
month = data[1]
day = data[2]
hour = data[3]
minute = data[4]
second = data[5]
elif tm_format == 3 or tm_format == 4:
if tm_format == 3:
u_time = float(struct.unpack(endianess + 'I', data[0:4])[0])
second = float(data[4])
final_time = time.gmtime((u_time * 60) + second)
elif tm_format == 4:
final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0]))
year = str(final_time.tm_year)
month = str(final_time.tm_mon)
day = str(final_time.tm_mday)
hour = str(final_time.tm_hour)
minute = str(final_time.tm_min)
second = str(final_time.tm_sec)
return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second) | [
"def",
"format_ltime",
"(",
"endianess",
",",
"tm_format",
",",
"data",
")",
":",
"if",
"tm_format",
"==",
"0",
":",
"return",
"''",
"elif",
"tm_format",
"==",
"1",
"or",
"tm_format",
"==",
"2",
":",
"# I can't find solid documentation on the BCD data-type",
"y"... | Return data formatted into a human readable time stamp.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bytes data: The packed and machine-formatted data to parse
:rtype: str | [
"Return",
"data",
"formatted",
"into",
"a",
"human",
"readable",
"time",
"stamp",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L40-L80 |
241,130 | securestate/termineter | lib/c1219/data.py | get_history_entry_record | def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
"""
Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bool event_number_flag: Whether or not an event number is included.
:param bool hist_seq_nbr_flag: Whether or not an history sequence number
is included.
:param str data: The packed and machine-formatted data to parse
:rtype: dict
"""
rcd = {}
if hist_date_time_flag:
tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)])
if tmstmp:
rcd['Time'] = tmstmp
data = data[LTIME_LENGTH.get(tm_format):]
if event_number_flag:
rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
if hist_seq_nbr_flag:
rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0]
rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2]
rcd['Arguments'] = data[4:]
return rcd | python | def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
rcd = {}
if hist_date_time_flag:
tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)])
if tmstmp:
rcd['Time'] = tmstmp
data = data[LTIME_LENGTH.get(tm_format):]
if event_number_flag:
rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
if hist_seq_nbr_flag:
rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0]
rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2]
rcd['Arguments'] = data[4:]
return rcd | [
"def",
"get_history_entry_record",
"(",
"endianess",
",",
"hist_date_time_flag",
",",
"tm_format",
",",
"event_number_flag",
",",
"hist_seq_nbr_flag",
",",
"data",
")",
":",
"rcd",
"=",
"{",
"}",
"if",
"hist_date_time_flag",
":",
"tmstmp",
"=",
"format_ltime",
"("... | Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bool event_number_flag: Whether or not an event number is included.
:param bool hist_seq_nbr_flag: Whether or not an history sequence number
is included.
:param str data: The packed and machine-formatted data to parse
:rtype: dict | [
"Return",
"data",
"formatted",
"into",
"a",
"log",
"entry",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L82-L111 |
241,131 | securestate/termineter | lib/c1219/data.py | get_table_idbb_field | def get_table_idbb_field(endianess, data):
"""
Return data from a packed TABLE_IDB_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 0x7ff
std_vs_mfg = bool(bfld & 0x800)
selector = (bfld & 0xf000) >> 12
return (proc_nbr, std_vs_mfg, selector) | python | def get_table_idbb_field(endianess, data):
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 0x7ff
std_vs_mfg = bool(bfld & 0x800)
selector = (bfld & 0xf000) >> 12
return (proc_nbr, std_vs_mfg, selector) | [
"def",
"get_table_idbb_field",
"(",
"endianess",
",",
"data",
")",
":",
"bfld",
"=",
"struct",
".",
"unpack",
"(",
"endianess",
"+",
"'H'",
",",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"proc_nbr",
"=",
"bfld",
"&",
"0x7ff",
"std_vs_mfg",
"=",... | Return data from a packed TABLE_IDB_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg) | [
"Return",
"data",
"from",
"a",
"packed",
"TABLE_IDB_BFLD",
"bit",
"-",
"field",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L113-L126 |
241,132 | securestate/termineter | lib/c1219/data.py | get_table_idcb_field | def get_table_idcb_field(endianess, data):
"""
Return data from a packed TABLE_IDC_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 2047
std_vs_mfg = bool(bfld & 2048)
proc_flag = bool(bfld & 4096)
flag1 = bool(bfld & 8192)
flag2 = bool(bfld & 16384)
flag3 = bool(bfld & 32768)
return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | python | def get_table_idcb_field(endianess, data):
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 2047
std_vs_mfg = bool(bfld & 2048)
proc_flag = bool(bfld & 4096)
flag1 = bool(bfld & 8192)
flag2 = bool(bfld & 16384)
flag3 = bool(bfld & 32768)
return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | [
"def",
"get_table_idcb_field",
"(",
"endianess",
",",
"data",
")",
":",
"bfld",
"=",
"struct",
".",
"unpack",
"(",
"endianess",
"+",
"'H'",
",",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"proc_nbr",
"=",
"bfld",
"&",
"2047",
"std_vs_mfg",
"=",
... | Return data from a packed TABLE_IDC_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | [
"Return",
"data",
"from",
"a",
"packed",
"TABLE_IDC_BFLD",
"bit",
"-",
"field",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L128-L144 |
241,133 | securestate/termineter | lib/termineter/utilities.py | unique | def unique(seq, idfunc=None):
"""
Unique a list or tuple and preserve the order
@type idfunc: Function or None
@param idfunc: If idfunc is provided it will be called during the
comparison process.
"""
if idfunc is None:
idfunc = lambda x: x
preserved_type = type(seq)
seen = {}
result = []
for item in seq:
marker = idfunc(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return preserved_type(result) | python | def unique(seq, idfunc=None):
if idfunc is None:
idfunc = lambda x: x
preserved_type = type(seq)
seen = {}
result = []
for item in seq:
marker = idfunc(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return preserved_type(result) | [
"def",
"unique",
"(",
"seq",
",",
"idfunc",
"=",
"None",
")",
":",
"if",
"idfunc",
"is",
"None",
":",
"idfunc",
"=",
"lambda",
"x",
":",
"x",
"preserved_type",
"=",
"type",
"(",
"seq",
")",
"seen",
"=",
"{",
"}",
"result",
"=",
"[",
"]",
"for",
... | Unique a list or tuple and preserve the order
@type idfunc: Function or None
@param idfunc: If idfunc is provided it will be called during the
comparison process. | [
"Unique",
"a",
"list",
"or",
"tuple",
"and",
"preserve",
"the",
"order"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/utilities.py#L63-L82 |
241,134 | securestate/termineter | lib/termineter/interface.py | InteractiveInterpreter.do_ipy | def do_ipy(self, args):
"""Start an interactive Python interpreter"""
import c1218.data
import c1219.data
from c1219.access.general import C1219GeneralAccess
from c1219.access.security import C1219SecurityAccess
from c1219.access.log import C1219LogAccess
from c1219.access.telephone import C1219TelephoneAccess
vars = {
'termineter.__version__': termineter.__version__,
'C1218Packet': c1218.data.C1218Packet,
'C1218ReadRequest': c1218.data.C1218ReadRequest,
'C1218WriteRequest': c1218.data.C1218WriteRequest,
'C1219ProcedureInit': c1219.data.C1219ProcedureInit,
'C1219GeneralAccess': C1219GeneralAccess,
'C1219SecurityAccess': C1219SecurityAccess,
'C1219LogAccess': C1219LogAccess,
'C1219TelephoneAccess': C1219TelephoneAccess,
'frmwk': self.frmwk,
'os': os,
'sys': sys
}
banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep
banner += os.linesep
banner += 'The framework instance is in the \'frmwk\' variable.'
if self.frmwk.is_serial_connected():
vars['conn'] = self.frmwk.serial_connection
banner += os.linesep
banner += 'The connection instance is in the \'conn\' variable.'
try:
import IPython.terminal.embed
except ImportError:
pyconsole = code.InteractiveConsole(vars)
savestdin = os.dup(sys.stdin.fileno())
savestdout = os.dup(sys.stdout.fileno())
savestderr = os.dup(sys.stderr.fileno())
try:
pyconsole.interact(banner)
except SystemExit:
sys.stdin = os.fdopen(savestdin, 'r', 0)
sys.stdout = os.fdopen(savestdout, 'w', 0)
sys.stderr = os.fdopen(savestderr, 'w', 0)
else:
self.print_line(banner)
pyconsole = IPython.terminal.embed.InteractiveShellEmbed(
ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython')
)
pyconsole.mainloop(vars) | python | def do_ipy(self, args):
import c1218.data
import c1219.data
from c1219.access.general import C1219GeneralAccess
from c1219.access.security import C1219SecurityAccess
from c1219.access.log import C1219LogAccess
from c1219.access.telephone import C1219TelephoneAccess
vars = {
'termineter.__version__': termineter.__version__,
'C1218Packet': c1218.data.C1218Packet,
'C1218ReadRequest': c1218.data.C1218ReadRequest,
'C1218WriteRequest': c1218.data.C1218WriteRequest,
'C1219ProcedureInit': c1219.data.C1219ProcedureInit,
'C1219GeneralAccess': C1219GeneralAccess,
'C1219SecurityAccess': C1219SecurityAccess,
'C1219LogAccess': C1219LogAccess,
'C1219TelephoneAccess': C1219TelephoneAccess,
'frmwk': self.frmwk,
'os': os,
'sys': sys
}
banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep
banner += os.linesep
banner += 'The framework instance is in the \'frmwk\' variable.'
if self.frmwk.is_serial_connected():
vars['conn'] = self.frmwk.serial_connection
banner += os.linesep
banner += 'The connection instance is in the \'conn\' variable.'
try:
import IPython.terminal.embed
except ImportError:
pyconsole = code.InteractiveConsole(vars)
savestdin = os.dup(sys.stdin.fileno())
savestdout = os.dup(sys.stdout.fileno())
savestderr = os.dup(sys.stderr.fileno())
try:
pyconsole.interact(banner)
except SystemExit:
sys.stdin = os.fdopen(savestdin, 'r', 0)
sys.stdout = os.fdopen(savestdout, 'w', 0)
sys.stderr = os.fdopen(savestderr, 'w', 0)
else:
self.print_line(banner)
pyconsole = IPython.terminal.embed.InteractiveShellEmbed(
ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython')
)
pyconsole.mainloop(vars) | [
"def",
"do_ipy",
"(",
"self",
",",
"args",
")",
":",
"import",
"c1218",
".",
"data",
"import",
"c1219",
".",
"data",
"from",
"c1219",
".",
"access",
".",
"general",
"import",
"C1219GeneralAccess",
"from",
"c1219",
".",
"access",
".",
"security",
"import",
... | Start an interactive Python interpreter | [
"Start",
"an",
"interactive",
"Python",
"interpreter"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L308-L355 |
241,135 | securestate/termineter | lib/termineter/interface.py | InteractiveInterpreter.do_reload | def do_reload(self, args):
"""Reload a module in to the framework"""
if args.module is not None:
if args.module not in self.frmwk.modules:
self.print_error('Invalid Module Selected.')
return
module = self.frmwk.modules[args.module]
elif self.frmwk.current_module:
module = self.frmwk.current_module
else:
self.print_error('Must \'use\' module first')
return
self.reload_module(module) | python | def do_reload(self, args):
if args.module is not None:
if args.module not in self.frmwk.modules:
self.print_error('Invalid Module Selected.')
return
module = self.frmwk.modules[args.module]
elif self.frmwk.current_module:
module = self.frmwk.current_module
else:
self.print_error('Must \'use\' module first')
return
self.reload_module(module) | [
"def",
"do_reload",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"module",
"is",
"not",
"None",
":",
"if",
"args",
".",
"module",
"not",
"in",
"self",
".",
"frmwk",
".",
"modules",
":",
"self",
".",
"print_error",
"(",
"'Invalid Module Select... | Reload a module in to the framework | [
"Reload",
"a",
"module",
"in",
"to",
"the",
"framework"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L428-L440 |
241,136 | securestate/termineter | lib/c1218/connection.py | ConnectionBase.send | def send(self, data):
"""
This sends a raw C12.18 frame and waits checks for an ACK response.
In the event that a NACK is received, this function will attempt
to resend the frame up to 3 times.
:param data: the data to be transmitted
:type data: str, :py:class:`~c1218.data.C1218Packet`
"""
if not isinstance(data, C1218Packet):
data = C1218Packet(data)
if self.toggle_control: # bit wise, fuck yeah
if self._toggle_bit:
data.set_control(ord(data.control) | 0x20)
self._toggle_bit = False
elif not self._toggle_bit:
if ord(data.control) & 0x20:
data.set_control(ord(data.control) ^ 0x20)
self._toggle_bit = True
elif self.toggle_control and not isinstance(data, C1218Packet):
self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance')
data = data.build()
self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
for pktcount in range(0, 3):
self.write(data)
response = self.serial_h.read(1)
if response == NACK:
self.loggerio.warning('received a NACK after writing data')
time.sleep(0.10)
elif len(response) == 0:
self.loggerio.error('received empty response after writing data')
time.sleep(0.10)
elif response != ACK:
self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data')
else:
return
self.loggerio.critical('failed 3 times to correctly send a frame')
raise C1218IOError('failed 3 times to correctly send a frame') | python | def send(self, data):
if not isinstance(data, C1218Packet):
data = C1218Packet(data)
if self.toggle_control: # bit wise, fuck yeah
if self._toggle_bit:
data.set_control(ord(data.control) | 0x20)
self._toggle_bit = False
elif not self._toggle_bit:
if ord(data.control) & 0x20:
data.set_control(ord(data.control) ^ 0x20)
self._toggle_bit = True
elif self.toggle_control and not isinstance(data, C1218Packet):
self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance')
data = data.build()
self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
for pktcount in range(0, 3):
self.write(data)
response = self.serial_h.read(1)
if response == NACK:
self.loggerio.warning('received a NACK after writing data')
time.sleep(0.10)
elif len(response) == 0:
self.loggerio.error('received empty response after writing data')
time.sleep(0.10)
elif response != ACK:
self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data')
else:
return
self.loggerio.critical('failed 3 times to correctly send a frame')
raise C1218IOError('failed 3 times to correctly send a frame') | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"C1218Packet",
")",
":",
"data",
"=",
"C1218Packet",
"(",
"data",
")",
"if",
"self",
".",
"toggle_control",
":",
"# bit wise, fuck yeah",
"if",
"self",
".",
... | This sends a raw C12.18 frame and waits checks for an ACK response.
In the event that a NACK is received, this function will attempt
to resend the frame up to 3 times.
:param data: the data to be transmitted
:type data: str, :py:class:`~c1218.data.C1218Packet` | [
"This",
"sends",
"a",
"raw",
"C12",
".",
"18",
"frame",
"and",
"waits",
"checks",
"for",
"an",
"ACK",
"response",
".",
"In",
"the",
"event",
"that",
"a",
"NACK",
"is",
"received",
"this",
"function",
"will",
"attempt",
"to",
"resend",
"the",
"frame",
"... | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L120-L157 |
241,137 | securestate/termineter | lib/c1218/connection.py | ConnectionBase.recv | def recv(self, full_frame=False):
"""
Receive a C1218Packet, the payload data is returned.
:param bool full_frame: If set to True, the entire C1218 frame is
returned instead of just the payload.
"""
payloadbuffer = b''
tries = 3
while tries:
tmpbuffer = self.serial_h.read(1)
if tmpbuffer != b'\xee':
self.loggerio.error('did not receive \\xee as the first byte of the frame')
self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
tries -= 1
continue
tmpbuffer += self.serial_h.read(5)
sequence, length = struct.unpack('>xxxBH', tmpbuffer)
payload = self.serial_h.read(length)
tmpbuffer += payload
chksum = self.serial_h.read(2)
if chksum == packet_checksum(tmpbuffer):
self.serial_h.write(ACK)
data = tmpbuffer + chksum
self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
payloadbuffer += payload
if sequence == 0:
if full_frame:
payloadbuffer = data
if sys.version_info[0] == 2:
payloadbuffer = bytearray(payloadbuffer)
return payloadbuffer
else:
tries = 3
else:
self.serial_h.write(NACK)
self.loggerio.warning('crc does not match on received frame')
tries -= 1
self.loggerio.critical('failed 3 times to correctly receive a frame')
raise C1218IOError('failed 3 times to correctly receive a frame') | python | def recv(self, full_frame=False):
payloadbuffer = b''
tries = 3
while tries:
tmpbuffer = self.serial_h.read(1)
if tmpbuffer != b'\xee':
self.loggerio.error('did not receive \\xee as the first byte of the frame')
self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
tries -= 1
continue
tmpbuffer += self.serial_h.read(5)
sequence, length = struct.unpack('>xxxBH', tmpbuffer)
payload = self.serial_h.read(length)
tmpbuffer += payload
chksum = self.serial_h.read(2)
if chksum == packet_checksum(tmpbuffer):
self.serial_h.write(ACK)
data = tmpbuffer + chksum
self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
payloadbuffer += payload
if sequence == 0:
if full_frame:
payloadbuffer = data
if sys.version_info[0] == 2:
payloadbuffer = bytearray(payloadbuffer)
return payloadbuffer
else:
tries = 3
else:
self.serial_h.write(NACK)
self.loggerio.warning('crc does not match on received frame')
tries -= 1
self.loggerio.critical('failed 3 times to correctly receive a frame')
raise C1218IOError('failed 3 times to correctly receive a frame') | [
"def",
"recv",
"(",
"self",
",",
"full_frame",
"=",
"False",
")",
":",
"payloadbuffer",
"=",
"b''",
"tries",
"=",
"3",
"while",
"tries",
":",
"tmpbuffer",
"=",
"self",
".",
"serial_h",
".",
"read",
"(",
"1",
")",
"if",
"tmpbuffer",
"!=",
"b'\\xee'",
... | Receive a C1218Packet, the payload data is returned.
:param bool full_frame: If set to True, the entire C1218 frame is
returned instead of just the payload. | [
"Receive",
"a",
"C1218Packet",
"the",
"payload",
"data",
"is",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L159-L198 |
241,138 | securestate/termineter | lib/c1218/connection.py | ConnectionBase.read | def read(self, size):
"""
Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection.
"""
data = self.serial_h.read(size)
self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8'))
self.serial_h.write(ACK)
if sys.version_info[0] == 2:
data = bytearray(data)
return data | python | def read(self, size):
data = self.serial_h.read(size)
self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8'))
self.serial_h.write(ACK)
if sys.version_info[0] == 2:
data = bytearray(data)
return data | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"serial_h",
".",
"read",
"(",
"size",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'read data, length: '",
"+",
"str",
"(",
"len",
"(",
"data",
")",
")",
"+",
"' data: ... | Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection. | [
"Read",
"raw",
"data",
"from",
"the",
"serial",
"connection",
".",
"This",
"function",
"is",
"not",
"meant",
"to",
"be",
"called",
"directly",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L210-L222 |
241,139 | securestate/termineter | lib/c1218/connection.py | ConnectionBase.close | def close(self):
"""
Send a terminate request and then disconnect from the serial device.
"""
if self._initialized:
self.stop()
self.logged_in = False
return self.serial_h.close() | python | def close(self):
if self._initialized:
self.stop()
self.logged_in = False
return self.serial_h.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"logged_in",
"=",
"False",
"return",
"self",
".",
"serial_h",
".",
"close",
"(",
")"
] | Send a terminate request and then disconnect from the serial device. | [
"Send",
"a",
"terminate",
"request",
"and",
"then",
"disconnect",
"from",
"the",
"serial",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L224-L231 |
241,140 | securestate/termineter | lib/c1218/connection.py | Connection.start | def start(self):
"""
Send an identity request and then a negotiation request.
"""
self.serial_h.flushOutput()
self.serial_h.flushInput()
self.send(C1218IdentRequest())
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to identification service request')
return False
self._initialized = True
self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600))
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to negotiate service request')
self.stop()
raise C1218NegotiateError('received incorrect response to negotiate service request', data[0])
return True | python | def start(self):
self.serial_h.flushOutput()
self.serial_h.flushInput()
self.send(C1218IdentRequest())
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to identification service request')
return False
self._initialized = True
self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600))
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to negotiate service request')
self.stop()
raise C1218NegotiateError('received incorrect response to negotiate service request', data[0])
return True | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"serial_h",
".",
"flushOutput",
"(",
")",
"self",
".",
"serial_h",
".",
"flushInput",
"(",
")",
"self",
".",
"send",
"(",
"C1218IdentRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
... | Send an identity request and then a negotiation request. | [
"Send",
"an",
"identity",
"request",
"and",
"then",
"a",
"negotiation",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L278-L297 |
241,141 | securestate/termineter | lib/c1218/connection.py | Connection.stop | def stop(self, force=False):
"""
Send a terminate request.
:param bool force: ignore the remote devices response
"""
if self._initialized:
self.send(C1218TerminateRequest())
data = self.recv()
if data == b'\x00' or force:
self._initialized = False
self._toggle_bit = False
return True
return False | python | def stop(self, force=False):
if self._initialized:
self.send(C1218TerminateRequest())
data = self.recv()
if data == b'\x00' or force:
self._initialized = False
self._toggle_bit = False
return True
return False | [
"def",
"stop",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"send",
"(",
"C1218TerminateRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
"if",
"data",
"==",
"b'\\x00'",
... | Send a terminate request.
:param bool force: ignore the remote devices response | [
"Send",
"a",
"terminate",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L299-L312 |
241,142 | securestate/termineter | lib/c1218/connection.py | Connection.login | def login(self, username='0000', userid=0, password=None):
"""
Log into the connected device.
:param str username: the username to log in with (len(username) <= 10)
:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)
:param str password: password to log in with (len(password) <= 20)
:rtype: bool
"""
if password and len(password) > 20:
self.logger.error('password longer than 20 characters received')
raise Exception('password longer than 20 characters, login failed')
self.send(C1218LogonRequest(username, userid))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, username and user id rejected')
return False
if password is not None:
self.send(C1218SecurityRequest(password))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, password rejected')
return False
self.logged_in = True
return True | python | def login(self, username='0000', userid=0, password=None):
if password and len(password) > 20:
self.logger.error('password longer than 20 characters received')
raise Exception('password longer than 20 characters, login failed')
self.send(C1218LogonRequest(username, userid))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, username and user id rejected')
return False
if password is not None:
self.send(C1218SecurityRequest(password))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, password rejected')
return False
self.logged_in = True
return True | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"'0000'",
",",
"userid",
"=",
"0",
",",
"password",
"=",
"None",
")",
":",
"if",
"password",
"and",
"len",
"(",
"password",
")",
">",
"20",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'password... | Log into the connected device.
:param str username: the username to log in with (len(username) <= 10)
:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)
:param str password: password to log in with (len(password) <= 20)
:rtype: bool | [
"Log",
"into",
"the",
"connected",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L314-L341 |
241,143 | securestate/termineter | lib/c1218/connection.py | Connection.logoff | def logoff(self):
"""
Send a logoff request.
:rtype: bool
"""
self.send(C1218LogoffRequest())
data = self.recv()
if data == b'\x00':
self._initialized = False
return True
return False | python | def logoff(self):
self.send(C1218LogoffRequest())
data = self.recv()
if data == b'\x00':
self._initialized = False
return True
return False | [
"def",
"logoff",
"(",
"self",
")",
":",
"self",
".",
"send",
"(",
"C1218LogoffRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
"if",
"data",
"==",
"b'\\x00'",
":",
"self",
".",
"_initialized",
"=",
"False",
"return",
"True",
"retu... | Send a logoff request.
:rtype: bool | [
"Send",
"a",
"logoff",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L343-L354 |
241,144 | securestate/termineter | lib/c1218/connection.py | Connection.get_table_data | def get_table_data(self, tableid, octetcount=None, offset=None):
"""
Read data from a table. If successful, all of the data from the
requested table will be returned.
:param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff)
:param int octetcount: Limit the amount of data read, only works if
the meter supports this type of reading.
:param int offset: The offset at which to start to read the data from.
"""
if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys():
self.logger.info('returning cached table #' + str(tableid))
return self._table_cache[tableid]
self.send(C1218ReadRequest(tableid, offset, octetcount))
data = self.recv()
status = data[0]
if status != 0x00:
status = status
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details)
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status)
if len(data) < 4:
if len(data) == 0:
self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned')
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
length = struct.unpack('>H', data[1:3])[0]
chksum = data[-1]
data = data[3:-1]
if len(data) != length:
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
if not check_data_checksum(data, chksum):
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum')
if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys():
self.logger.info('caching table #' + str(tableid))
self._table_cache[tableid] = data
return data | python | def get_table_data(self, tableid, octetcount=None, offset=None):
if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys():
self.logger.info('returning cached table #' + str(tableid))
return self._table_cache[tableid]
self.send(C1218ReadRequest(tableid, offset, octetcount))
data = self.recv()
status = data[0]
if status != 0x00:
status = status
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details)
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status)
if len(data) < 4:
if len(data) == 0:
self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned')
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
length = struct.unpack('>H', data[1:3])[0]
chksum = data[-1]
data = data[3:-1]
if len(data) != length:
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
if not check_data_checksum(data, chksum):
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum')
if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys():
self.logger.info('caching table #' + str(tableid))
self._table_cache[tableid] = data
return data | [
"def",
"get_table_data",
"(",
"self",
",",
"tableid",
",",
"octetcount",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"if",
"self",
".",
"caching_enabled",
"and",
"tableid",
"in",
"self",
".",
"_cacheable_tables",
"and",
"tableid",
"in",
"self",
".",... | Read data from a table. If successful, all of the data from the
requested table will be returned.
:param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff)
:param int octetcount: Limit the amount of data read, only works if
the meter supports this type of reading.
:param int offset: The offset at which to start to read the data from. | [
"Read",
"data",
"from",
"a",
"table",
".",
"If",
"successful",
"all",
"of",
"the",
"data",
"from",
"the",
"requested",
"table",
"will",
"be",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L356-L396 |
241,145 | securestate/termineter | lib/c1218/connection.py | Connection.set_table_data | def set_table_data(self, tableid, data, offset=None):
"""
Write data to a table.
:param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff)
:param str data: The data to write into the table.
:param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff).
"""
self.send(C1218WriteRequest(tableid, data, offset))
data = self.recv()
if data[0] != 0x00:
status = data[0]
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not write data to the table, error: ' + details)
raise C1218WriteTableError('could not write data to the table, error: ' + details, status)
return | python | def set_table_data(self, tableid, data, offset=None):
self.send(C1218WriteRequest(tableid, data, offset))
data = self.recv()
if data[0] != 0x00:
status = data[0]
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not write data to the table, error: ' + details)
raise C1218WriteTableError('could not write data to the table, error: ' + details, status)
return | [
"def",
"set_table_data",
"(",
"self",
",",
"tableid",
",",
"data",
",",
"offset",
"=",
"None",
")",
":",
"self",
".",
"send",
"(",
"C1218WriteRequest",
"(",
"tableid",
",",
"data",
",",
"offset",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
... | Write data to a table.
:param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff)
:param str data: The data to write into the table.
:param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff). | [
"Write",
"data",
"to",
"a",
"table",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L398-L413 |
241,146 | securestate/termineter | lib/c1218/connection.py | Connection.run_procedure | def run_procedure(self, process_number, std_vs_mfg, params=''):
"""
Initiate a C1219 procedure, the request is written to table 7 and
the response is read from table 8.
:param int process_number: The numeric procedure identifier (0 <= process_number <= 2047).
:param bool std_vs_mfg: Whether the procedure is manufacturer specified
or not. True is manufacturer specified.
:param bytes params: The parameters to pass to the procedure initiation request.
:return: A tuple of the result code and the response data.
:rtype: tuple
"""
seqnum = random.randint(2, 254)
self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')')
procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build()
self.set_table_data(7, procedure_request)
response = self.get_table_data(8)
if response[:3] == procedure_request[:3]:
return response[3], response[4:]
else:
self.logger.error('invalid response from procedure response table (table #8)')
raise C1219ProcedureError('invalid response from procedure response table (table #8)') | python | def run_procedure(self, process_number, std_vs_mfg, params=''):
seqnum = random.randint(2, 254)
self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')')
procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build()
self.set_table_data(7, procedure_request)
response = self.get_table_data(8)
if response[:3] == procedure_request[:3]:
return response[3], response[4:]
else:
self.logger.error('invalid response from procedure response table (table #8)')
raise C1219ProcedureError('invalid response from procedure response table (table #8)') | [
"def",
"run_procedure",
"(",
"self",
",",
"process_number",
",",
"std_vs_mfg",
",",
"params",
"=",
"''",
")",
":",
"seqnum",
"=",
"random",
".",
"randint",
"(",
"2",
",",
"254",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'starting procedure: '",
"+",... | Initiate a C1219 procedure, the request is written to table 7 and
the response is read from table 8.
:param int process_number: The numeric procedure identifier (0 <= process_number <= 2047).
:param bool std_vs_mfg: Whether the procedure is manufacturer specified
or not. True is manufacturer specified.
:param bytes params: The parameters to pass to the procedure initiation request.
:return: A tuple of the result code and the response data.
:rtype: tuple | [
"Initiate",
"a",
"C1219",
"procedure",
"the",
"request",
"is",
"written",
"to",
"table",
"7",
"and",
"the",
"response",
"is",
"read",
"from",
"table",
"8",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L415-L437 |
241,147 | securestate/termineter | lib/termineter/options.py | Options.add_string | def add_string(self, name, help, required=True, default=None):
"""
Add a new option with a type of String.
:param str name: The name of the option, how it will be referenced.
:param str help: The string returned as help to describe how the option is used.
:param bool required: Whether to require that this option be set or not.
:param str default: The default value for this option. If required is True and the user must specify it, set to anything but None.
"""
self._options[name] = Option(name, 'str', help, required, default=default) | python | def add_string(self, name, help, required=True, default=None):
self._options[name] = Option(name, 'str', help, required, default=default) | [
"def",
"add_string",
"(",
"self",
",",
"name",
",",
"help",
",",
"required",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_options",
"[",
"name",
"]",
"=",
"Option",
"(",
"name",
",",
"'str'",
",",
"help",
",",
"required",
",",... | Add a new option with a type of String.
:param str name: The name of the option, how it will be referenced.
:param str help: The string returned as help to describe how the option is used.
:param bool required: Whether to require that this option be set or not.
:param str default: The default value for this option. If required is True and the user must specify it, set to anything but None. | [
"Add",
"a",
"new",
"option",
"with",
"a",
"type",
"of",
"String",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L80-L89 |
241,148 | securestate/termineter | lib/termineter/options.py | Options.set_option_value | def set_option_value(self, name, value):
"""
Set an option's value.
:param str name: The name of the option to set the value for.
:param str value: The value to set the option to, it will be converted from a string.
:return: The previous value for the specified option.
"""
option = self.get_option(name)
old_value = option.value
if option.type in ('str', 'rfile'):
option.value = value
elif option.type == 'int':
value = value.lower()
if not value.isdigit():
if value.startswith('0x') and string_is_hex(value[2:]):
value = int(value[2:], 16)
else:
raise TypeError('invalid value type')
option.value = int(value)
elif option.type == 'flt':
if value.count('.') > 1:
raise TypeError('invalid value type')
if not value.replace('.', '').isdigit():
raise TypeError('invalid value type')
option.value = float(value)
elif option.type == 'bool':
if value.lower() in ['true', '1', 'on']:
option.value = True
elif value.lower() in ['false', '0', 'off']:
option.value = False
else:
raise TypeError('invalid value type')
else:
raise Exception('unknown value type')
if option.callback and not option.callback(value, old_value):
option.value = old_value
return False
return True | python | def set_option_value(self, name, value):
option = self.get_option(name)
old_value = option.value
if option.type in ('str', 'rfile'):
option.value = value
elif option.type == 'int':
value = value.lower()
if not value.isdigit():
if value.startswith('0x') and string_is_hex(value[2:]):
value = int(value[2:], 16)
else:
raise TypeError('invalid value type')
option.value = int(value)
elif option.type == 'flt':
if value.count('.') > 1:
raise TypeError('invalid value type')
if not value.replace('.', '').isdigit():
raise TypeError('invalid value type')
option.value = float(value)
elif option.type == 'bool':
if value.lower() in ['true', '1', 'on']:
option.value = True
elif value.lower() in ['false', '0', 'off']:
option.value = False
else:
raise TypeError('invalid value type')
else:
raise Exception('unknown value type')
if option.callback and not option.callback(value, old_value):
option.value = old_value
return False
return True | [
"def",
"set_option_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"option",
"=",
"self",
".",
"get_option",
"(",
"name",
")",
"old_value",
"=",
"option",
".",
"value",
"if",
"option",
".",
"type",
"in",
"(",
"'str'",
",",
"'rfile'",
")",
"... | Set an option's value.
:param str name: The name of the option to set the value for.
:param str value: The value to set the option to, it will be converted from a string.
:return: The previous value for the specified option. | [
"Set",
"an",
"option",
"s",
"value",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L153-L191 |
241,149 | securestate/termineter | lib/termineter/options.py | Options.get_missing_options | def get_missing_options(self):
"""
Get a list of options that are required, but with default values
of None.
"""
return [option.name for option in self._options.values() if option.required and option.value is None] | python | def get_missing_options(self):
return [option.name for option in self._options.values() if option.required and option.value is None] | [
"def",
"get_missing_options",
"(",
"self",
")",
":",
"return",
"[",
"option",
".",
"name",
"for",
"option",
"in",
"self",
".",
"_options",
".",
"values",
"(",
")",
"if",
"option",
".",
"required",
"and",
"option",
".",
"value",
"is",
"None",
"]"
] | Get a list of options that are required, but with default values
of None. | [
"Get",
"a",
"list",
"of",
"options",
"that",
"are",
"required",
"but",
"with",
"default",
"values",
"of",
"None",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L193-L198 |
241,150 | securestate/termineter | lib/termineter/__init__.py | get_revision | def get_revision():
"""
Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:return: The git revision tag if it's available.
:rtype: str
"""
git_bin = smoke_zephyr.utilities.which('git')
if not git_bin:
return None
proc_h = subprocess.Popen(
(git_bin, 'rev-parse', 'HEAD'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
rev = proc_h.stdout.read().strip()
proc_h.wait()
if not len(rev):
return None
return rev.decode('utf-8') | python | def get_revision():
git_bin = smoke_zephyr.utilities.which('git')
if not git_bin:
return None
proc_h = subprocess.Popen(
(git_bin, 'rev-parse', 'HEAD'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
rev = proc_h.stdout.read().strip()
proc_h.wait()
if not len(rev):
return None
return rev.decode('utf-8') | [
"def",
"get_revision",
"(",
")",
":",
"git_bin",
"=",
"smoke_zephyr",
".",
"utilities",
".",
"which",
"(",
"'git'",
")",
"if",
"not",
"git_bin",
":",
"return",
"None",
"proc_h",
"=",
"subprocess",
".",
"Popen",
"(",
"(",
"git_bin",
",",
"'rev-parse'",
",... | Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:return: The git revision tag if it's available.
:rtype: str | [
"Retrieve",
"the",
"current",
"git",
"revision",
"identifier",
".",
"If",
"the",
"git",
"binary",
"can",
"not",
"be",
"found",
"or",
"the",
"repository",
"information",
"is",
"unavailable",
"None",
"will",
"be",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/__init__.py#L42-L64 |
241,151 | securestate/termineter | lib/termineter/core.py | Framework.reload_module | def reload_module(self, module_path=None):
"""
Reloads a module into the framework. If module_path is not
specified, then the current_module variable is used. Returns True
on success, False on error.
@type module_path: String
@param module_path: The name of the module to reload
"""
if module_path is None:
if self.current_module is not None:
module_path = self.current_module.name
else:
self.logger.warning('must specify module if not module is currently being used')
return False
if module_path not in self.module:
self.logger.error('invalid module requested for reload')
raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload')
self.logger.info('reloading module: ' + module_path)
module_instance = self.import_module(module_path, reload_module=True)
if not isinstance(module_instance, termineter.module.TermineterModule):
self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class')
if not hasattr(module_instance, 'run'):
self.logger.error('module: ' + module_path + ' has no run() method')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method')
if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options):
self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances')
raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances')
module_instance.name = module_path.split('/')[-1]
module_instance.path = module_path
self.modules[module_path] = module_instance
if self.current_module is not None:
if self.current_module.path == module_instance.path:
self.current_module = module_instance
return True | python | def reload_module(self, module_path=None):
if module_path is None:
if self.current_module is not None:
module_path = self.current_module.name
else:
self.logger.warning('must specify module if not module is currently being used')
return False
if module_path not in self.module:
self.logger.error('invalid module requested for reload')
raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload')
self.logger.info('reloading module: ' + module_path)
module_instance = self.import_module(module_path, reload_module=True)
if not isinstance(module_instance, termineter.module.TermineterModule):
self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class')
if not hasattr(module_instance, 'run'):
self.logger.error('module: ' + module_path + ' has no run() method')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method')
if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options):
self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances')
raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances')
module_instance.name = module_path.split('/')[-1]
module_instance.path = module_path
self.modules[module_path] = module_instance
if self.current_module is not None:
if self.current_module.path == module_instance.path:
self.current_module = module_instance
return True | [
"def",
"reload_module",
"(",
"self",
",",
"module_path",
"=",
"None",
")",
":",
"if",
"module_path",
"is",
"None",
":",
"if",
"self",
".",
"current_module",
"is",
"not",
"None",
":",
"module_path",
"=",
"self",
".",
"current_module",
".",
"name",
"else",
... | Reloads a module into the framework. If module_path is not
specified, then the current_module variable is used. Returns True
on success, False on error.
@type module_path: String
@param module_path: The name of the module to reload | [
"Reloads",
"a",
"module",
"into",
"the",
"framework",
".",
"If",
"module_path",
"is",
"not",
"specified",
"then",
"the",
"current_module",
"variable",
"is",
"used",
".",
"Returns",
"True",
"on",
"success",
"False",
"on",
"error",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L168-L204 |
241,152 | securestate/termineter | lib/termineter/core.py | Framework.serial_disconnect | def serial_disconnect(self):
"""
Closes the serial connection to the meter and disconnects from the
device.
"""
if self._serial_connected:
try:
self.serial_connection.close()
except c1218.errors.C1218IOError as error:
self.logger.error('caught C1218IOError: ' + str(error))
except serial.serialutil.SerialException as error:
self.logger.error('caught SerialException: ' + str(error))
self._serial_connected = False
self.logger.warning('the serial interface has been disconnected')
return True | python | def serial_disconnect(self):
if self._serial_connected:
try:
self.serial_connection.close()
except c1218.errors.C1218IOError as error:
self.logger.error('caught C1218IOError: ' + str(error))
except serial.serialutil.SerialException as error:
self.logger.error('caught SerialException: ' + str(error))
self._serial_connected = False
self.logger.warning('the serial interface has been disconnected')
return True | [
"def",
"serial_disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_serial_connected",
":",
"try",
":",
"self",
".",
"serial_connection",
".",
"close",
"(",
")",
"except",
"c1218",
".",
"errors",
".",
"C1218IOError",
"as",
"error",
":",
"self",
".",
... | Closes the serial connection to the meter and disconnects from the
device. | [
"Closes",
"the",
"serial",
"connection",
"to",
"the",
"meter",
"and",
"disconnects",
"from",
"the",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L324-L338 |
241,153 | securestate/termineter | lib/termineter/core.py | Framework.serial_get | def serial_get(self):
"""
Create the serial connection from the framework settings and return
it, setting the framework instance in the process.
"""
frmwk_c1218_settings = {
'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'],
'pktsize': self.advanced_options['C1218_PACKET_SIZE']
}
frmwk_serial_settings = termineter.utilities.get_default_serial_settings()
frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE']
frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE']
frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS']
self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION'])
try:
self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES'])
except Exception as error:
self.logger.error('could not open the serial device')
raise error
return self.serial_connection | python | def serial_get(self):
frmwk_c1218_settings = {
'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'],
'pktsize': self.advanced_options['C1218_PACKET_SIZE']
}
frmwk_serial_settings = termineter.utilities.get_default_serial_settings()
frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE']
frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE']
frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS']
self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION'])
try:
self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES'])
except Exception as error:
self.logger.error('could not open the serial device')
raise error
return self.serial_connection | [
"def",
"serial_get",
"(",
"self",
")",
":",
"frmwk_c1218_settings",
"=",
"{",
"'nbrpkts'",
":",
"self",
".",
"advanced_options",
"[",
"'C1218_MAX_PACKETS'",
"]",
",",
"'pktsize'",
":",
"self",
".",
"advanced_options",
"[",
"'C1218_PACKET_SIZE'",
"]",
"}",
"frmwk... | Create the serial connection from the framework settings and return
it, setting the framework instance in the process. | [
"Create",
"the",
"serial",
"connection",
"from",
"the",
"framework",
"settings",
"and",
"return",
"it",
"setting",
"the",
"framework",
"instance",
"in",
"the",
"process",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L340-L361 |
241,154 | securestate/termineter | lib/termineter/core.py | Framework.serial_connect | def serial_connect(self):
"""
Connect to the serial device.
"""
self.serial_get()
try:
self.serial_connection.start()
except c1218.errors.C1218IOError as error:
self.logger.error('serial connection has been opened but the meter is unresponsive')
raise error
self._serial_connected = True
return True | python | def serial_connect(self):
self.serial_get()
try:
self.serial_connection.start()
except c1218.errors.C1218IOError as error:
self.logger.error('serial connection has been opened but the meter is unresponsive')
raise error
self._serial_connected = True
return True | [
"def",
"serial_connect",
"(",
"self",
")",
":",
"self",
".",
"serial_get",
"(",
")",
"try",
":",
"self",
".",
"serial_connection",
".",
"start",
"(",
")",
"except",
"c1218",
".",
"errors",
".",
"C1218IOError",
"as",
"error",
":",
"self",
".",
"logger",
... | Connect to the serial device. | [
"Connect",
"to",
"the",
"serial",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L363-L374 |
241,155 | securestate/termineter | lib/termineter/core.py | Framework.serial_login | def serial_login(self):
"""
Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be
called by modules in order to login with a username and password configured within the framework instance.
"""
if not self._serial_connected:
raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected')
username = self.options['USERNAME']
user_id = self.options['USER_ID']
password = self.options['PASSWORD']
if self.options['PASSWORD_HEX']:
hex_regex = re.compile('^([0-9a-fA-F]{2})+$')
if hex_regex.match(password) is None:
self.print_error('Invalid characters in password')
raise termineter.errors.FrameworkConfigurationError('invalid characters in password')
password = binascii.a2b_hex(password)
if len(username) > 10:
self.print_error('Username cannot be longer than 10 characters')
raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters')
if not (0 <= user_id <= 0xffff):
self.print_error('User id must be between 0 and 0xffff')
raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff')
if len(password) > 20:
self.print_error('Password cannot be longer than 20 characters')
raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters')
if not self.serial_connection.login(username, user_id, password):
return False
return True | python | def serial_login(self):
if not self._serial_connected:
raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected')
username = self.options['USERNAME']
user_id = self.options['USER_ID']
password = self.options['PASSWORD']
if self.options['PASSWORD_HEX']:
hex_regex = re.compile('^([0-9a-fA-F]{2})+$')
if hex_regex.match(password) is None:
self.print_error('Invalid characters in password')
raise termineter.errors.FrameworkConfigurationError('invalid characters in password')
password = binascii.a2b_hex(password)
if len(username) > 10:
self.print_error('Username cannot be longer than 10 characters')
raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters')
if not (0 <= user_id <= 0xffff):
self.print_error('User id must be between 0 and 0xffff')
raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff')
if len(password) > 20:
self.print_error('Password cannot be longer than 20 characters')
raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters')
if not self.serial_connection.login(username, user_id, password):
return False
return True | [
"def",
"serial_login",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_serial_connected",
":",
"raise",
"termineter",
".",
"errors",
".",
"FrameworkRuntimeError",
"(",
"'the serial interface is disconnected'",
")",
"username",
"=",
"self",
".",
"options",
"[",
... | Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be
called by modules in order to login with a username and password configured within the framework instance. | [
"Attempt",
"to",
"log",
"into",
"the",
"meter",
"over",
"the",
"C12",
".",
"18",
"protocol",
".",
"Returns",
"True",
"on",
"success",
"False",
"on",
"a",
"failure",
".",
"This",
"can",
"be",
"called",
"by",
"modules",
"in",
"order",
"to",
"login",
"wit... | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L376-L405 |
241,156 | MasoniteFramework/masonite | databases/seeds/user_table_seeder.py | UserTableSeeder.run | def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | python | def run(self):
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"register",
"(",
"User",
",",
"self",
".",
"users_factory",
")",
"self",
".",
"factory",
"(",
"User",
",",
"50",
")",
".",
"create",
"(",
")"
] | Run the database seeds. | [
"Run",
"the",
"database",
"seeds",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/seeds/user_table_seeder.py#L18-L24 |
241,157 | MasoniteFramework/masonite | bootstrap/start.py | app | def app(environ, start_response):
"""The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response
"""
from wsgi import container
"""Add Environ To Service Container
Add the environ to the service container. The environ is generated by the
the WSGI server above and used by a service provider to manipulate the
incoming requests
"""
container.bind('Environ', environ)
"""Execute All Service Providers That Require The WSGI Server
Run all service provider boot methods if the wsgi attribute is true.
"""
try:
for provider in container.make('WSGIProviders'):
container.resolve(provider.boot)
except Exception as e:
container.make('ExceptionHandler').load_exception(e)
"""We Are Ready For Launch
If we have a solid response and not redirecting then we need to return
a 200 status code along with the data. If we don't, then we'll have
to return a 302 redirection to where ever the user would like go
to next.
"""
start_response(container.make('Request').get_status_code(),
container.make('Request').get_and_reset_headers())
"""Final Step
This will take the data variable from the Service Container and return
it to the WSGI server.
"""
return iter([bytes(container.make('Response'), 'utf-8')]) | python | def app(environ, start_response):
from wsgi import container
"""Add Environ To Service Container
Add the environ to the service container. The environ is generated by the
the WSGI server above and used by a service provider to manipulate the
incoming requests
"""
container.bind('Environ', environ)
"""Execute All Service Providers That Require The WSGI Server
Run all service provider boot methods if the wsgi attribute is true.
"""
try:
for provider in container.make('WSGIProviders'):
container.resolve(provider.boot)
except Exception as e:
container.make('ExceptionHandler').load_exception(e)
"""We Are Ready For Launch
If we have a solid response and not redirecting then we need to return
a 200 status code along with the data. If we don't, then we'll have
to return a 302 redirection to where ever the user would like go
to next.
"""
start_response(container.make('Request').get_status_code(),
container.make('Request').get_and_reset_headers())
"""Final Step
This will take the data variable from the Service Container and return
it to the WSGI server.
"""
return iter([bytes(container.make('Response'), 'utf-8')]) | [
"def",
"app",
"(",
"environ",
",",
"start_response",
")",
":",
"from",
"wsgi",
"import",
"container",
"\"\"\"Add Environ To Service Container\n Add the environ to the service container. The environ is generated by the\n the WSGI server above and used by a service provider to manipulate... | The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response | [
"The",
"WSGI",
"Application",
"Server",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/bootstrap/start.py#L12-L57 |
241,158 | MasoniteFramework/masonite | databases/migrations/2018_01_09_043202_create_users_table.py | CreateUsersTable.up | def up(self):
"""Run the migrations."""
with self.schema.create('users') as table:
table.increments('id')
table.string('name')
table.string('email').unique()
table.string('password')
table.string('remember_token').nullable()
table.timestamp('verified_at').nullable()
table.timestamps() | python | def up(self):
with self.schema.create('users') as table:
table.increments('id')
table.string('name')
table.string('email').unique()
table.string('password')
table.string('remember_token').nullable()
table.timestamp('verified_at').nullable()
table.timestamps() | [
"def",
"up",
"(",
"self",
")",
":",
"with",
"self",
".",
"schema",
".",
"create",
"(",
"'users'",
")",
"as",
"table",
":",
"table",
".",
"increments",
"(",
"'id'",
")",
"table",
".",
"string",
"(",
"'name'",
")",
"table",
".",
"string",
"(",
"'emai... | Run the migrations. | [
"Run",
"the",
"migrations",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/migrations/2018_01_09_043202_create_users_table.py#L6-L15 |
241,159 | MasoniteFramework/masonite | app/http/middleware/VerifyEmailMiddleware.py | VerifyEmailMiddleware.before | def before(self):
"""Run This Middleware Before The Route Executes."""
user = self.request.user()
if user and user.verified_at is None:
self.request.redirect('/email/verify') | python | def before(self):
user = self.request.user()
if user and user.verified_at is None:
self.request.redirect('/email/verify') | [
"def",
"before",
"(",
"self",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"(",
")",
"if",
"user",
"and",
"user",
".",
"verified_at",
"is",
"None",
":",
"self",
".",
"request",
".",
"redirect",
"(",
"'/email/verify'",
")"
] | Run This Middleware Before The Route Executes. | [
"Run",
"This",
"Middleware",
"Before",
"The",
"Route",
"Executes",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/middleware/VerifyEmailMiddleware.py#L17-L22 |
241,160 | MasoniteFramework/masonite | app/http/controllers/WelcomeController.py | WelcomeController.show | def show(self, view: View, request: Request):
"""Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class.
"""
return view.render('welcome', {
'app': request.app().make('Application')
}) | python | def show(self, view: View, request: Request):
return view.render('welcome', {
'app': request.app().make('Application')
}) | [
"def",
"show",
"(",
"self",
",",
"view",
":",
"View",
",",
"request",
":",
"Request",
")",
":",
"return",
"view",
".",
"render",
"(",
"'welcome'",
",",
"{",
"'app'",
":",
"request",
".",
"app",
"(",
")",
".",
"make",
"(",
"'Application'",
")",
"}",... | Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class. | [
"Show",
"the",
"welcome",
"page",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/controllers/WelcomeController.py#L10-L22 |
241,161 | pybluez/pybluez | bluetooth/btcommon.py | is_valid_address | def is_valid_address (s):
"""
returns True if address is a valid Bluetooth address
valid address are always strings of the form XX:XX:XX:XX:XX:XX
where X is a hexadecimal character. For example,
01:23:45:67:89:AB is a valid address, but
IN:VA:LI:DA:DD:RE is not
"""
try:
pairs = s.split (":")
if len (pairs) != 6: return False
if not all(0 <= int(b, 16) <= 255 for b in pairs): return False
except:
return False
return True | python | def is_valid_address (s):
try:
pairs = s.split (":")
if len (pairs) != 6: return False
if not all(0 <= int(b, 16) <= 255 for b in pairs): return False
except:
return False
return True | [
"def",
"is_valid_address",
"(",
"s",
")",
":",
"try",
":",
"pairs",
"=",
"s",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"pairs",
")",
"!=",
"6",
":",
"return",
"False",
"if",
"not",
"all",
"(",
"0",
"<=",
"int",
"(",
"b",
",",
"16",
... | returns True if address is a valid Bluetooth address
valid address are always strings of the form XX:XX:XX:XX:XX:XX
where X is a hexadecimal character. For example,
01:23:45:67:89:AB is a valid address, but
IN:VA:LI:DA:DD:RE is not | [
"returns",
"True",
"if",
"address",
"is",
"a",
"valid",
"Bluetooth",
"address"
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/btcommon.py#L182-L197 |
241,162 | 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):
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 |
241,163 | 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):
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 |
241,164 | 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):
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 |
241,165 | 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):
# 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 |
241,166 | 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):
# 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 |
241,167 | 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):
# 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 |
241,168 | 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):
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 |
241,169 | 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):
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 |
241,170 | 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 |
241,171 | 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 |
241,172 | 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 |
241,173 | 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):
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 |
241,174 | 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 |
241,175 | 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 |
241,176 | 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 |
241,177 | 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 |
241,178 | 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 |
241,179 | 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 |
241,180 | 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 |
241,181 | 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 |
241,182 | 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 |
241,183 | 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):
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 |
241,184 | 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):
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 |
241,185 | 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):
# 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 |
241,186 | 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):
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 |
241,187 | 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):
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 |
241,188 | 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):
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 |
241,189 | 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):
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 |
241,190 | 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):
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 |
241,191 | 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):
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 |
241,192 | 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):
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 |
241,193 | 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):
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 |
241,194 | 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):
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 |
241,195 | 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):
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 |
241,196 | 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):
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 |
241,197 | 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):
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 |
241,198 | 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):
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 |
241,199 | 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):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.