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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
28,400
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.begin_transaction
def begin_transaction( self, database, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.firestore_v1beta1.types.BeginTransactionResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "begin_transaction" not in self._inner_api_calls: self._inner_api_calls[ "begin_transaction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.begin_transaction, default_retry=self._method_configs["BeginTransaction"].retry, default_timeout=self._method_configs["BeginTransaction"].timeout, client_info=self._client_info, ) request = firestore_pb2.BeginTransactionRequest( database=database, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["begin_transaction"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def begin_transaction( self, database, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.firestore_v1beta1.types.BeginTransactionResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "begin_transaction" not in self._inner_api_calls: self._inner_api_calls[ "begin_transaction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.begin_transaction, default_retry=self._method_configs["BeginTransaction"].retry, default_timeout=self._method_configs["BeginTransaction"].timeout, client_info=self._client_info, ) request = firestore_pb2.BeginTransactionRequest( database=database, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("database", database)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["begin_transaction"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "begin_transaction", "(", "self", ",", "database", ",", "options_", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"begin_transaction\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"begin_transaction\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "begin_transaction", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BeginTransaction\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BeginTransaction\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "firestore_pb2", ".", "BeginTransactionRequest", "(", "database", "=", "database", ",", "options", "=", "options_", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"database\"", ",", "database", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"begin_transaction\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Starts a new transaction. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> >>> response = client.begin_transaction(database) Args: database (str): The database name. In the format: ``projects/{project_id}/databases/{database_id}``. options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction. Defaults to a read-write transaction. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.firestore_v1beta1.types.BeginTransactionResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Starts", "a", "new", "transaction", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L866-L942
28,401
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.run_query
def run_query( self, parent, structured_query=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "run_query" not in self._inner_api_calls: self._inner_api_calls[ "run_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_query, default_retry=self._method_configs["RunQuery"].retry, default_timeout=self._method_configs["RunQuery"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(structured_query=structured_query) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.RunQueryRequest( parent=parent, structured_query=structured_query, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def run_query( self, parent, structured_query=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "run_query" not in self._inner_api_calls: self._inner_api_calls[ "run_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_query, default_retry=self._method_configs["RunQuery"].retry, default_timeout=self._method_configs["RunQuery"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(structured_query=structured_query) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) request = firestore_pb2.RunQueryRequest( parent=parent, structured_query=structured_query, transaction=transaction, new_transaction=new_transaction, read_time=read_time, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["run_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "run_query", "(", "self", ",", "parent", ",", "structured_query", "=", "None", ",", "transaction", "=", "None", ",", "new_transaction", "=", "None", ",", "read_time", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"run_query\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"run_query\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "run_query", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"RunQuery\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"RunQuery\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "structured_query", "=", "structured_query", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "request", "=", "firestore_pb2", ".", "RunQueryRequest", "(", "parent", "=", "parent", ",", "structured_query", "=", "structured_query", ",", "transaction", "=", "transaction", ",", "new_transaction", "=", "new_transaction", ",", "read_time", "=", "read_time", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"run_query\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Runs a query. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> for element in client.run_query(parent): ... # process element ... pass Args: parent (str): The parent resource name. In the format: ``projects/{project_id}/databases/{database_id}/documents`` or ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. For example: ``projects/my-project/databases/my-database/documents`` or ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`` structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery` transaction (bytes): Reads documents in a transaction. new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents. Defaults to a read-only transaction. The new transaction ID will be returned as the first response in the stream. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions` read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time. This may not be older than 60 seconds. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Timestamp` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Runs", "a", "query", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L1102-L1214
28,402
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
FirestoreClient.write
def write( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "write" not in self._inner_api_calls: self._inner_api_calls[ "write" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write, default_retry=self._method_configs["Write"].retry, default_timeout=self._method_configs["Write"].timeout, client_info=self._client_info, ) return self._inner_api_calls["write"]( requests, retry=retry, timeout=timeout, metadata=metadata )
python
def write( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "write" not in self._inner_api_calls: self._inner_api_calls[ "write" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write, default_retry=self._method_configs["Write"].retry, default_timeout=self._method_configs["Write"].timeout, client_info=self._client_info, ) return self._inner_api_calls["write"]( requests, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "write", "(", "self", ",", "requests", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"write\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"write\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "write", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"Write\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"Write\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"write\"", "]", "(", "requests", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Streams batches of document updates and deletes, in order. EXPERIMENTAL: This method interface might change in the future. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> database = client.database_root_path('[PROJECT]', '[DATABASE]') >>> request = {'database': database} >>> >>> requests = [request] >>> for element in client.write(requests): ... # process element ... pass Args: requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Streams", "batches", "of", "document", "updates", "and", "deletes", "in", "order", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L1216-L1276
28,403
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.log_path
def log_path(cls, project, log): """Return a fully-qualified log string.""" return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
python
def log_path(cls, project, log): """Return a fully-qualified log string.""" return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
[ "def", "log_path", "(", "cls", ",", "project", ",", "log", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/logs/{log}\"", ",", "project", "=", "project", ",", "log", "=", "log", ")" ]
Return a fully-qualified log string.
[ "Return", "a", "fully", "-", "qualified", "log", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L75-L79
28,404
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py
LoggingServiceV2Client.delete_log
def delete_log( self, log_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_log" not in self._inner_api_calls: self._inner_api_calls[ "delete_log" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_log, default_retry=self._method_configs["DeleteLog"].retry, default_timeout=self._method_configs["DeleteLog"].timeout, client_info=self._client_info, ) request = logging_pb2.DeleteLogRequest(log_name=log_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("log_name", log_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_log"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def delete_log( self, log_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_log" not in self._inner_api_calls: self._inner_api_calls[ "delete_log" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_log, default_retry=self._method_configs["DeleteLog"].retry, default_timeout=self._method_configs["DeleteLog"].timeout, client_info=self._client_info, ) request = logging_pb2.DeleteLogRequest(log_name=log_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("log_name", log_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_log"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "delete_log", "(", "self", ",", "log_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"delete_log\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_log\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_log", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteLog\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteLog\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_pb2", ".", "DeleteLogRequest", "(", "log_name", "=", "log_name", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"log_name\"", ",", "log_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "self", ".", "_inner_api_calls", "[", "\"delete_log\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.LoggingServiceV2Client() >>> >>> log_name = client.log_path('[PROJECT]', '[LOG]') >>> >>> client.delete_log(log_name) Args: log_name (str): Required. The resource name of the log to delete: :: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" ``[LOG_ID]`` must be URL-encoded. For example, ``"projects/my-project-id/logs/syslog"``, ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. For more information about log names, see ``LogEntry``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "all", "the", "log", "entries", "in", "a", "log", ".", "The", "log", "reappears", "if", "it", "receives", "new", "entries", ".", "Log", "entries", "written", "shortly", "before", "the", "delete", "operation", "might", "not", "be", "deleted", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/logging_service_v2_client.py#L187-L266
28,405
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
_expand_variable_match
def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable '{}' not specified and needed by template " "`{}` at position {}".format(name, match.string, match.start()) ) elif positional is not None: try: return six.text_type(positional_vars.pop(0)) except IndexError: raise ValueError( "Positional variable not specified and needed by template " "`{}` at position {}".format(match.string, match.start()) ) else: raise ValueError("Unknown template expression {}".format(match.group(0)))
python
def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable '{}' not specified and needed by template " "`{}` at position {}".format(name, match.string, match.start()) ) elif positional is not None: try: return six.text_type(positional_vars.pop(0)) except IndexError: raise ValueError( "Positional variable not specified and needed by template " "`{}` at position {}".format(match.string, match.start()) ) else: raise ValueError("Unknown template expression {}".format(match.group(0)))
[ "def", "_expand_variable_match", "(", "positional_vars", ",", "named_vars", ",", "match", ")", ":", "positional", "=", "match", ".", "group", "(", "\"positional\"", ")", "name", "=", "match", ".", "group", "(", "\"name\"", ")", "if", "name", "is", "not", "None", ":", "try", ":", "return", "six", ".", "text_type", "(", "named_vars", "[", "name", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Named variable '{}' not specified and needed by template \"", "\"`{}` at position {}\"", ".", "format", "(", "name", ",", "match", ".", "string", ",", "match", ".", "start", "(", ")", ")", ")", "elif", "positional", "is", "not", "None", ":", "try", ":", "return", "six", ".", "text_type", "(", "positional_vars", ".", "pop", "(", "0", ")", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Positional variable not specified and needed by template \"", "\"`{}` at position {}\"", ".", "format", "(", "match", ".", "string", ",", "match", ".", "start", "(", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown template expression {}\"", ".", "format", "(", "match", ".", "group", "(", "0", ")", ")", ")" ]
Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered.
[ "Expand", "a", "matched", "variable", "with", "its", "value", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L65-L101
28,406
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
expand
def expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ replacer = functools.partial(_expand_variable_match, list(args), kwargs) return _VARIABLE_RE.sub(replacer, tmpl)
python
def expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered. """ replacer = functools.partial(_expand_variable_match, list(args), kwargs) return _VARIABLE_RE.sub(replacer, tmpl)
[ "def", "expand", "(", "tmpl", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "replacer", "=", "functools", ".", "partial", "(", "_expand_variable_match", ",", "list", "(", "args", ")", ",", "kwargs", ")", "return", "_VARIABLE_RE", ".", "sub", "(", "replacer", ",", "tmpl", ")" ]
Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args: tmpl (str): The path template. args: The positional variables for the path. kwargs: The named variables for the path. Returns: str: The expanded path Raises: ValueError: If a positional or named variable is required by the template but not specified or if an unexpected template expression is encountered.
[ "Expand", "a", "path", "template", "with", "the", "given", "variables", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L104-L128
28,407
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
_replace_variable_with_pattern
def _replace_variable_with_pattern(match): """Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") template = match.group("template") if name is not None: if not template: return _SINGLE_SEGMENT_PATTERN.format(name) elif template == "**": return _MULTI_SEGMENT_PATTERN.format(name) else: return _generate_pattern_for_template(template) elif positional == "*": return _SINGLE_SEGMENT_PATTERN elif positional == "**": return _MULTI_SEGMENT_PATTERN else: raise ValueError("Unknown template expression {}".format(match.group(0)))
python
def _replace_variable_with_pattern(match): """Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered. """ positional = match.group("positional") name = match.group("name") template = match.group("template") if name is not None: if not template: return _SINGLE_SEGMENT_PATTERN.format(name) elif template == "**": return _MULTI_SEGMENT_PATTERN.format(name) else: return _generate_pattern_for_template(template) elif positional == "*": return _SINGLE_SEGMENT_PATTERN elif positional == "**": return _MULTI_SEGMENT_PATTERN else: raise ValueError("Unknown template expression {}".format(match.group(0)))
[ "def", "_replace_variable_with_pattern", "(", "match", ")", ":", "positional", "=", "match", ".", "group", "(", "\"positional\"", ")", "name", "=", "match", ".", "group", "(", "\"name\"", ")", "template", "=", "match", ".", "group", "(", "\"template\"", ")", "if", "name", "is", "not", "None", ":", "if", "not", "template", ":", "return", "_SINGLE_SEGMENT_PATTERN", ".", "format", "(", "name", ")", "elif", "template", "==", "\"**\"", ":", "return", "_MULTI_SEGMENT_PATTERN", ".", "format", "(", "name", ")", "else", ":", "return", "_generate_pattern_for_template", "(", "template", ")", "elif", "positional", "==", "\"*\"", ":", "return", "_SINGLE_SEGMENT_PATTERN", "elif", "positional", "==", "\"**\"", ":", "return", "_MULTI_SEGMENT_PATTERN", "else", ":", "raise", "ValueError", "(", "\"Unknown template expression {}\"", ".", "format", "(", "match", ".", "group", "(", "0", ")", ")", ")" ]
Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular expression match Returns: str: A regular expression pattern that can be used to validate the variable in an expanded path. Raises: ValueError: If an unexpected template expression is encountered.
[ "Replace", "a", "variable", "match", "with", "a", "pattern", "that", "can", "be", "used", "to", "validate", "it", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L131-L159
28,408
googleapis/google-cloud-python
api_core/google/api_core/path_template.py
validate
def validate(tmpl, path): """Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches. """ pattern = _generate_pattern_for_template(tmpl) + "$" return True if re.match(pattern, path) is not None else False
python
def validate(tmpl, path): """Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches. """ pattern = _generate_pattern_for_template(tmpl) + "$" return True if re.match(pattern, path) is not None else False
[ "def", "validate", "(", "tmpl", ",", "path", ")", ":", "pattern", "=", "_generate_pattern_for_template", "(", "tmpl", ")", "+", "\"$\"", "return", "True", "if", "re", ".", "match", "(", "pattern", ",", "path", ")", "is", "not", "None", "else", "False" ]
Validate a path against the path template. .. code-block:: python >>> validate('users/*/messages/*', 'users/me/messages/123') True >>> validate('users/*/messages/*', 'users/me/drafts/123') False >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3) True >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3) False Args: tmpl (str): The path template. path (str): The expanded path. Returns: bool: True if the path matches.
[ "Validate", "a", "path", "against", "the", "path", "template", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/path_template.py#L175-L197
28,409
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.name
def name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name. """ return self.instance_admin_client.app_profile_path( self._instance._client.project, self._instance.instance_id, self.app_profile_id, )
python
def name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name. """ return self.instance_admin_client.app_profile_path( self._instance._client.project, self._instance.instance_id, self.app_profile_id, )
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "instance_admin_client", ".", "app_profile_path", "(", "self", ".", "_instance", ".", "_client", ".", "project", ",", "self", ".", "_instance", ".", "instance_id", ",", "self", ".", "app_profile_id", ",", ")" ]
AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` :rtype: str :returns: The AppProfile name.
[ "AppProfile", "name", "used", "in", "requests", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L85-L103
28,410
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.from_pb
def from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_id}`` or if the parsed instance ID does not match the istance ID on the client. or if the parsed project ID does not match the project ID on the client. """ match_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.name, ) if match_app_profile_name.group("instance") != instance.instance_id: raise ValueError( "Instance ID on app_profile does not match the " "instance ID on the client" ) if match_app_profile_name.group("project") != instance._client.project: raise ValueError( "Project ID on app_profile does not match the " "project ID on the client" ) app_profile_id = match_app_profile_name.group("app_profile_id") result = cls(app_profile_id, instance) result._update_from_pb(app_profile_pb) return result
python
def from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_id}`` or if the parsed instance ID does not match the istance ID on the client. or if the parsed project ID does not match the project ID on the client. """ match_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.name, ) if match_app_profile_name.group("instance") != instance.instance_id: raise ValueError( "Instance ID on app_profile does not match the " "instance ID on the client" ) if match_app_profile_name.group("project") != instance._client.project: raise ValueError( "Project ID on app_profile does not match the " "project ID on the client" ) app_profile_id = match_app_profile_name.group("app_profile_id") result = cls(app_profile_id, instance) result._update_from_pb(app_profile_pb) return result
[ "def", "from_pb", "(", "cls", ",", "app_profile_pb", ",", "instance", ")", ":", "match_app_profile_name", "=", "_APP_PROFILE_NAME_RE", ".", "match", "(", "app_profile_pb", ".", "name", ")", "if", "match_app_profile_name", "is", "None", ":", "raise", "ValueError", "(", "\"AppProfile protobuf name was not in the \"", "\"expected format.\"", ",", "app_profile_pb", ".", "name", ",", ")", "if", "match_app_profile_name", ".", "group", "(", "\"instance\"", ")", "!=", "instance", ".", "instance_id", ":", "raise", "ValueError", "(", "\"Instance ID on app_profile does not match the \"", "\"instance ID on the client\"", ")", "if", "match_app_profile_name", ".", "group", "(", "\"project\"", ")", "!=", "instance", ".", "_client", ".", "project", ":", "raise", "ValueError", "(", "\"Project ID on app_profile does not match the \"", "\"project ID on the client\"", ")", "app_profile_id", "=", "match_app_profile_name", ".", "group", "(", "\"app_profile_id\"", ")", "result", "=", "cls", "(", "app_profile_id", ",", "instance", ")", "result", ".", "_update_from_pb", "(", "app_profile_pb", ")", "return", "result" ]
Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. :rtype: :class:`AppProfile` :returns: The AppProfile parsed from the protobuf response. :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile name does not match ``projects/{project}/instances/{instance_id}/appProfiles/{app_profile_id}`` or if the parsed instance ID does not match the istance ID on the client. or if the parsed project ID does not match the project ID on the client.
[ "Creates", "an", "instance", "app_profile", "from", "a", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L131-L171
28,411
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.reload
def reload(self): """Reload the metadata for this cluster""" app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request. self._update_from_pb(app_profile_pb)
python
def reload(self): """Reload the metadata for this cluster""" app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request. self._update_from_pb(app_profile_pb)
[ "def", "reload", "(", "self", ")", ":", "app_profile_pb", "=", "self", ".", "instance_admin_client", ".", "get_app_profile", "(", "self", ".", "name", ")", "# NOTE: _update_from_pb does not check that the project and", "# app_profile ID on the response match the request.", "self", ".", "_update_from_pb", "(", "app_profile_pb", ")" ]
Reload the metadata for this cluster
[ "Reload", "the", "metadata", "for", "this", "cluster" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L227-L234
28,412
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.exists
def exists(self): """Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """ try: self.instance_admin_client.get_app_profile(self.name) return True # NOTE: There could be other exceptions that are returned to the user. except NotFound: return False
python
def exists(self): """Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """ try: self.instance_admin_client.get_app_profile(self.name) return True # NOTE: There could be other exceptions that are returned to the user. except NotFound: return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "instance_admin_client", ".", "get_app_profile", "(", "self", ".", "name", ")", "return", "True", "# NOTE: There could be other exceptions that are returned to the user.", "except", "NotFound", ":", "return", "False" ]
Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False.
[ "Check", "whether", "the", "AppProfile", "already", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L236-L247
28,413
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.create
def create(self, ignore_warnings=None): """Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile. """ return self.from_pb( self.instance_admin_client.create_app_profile( parent=self._instance.name, app_profile_id=self.app_profile_id, app_profile=self._to_pb(), ignore_warnings=ignore_warnings, ), self._instance, )
python
def create(self, ignore_warnings=None): """Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile. """ return self.from_pb( self.instance_admin_client.create_app_profile( parent=self._instance.name, app_profile_id=self.app_profile_id, app_profile=self._to_pb(), ignore_warnings=ignore_warnings, ), self._instance, )
[ "def", "create", "(", "self", ",", "ignore_warnings", "=", "None", ")", ":", "return", "self", ".", "from_pb", "(", "self", ".", "instance_admin_client", ".", "create_app_profile", "(", "parent", "=", "self", ".", "_instance", ".", "name", ",", "app_profile_id", "=", "self", ".", "app_profile_id", ",", "app_profile", "=", "self", ".", "_to_pb", "(", ")", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")", ",", "self", ".", "_instance", ",", ")" ]
Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in addition to the ``routing_policy_type``, ``description``, ``cluster_id`` and ``allow_transactional_writes``. To change them before creating, reset the values via .. code:: python app_profile.app_profile_id = 'i-changed-my-mind' app_profile.routing_policy_type = ( google.cloud.bigtable.enums.RoutingPolicyType.SINGLE ) app_profile.description = 'new-description' app-profile.cluster_id = 'other-cluster-id' app-profile.allow_transactional_writes = True before calling :meth:`create`. :type: ignore_warnings: bool :param: ignore_warnings: (Optional) If true, ignore safety checks when creating the AppProfile.
[ "Create", "this", "AppProfile", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L249-L283
28,414
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/app_profile.py
AppProfile.update
def update(self, ignore_warnings=None): """Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes`` """ update_mask_pb = field_mask_pb2.FieldMask() if self.description is not None: update_mask_pb.paths.append("description") if self.routing_policy_type == RoutingPolicyType.ANY: update_mask_pb.paths.append("multi_cluster_routing_use_any") else: update_mask_pb.paths.append("single_cluster_routing") return self.instance_admin_client.update_app_profile( app_profile=self._to_pb(), update_mask=update_mask_pb, ignore_warnings=ignore_warnings, )
python
def update(self, ignore_warnings=None): """Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes`` """ update_mask_pb = field_mask_pb2.FieldMask() if self.description is not None: update_mask_pb.paths.append("description") if self.routing_policy_type == RoutingPolicyType.ANY: update_mask_pb.paths.append("multi_cluster_routing_use_any") else: update_mask_pb.paths.append("single_cluster_routing") return self.instance_admin_client.update_app_profile( app_profile=self._to_pb(), update_mask=update_mask_pb, ignore_warnings=ignore_warnings, )
[ "def", "update", "(", "self", ",", "ignore_warnings", "=", "None", ")", ":", "update_mask_pb", "=", "field_mask_pb2", ".", "FieldMask", "(", ")", "if", "self", ".", "description", "is", "not", "None", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"description\"", ")", "if", "self", ".", "routing_policy_type", "==", "RoutingPolicyType", ".", "ANY", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"multi_cluster_routing_use_any\"", ")", "else", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"single_cluster_routing\"", ")", "return", "self", ".", "instance_admin_client", ".", "update_app_profile", "(", "app_profile", "=", "self", ".", "_to_pb", "(", ")", ",", "update_mask", "=", "update_mask_pb", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")" ]
Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ``cluster_id`` ``allow_transactional_writes``
[ "Update", "this", "app_profile", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/app_profile.py#L285-L311
28,415
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.sink_path
def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
python
def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
[ "def", "sink_path", "(", "cls", ",", "project", ",", "sink", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/sinks/{sink}\"", ",", "project", "=", "project", ",", "sink", "=", "sink", ")" ]
Return a fully-qualified sink string.
[ "Return", "a", "fully", "-", "qualified", "sink", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L88-L92
28,416
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.exclusion_path
def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string.""" return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, )
python
def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string.""" return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, )
[ "def", "exclusion_path", "(", "cls", ",", "project", ",", "exclusion", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/exclusions/{exclusion}\"", ",", "project", "=", "project", ",", "exclusion", "=", "exclusion", ",", ")" ]
Return a fully-qualified exclusion string.
[ "Return", "a", "fully", "-", "qualified", "exclusion", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L95-L101
28,417
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.create_sink
def create_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogSink` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_sink" not in self._inner_api_calls: self._inner_api_calls[ "create_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_sink, default_retry=self._method_configs["CreateSink"].retry, default_timeout=self._method_configs["CreateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateSinkRequest( parent=parent, sink=sink, unique_writer_identity=unique_writer_identity ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogSink` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_sink" not in self._inner_api_calls: self._inner_api_calls[ "create_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_sink, default_retry=self._method_configs["CreateSink"].retry, default_timeout=self._method_configs["CreateSink"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateSinkRequest( parent=parent, sink=sink, unique_writer_identity=unique_writer_identity ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_sink"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_sink", "(", "self", ",", "parent", ",", "sink", ",", "unique_writer_identity", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_sink\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_sink\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_sink", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateSink\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateSink\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_config_pb2", ".", "CreateSinkRequest", "(", "parent", "=", "parent", ",", "sink", "=", "sink", ",", "unique_writer_identity", "=", "unique_writer_identity", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_sink\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `sink`: >>> sink = {} >>> >>> response = client.create_sink(parent, sink) Args: parent (str): Required. The resource in which to create the sink: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. sink (Union[dict, ~google.cloud.logging_v2.types.LogSink]): Required. The new sink, whose ``name`` parameter is a sink identifier that is not already in use. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogSink` unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity`` in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as ``writer_identity`` is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself. If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of ``writer_identity`` will be a unique service account used only for exports from the new sink. For more information, see ``writer_identity`` in ``LogSink``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogSink` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "sink", "that", "exports", "specified", "log", "entries", "to", "a", "destination", ".", "The", "export", "of", "newly", "-", "ingested", "log", "entries", "begins", "immediately", "unless", "the", "sink", "s", "writer_identity", "is", "not", "permitted", "to", "write", "to", "the", "destination", ".", "A", "sink", "can", "export", "log", "entries", "only", "from", "the", "resource", "owning", "the", "sink", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L390-L493
28,418
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
ConfigServiceV2Client.create_exclusion
def create_exclusion( self, parent, exclusion, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogExclusion` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_exclusion" not in self._inner_api_calls: self._inner_api_calls[ "create_exclusion" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_exclusion, default_retry=self._method_configs["CreateExclusion"].retry, default_timeout=self._method_configs["CreateExclusion"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateExclusionRequest( parent=parent, exclusion=exclusion ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_exclusion"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_exclusion( self, parent, exclusion, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogExclusion` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_exclusion" not in self._inner_api_calls: self._inner_api_calls[ "create_exclusion" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_exclusion, default_retry=self._method_configs["CreateExclusion"].retry, default_timeout=self._method_configs["CreateExclusion"].timeout, client_info=self._client_info, ) request = logging_config_pb2.CreateExclusionRequest( parent=parent, exclusion=exclusion ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_exclusion"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_exclusion", "(", "self", ",", "parent", ",", "exclusion", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_exclusion\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_exclusion\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_exclusion", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateExclusion\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateExclusion\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "logging_config_pb2", ".", "CreateExclusionRequest", "(", "parent", "=", "parent", ",", "exclusion", "=", "exclusion", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_exclusion\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. Example: >>> from google.cloud import logging_v2 >>> >>> client = logging_v2.ConfigServiceV2Client() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `exclusion`: >>> exclusion = {} >>> >>> response = client.create_exclusion(parent, exclusion) Args: parent (str): Required. The parent resource in which to create the exclusion: :: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: ``"projects/my-logging-project"``, ``"organizations/123456789"``. exclusion (Union[dict, ~google.cloud.logging_v2.types.LogExclusion]): Required. The new exclusion, whose ``name`` parameter is an exclusion name that is not already used in the parent resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.logging_v2.types.LogExclusion` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.logging_v2.types.LogExclusion` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "new", "exclusion", "in", "a", "specified", "parent", "resource", ".", "Only", "log", "entries", "belonging", "to", "that", "resource", "can", "be", "excluded", ".", "You", "can", "have", "up", "to", "10", "exclusions", "in", "a", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L886-L976
28,419
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/_helpers.py
_parse_value_pb
def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed """ if value_pb.HasField("null_value"): return None if field_type.code == type_pb2.STRING: result = value_pb.string_value elif field_type.code == type_pb2.BYTES: result = value_pb.string_value.encode("utf8") elif field_type.code == type_pb2.BOOL: result = value_pb.bool_value elif field_type.code == type_pb2.INT64: result = int(value_pb.string_value) elif field_type.code == type_pb2.FLOAT64: if value_pb.HasField("string_value"): result = float(value_pb.string_value) else: result = value_pb.number_value elif field_type.code == type_pb2.DATE: result = _date_from_iso8601_date(value_pb.string_value) elif field_type.code == type_pb2.TIMESTAMP: DatetimeWithNanoseconds = datetime_helpers.DatetimeWithNanoseconds result = DatetimeWithNanoseconds.from_rfc3339(value_pb.string_value) elif field_type.code == type_pb2.ARRAY: result = [ _parse_value_pb(item_pb, field_type.array_element_type) for item_pb in value_pb.list_value.values ] elif field_type.code == type_pb2.STRUCT: result = [ _parse_value_pb(item_pb, field_type.struct_type.fields[i].type) for (i, item_pb) in enumerate(value_pb.list_value.values) ] else: raise ValueError("Unknown type: %s" % (field_type,)) return result
python
def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed """ if value_pb.HasField("null_value"): return None if field_type.code == type_pb2.STRING: result = value_pb.string_value elif field_type.code == type_pb2.BYTES: result = value_pb.string_value.encode("utf8") elif field_type.code == type_pb2.BOOL: result = value_pb.bool_value elif field_type.code == type_pb2.INT64: result = int(value_pb.string_value) elif field_type.code == type_pb2.FLOAT64: if value_pb.HasField("string_value"): result = float(value_pb.string_value) else: result = value_pb.number_value elif field_type.code == type_pb2.DATE: result = _date_from_iso8601_date(value_pb.string_value) elif field_type.code == type_pb2.TIMESTAMP: DatetimeWithNanoseconds = datetime_helpers.DatetimeWithNanoseconds result = DatetimeWithNanoseconds.from_rfc3339(value_pb.string_value) elif field_type.code == type_pb2.ARRAY: result = [ _parse_value_pb(item_pb, field_type.array_element_type) for item_pb in value_pb.list_value.values ] elif field_type.code == type_pb2.STRUCT: result = [ _parse_value_pb(item_pb, field_type.struct_type.fields[i].type) for (i, item_pb) in enumerate(value_pb.list_value.values) ] else: raise ValueError("Unknown type: %s" % (field_type,)) return result
[ "def", "_parse_value_pb", "(", "value_pb", ",", "field_type", ")", ":", "if", "value_pb", ".", "HasField", "(", "\"null_value\"", ")", ":", "return", "None", "if", "field_type", ".", "code", "==", "type_pb2", ".", "STRING", ":", "result", "=", "value_pb", ".", "string_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "BYTES", ":", "result", "=", "value_pb", ".", "string_value", ".", "encode", "(", "\"utf8\"", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "BOOL", ":", "result", "=", "value_pb", ".", "bool_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "INT64", ":", "result", "=", "int", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "FLOAT64", ":", "if", "value_pb", ".", "HasField", "(", "\"string_value\"", ")", ":", "result", "=", "float", "(", "value_pb", ".", "string_value", ")", "else", ":", "result", "=", "value_pb", ".", "number_value", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "DATE", ":", "result", "=", "_date_from_iso8601_date", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "TIMESTAMP", ":", "DatetimeWithNanoseconds", "=", "datetime_helpers", ".", "DatetimeWithNanoseconds", "result", "=", "DatetimeWithNanoseconds", ".", "from_rfc3339", "(", "value_pb", ".", "string_value", ")", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "ARRAY", ":", "result", "=", "[", "_parse_value_pb", "(", "item_pb", ",", "field_type", ".", "array_element_type", ")", "for", "item_pb", "in", "value_pb", ".", "list_value", ".", "values", "]", "elif", "field_type", ".", "code", "==", "type_pb2", ".", "STRUCT", ":", "result", "=", "[", "_parse_value_pb", "(", "item_pb", ",", "field_type", ".", "struct_type", ".", "fields", "[", "i", "]", ".", "type", ")", "for", "(", "i", ",", "item_pb", ")", "in", "enumerate", "(", "value_pb", ".", "list_value", ".", "values", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown type: %s\"", "%", "(", "field_type", ",", ")", ")", "return", "result" ]
Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type :returns: value extracted from value_pb :raises ValueError: if unknown type is passed
[ "Convert", "a", "Value", "protobuf", "to", "cell", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/_helpers.py#L122-L167
28,420
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/_helpers.py
_parse_list_value_pbs
def _parse_list_value_pbs(rows, row_type): """Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types """ result = [] for row in rows: row_data = [] for value_pb, field in zip(row.values, row_type.fields): row_data.append(_parse_value_pb(value_pb, field.type)) result.append(row_data) return result
python
def _parse_list_value_pbs(rows, row_type): """Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types """ result = [] for row in rows: row_data = [] for value_pb, field in zip(row.values, row_type.fields): row_data.append(_parse_value_pb(value_pb, field.type)) result.append(row_data) return result
[ "def", "_parse_list_value_pbs", "(", "rows", ",", "row_type", ")", ":", "result", "=", "[", "]", "for", "row", "in", "rows", ":", "row_data", "=", "[", "]", "for", "value_pb", ",", "field", "in", "zip", "(", "row", ".", "values", ",", "row_type", ".", "fields", ")", ":", "row_data", ".", "append", "(", "_parse_value_pb", "(", "value_pb", ",", "field", ".", "type", ")", ")", "result", ".", "append", "(", "row_data", ")", "return", "result" ]
Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data :returns: data for the rows, coerced into appropriate types
[ "Convert", "a", "list", "of", "ListValue", "protobufs", "into", "a", "list", "of", "list", "of", "cell", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/_helpers.py#L173-L191
28,421
googleapis/google-cloud-python
asset/google/cloud/asset_v1/gapic/asset_service_client.py
AssetServiceClient.export_assets
def export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "export_assets" not in self._inner_api_calls: self._inner_api_calls[ "export_assets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_assets, default_retry=self._method_configs["ExportAssets"].retry, default_timeout=self._method_configs["ExportAssets"].timeout, client_info=self._client_info, ) request = asset_service_pb2.ExportAssetsRequest( parent=parent, output_config=output_config, read_time=read_time, asset_types=asset_types, content_type=content_type, ) operation = self._inner_api_calls["export_assets"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, asset_service_pb2.ExportAssetsResponse, metadata_type=asset_service_pb2.ExportAssetsRequest, )
python
def export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "export_assets" not in self._inner_api_calls: self._inner_api_calls[ "export_assets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_assets, default_retry=self._method_configs["ExportAssets"].retry, default_timeout=self._method_configs["ExportAssets"].timeout, client_info=self._client_info, ) request = asset_service_pb2.ExportAssetsRequest( parent=parent, output_config=output_config, read_time=read_time, asset_types=asset_types, content_type=content_type, ) operation = self._inner_api_calls["export_assets"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, asset_service_pb2.ExportAssetsResponse, metadata_type=asset_service_pb2.ExportAssetsRequest, )
[ "def", "export_assets", "(", "self", ",", "parent", ",", "output_config", ",", "read_time", "=", "None", ",", "asset_types", "=", "None", ",", "content_type", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"export_assets\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"export_assets\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "export_assets", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ExportAssets\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ExportAssets\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "asset_service_pb2", ".", "ExportAssetsRequest", "(", "parent", "=", "parent", ",", "output_config", "=", "output_config", ",", "read_time", "=", "read_time", ",", "asset_types", "=", "asset_types", ",", "content_type", "=", "content_type", ",", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"export_assets\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "asset_service_pb2", ".", "ExportAssetsResponse", ",", "metadata_type", "=", "asset_service_pb2", ".", "ExportAssetsRequest", ",", ")" ]
Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the ``google.longrunning.Operation`` API allowing you to keep track of the export. Example: >>> from google.cloud import asset_v1 >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_assets(parent, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.OutputConfig` read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.Timestamp` asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See `Introduction to Cloud Asset Inventory <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview>`__ for all supported asset types. content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be returned. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Exports", "assets", "with", "time", "and", "resource", "types", "to", "a", "given", "Cloud", "Storage", "location", ".", "The", "output", "format", "is", "newline", "-", "delimited", "JSON", ".", "This", "API", "implements", "the", "google", ".", "longrunning", ".", "Operation", "API", "allowing", "you", "to", "keep", "track", "of", "the", "export", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/asset/google/cloud/asset_v1/gapic/asset_service_client.py#L179-L288
28,422
googleapis/google-cloud-python
asset/google/cloud/asset_v1/gapic/asset_service_client.py
AssetServiceClient.batch_get_assets_history
def batch_get_assets_history( self, parent, content_type, read_time_window, asset_names=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_assets_history" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_assets_history" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_assets_history, default_retry=self._method_configs["BatchGetAssetsHistory"].retry, default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, client_info=self._client_info, ) request = asset_service_pb2.BatchGetAssetsHistoryRequest( parent=parent, content_type=content_type, read_time_window=read_time_window, asset_names=asset_names, ) return self._inner_api_calls["batch_get_assets_history"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def batch_get_assets_history( self, parent, content_type, read_time_window, asset_names=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_get_assets_history" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_assets_history" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_assets_history, default_retry=self._method_configs["BatchGetAssetsHistory"].retry, default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, client_info=self._client_info, ) request = asset_service_pb2.BatchGetAssetsHistoryRequest( parent=parent, content_type=content_type, read_time_window=read_time_window, asset_names=asset_names, ) return self._inner_api_calls["batch_get_assets_history"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "batch_get_assets_history", "(", "self", ",", "parent", ",", "content_type", ",", "read_time_window", ",", "asset_names", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"batch_get_assets_history\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"batch_get_assets_history\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "batch_get_assets_history", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BatchGetAssetsHistory\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BatchGetAssetsHistory\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "asset_service_pb2", ".", "BatchGetAssetsHistoryRequest", "(", "parent", "=", "parent", ",", "content_type", "=", "content_type", ",", "read_time_window", "=", "read_time_window", ",", "asset_names", "=", "asset_names", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"batch_get_assets_history\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM\_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID\_ARGUMENT error. Example: >>> from google.cloud import asset_v1 >>> from google.cloud.asset_v1 import enums >>> >>> client = asset_v1.AssetServiceClient() >>> >>> # TODO: Initialize `parent`: >>> parent = '' >>> >>> # TODO: Initialize `content_type`: >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `read_time_window`: >>> read_time_window = {} >>> >>> response = client.batch_get_assets_history(parent, content_type, read_time_window) Args: parent (str): Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type. read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\_time and end\_time are optional and if set, it must be after 2018-10-02 UTC. If end\_time is not set, it is default to current timestamp. If start\_time is not set, the snapshot of the assets at end\_time will be returned. The returned results contain all temporal assets whose time window overlap with read\_time\_window. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.asset_v1.types.TimeWindow` asset_names (list[str]): A list of the full names of the assets. For example: ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. See `Resource Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__ and `Resource Name Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__ for more info. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Batch", "gets", "the", "update", "history", "of", "assets", "that", "overlap", "a", "time", "window", ".", "For", "RESOURCE", "content", "this", "API", "outputs", "history", "with", "asset", "in", "both", "non", "-", "delete", "or", "deleted", "status", ".", "For", "IAM", "\\", "_POLICY", "content", "this", "API", "outputs", "history", "when", "the", "asset", "and", "its", "attached", "IAM", "POLICY", "both", "exist", ".", "This", "can", "create", "gaps", "in", "the", "output", "history", ".", "If", "a", "specified", "asset", "does", "not", "exist", "this", "API", "returns", "an", "INVALID", "\\", "_ARGUMENT", "error", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/asset/google/cloud/asset_v1/gapic/asset_service_client.py#L290-L387
28,423
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_avro_schema
def _avro_schema(read_session): """Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session. """ json_schema = json.loads(read_session.avro_schema.schema) column_names = tuple((field["name"] for field in json_schema["fields"])) return fastavro.parse_schema(json_schema), column_names
python
def _avro_schema(read_session): """Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session. """ json_schema = json.loads(read_session.avro_schema.schema) column_names = tuple((field["name"] for field in json_schema["fields"])) return fastavro.parse_schema(json_schema), column_names
[ "def", "_avro_schema", "(", "read_session", ")", ":", "json_schema", "=", "json", ".", "loads", "(", "read_session", ".", "avro_schema", ".", "schema", ")", "column_names", "=", "tuple", "(", "(", "field", "[", "\"name\"", "]", "for", "field", "in", "json_schema", "[", "\"fields\"", "]", ")", ")", "return", "fastavro", ".", "parse_schema", "(", "json_schema", ")", ",", "column_names" ]
Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ ): The read session associated with this read rows stream. This contains the schema, which is required to parse the data blocks. Returns: Tuple[fastavro.schema, Tuple[str]]: A parsed Avro schema, using :func:`fastavro.schema.parse_schema` and the column names for a read session.
[ "Extract", "and", "parse", "Avro", "schema", "from", "a", "read", "session", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L375-L393
28,424
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_avro_rows
def _avro_rows(block, avro_schema): """Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries. """ blockio = six.BytesIO(block.avro_rows.serialized_binary_rows) while True: # Loop in a while loop because schemaless_reader can only read # a single record. try: # TODO: Parse DATETIME into datetime.datetime (no timezone), # instead of as a string. yield fastavro.schemaless_reader(blockio, avro_schema) except StopIteration: break
python
def _avro_rows(block, avro_schema): """Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries. """ blockio = six.BytesIO(block.avro_rows.serialized_binary_rows) while True: # Loop in a while loop because schemaless_reader can only read # a single record. try: # TODO: Parse DATETIME into datetime.datetime (no timezone), # instead of as a string. yield fastavro.schemaless_reader(blockio, avro_schema) except StopIteration: break
[ "def", "_avro_rows", "(", "block", ",", "avro_schema", ")", ":", "blockio", "=", "six", ".", "BytesIO", "(", "block", ".", "avro_rows", ".", "serialized_binary_rows", ")", "while", "True", ":", "# Loop in a while loop because schemaless_reader can only read", "# a single record.", "try", ":", "# TODO: Parse DATETIME into datetime.datetime (no timezone),", "# instead of as a string.", "yield", "fastavro", ".", "schemaless_reader", "(", "blockio", ",", "avro_schema", ")", "except", "StopIteration", ":", "break" ]
Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A block containing Avro bytes to parse into rows. avro_schema (fastavro.schema): A parsed Avro schema, used to deserialized the bytes in the block. Returns: Iterable[Mapping]: A sequence of rows, represented as dictionaries.
[ "Parse", "all", "rows", "in", "a", "stream", "block", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L396-L421
28,425
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
_copy_stream_position
def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion. """ if isinstance(position, types.StreamPosition): output = types.StreamPosition() output.CopyFrom(position) return output return types.StreamPosition(**position)
python
def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion. """ if isinstance(position, types.StreamPosition): output = types.StreamPosition() output.CopyFrom(position) return output return types.StreamPosition(**position)
[ "def", "_copy_stream_position", "(", "position", ")", ":", "if", "isinstance", "(", "position", ",", "types", ".", "StreamPosition", ")", ":", "output", "=", "types", ".", "StreamPosition", "(", ")", "output", ".", "CopyFrom", "(", "position", ")", "return", "output", "return", "types", ".", "StreamPosition", "(", "*", "*", "position", ")" ]
Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition: A copy of the input StreamPostion.
[ "Copy", "a", "StreamPosition", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L424-L443
28,426
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsStream._reconnect
def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset.""" self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_kwargs )
python
def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset.""" self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_kwargs )
[ "def", "_reconnect", "(", "self", ")", ":", "self", ".", "_wrapped", "=", "self", ".", "_client", ".", "read_rows", "(", "_copy_stream_position", "(", "self", ".", "_position", ")", ",", "*", "*", "self", ".", "_read_rows_kwargs", ")" ]
Reconnect to the ReadRows stream using the most recent offset.
[ "Reconnect", "to", "the", "ReadRows", "stream", "using", "the", "most", "recent", "offset", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L128-L132
28,427
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsIterable.pages
def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. """ # Each page is an iterator of rows. But also has num_items, remaining, # and to_dataframe. avro_schema, column_names = _avro_schema(self._read_session) for block in self._reader: self._status = block.status yield ReadRowsPage(avro_schema, column_names, block)
python
def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. """ # Each page is an iterator of rows. But also has num_items, remaining, # and to_dataframe. avro_schema, column_names = _avro_schema(self._read_session) for block in self._reader: self._status = block.status yield ReadRowsPage(avro_schema, column_names, block)
[ "def", "pages", "(", "self", ")", ":", "# Each page is an iterator of rows. But also has num_items, remaining,", "# and to_dataframe.", "avro_schema", ",", "column_names", "=", "_avro_schema", "(", "self", ".", "_read_session", ")", "for", "block", "in", "self", ".", "_reader", ":", "self", ".", "_status", "=", "block", ".", "status", "yield", "ReadRowsPage", "(", "avro_schema", ",", "column_names", ",", "block", ")" ]
A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages.
[ "A", "generator", "of", "all", "pages", "in", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L226-L238
28,428
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsPage._parse_block
def _parse_block(self): """Parse metadata and rows from the block only once.""" if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count self._remaining = self._block.avro_rows.row_count self._iter_rows = iter(rows)
python
def _parse_block(self): """Parse metadata and rows from the block only once.""" if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count self._remaining = self._block.avro_rows.row_count self._iter_rows = iter(rows)
[ "def", "_parse_block", "(", "self", ")", ":", "if", "self", ".", "_iter_rows", "is", "not", "None", ":", "return", "rows", "=", "_avro_rows", "(", "self", ".", "_block", ",", "self", ".", "_avro_schema", ")", "self", ".", "_num_items", "=", "self", ".", "_block", ".", "avro_rows", ".", "row_count", "self", ".", "_remaining", "=", "self", ".", "_block", ".", "avro_rows", ".", "row_count", "self", ".", "_iter_rows", "=", "iter", "(", "rows", ")" ]
Parse metadata and rows from the block only once.
[ "Parse", "metadata", "and", "rows", "from", "the", "block", "only", "once", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L301-L309
28,429
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py
ReadRowsPage.next
def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
python
def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
[ "def", "next", "(", "self", ")", ":", "self", ".", "_parse_block", "(", ")", "if", "self", ".", "_remaining", ">", "0", ":", "self", ".", "_remaining", "-=", "1", "return", "six", ".", "next", "(", "self", ".", "_iter_rows", ")" ]
Get the next row in the page.
[ "Get", "the", "next", "row", "in", "the", "page", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L327-L332
28,430
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.instance_config_path
def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
python
def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
[ "def", "instance_config_path", "(", "cls", ",", "project", ",", "instance_config", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instanceConfigs/{instance_config}\"", ",", "project", "=", "project", ",", "instance_config", "=", "instance_config", ",", ")" ]
Return a fully-qualified instance_config string.
[ "Return", "a", "fully", "-", "qualified", "instance_config", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L110-L116
28,431
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.create_instance
def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, )
python
def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, )
[ "def", "create_instance", "(", "self", ",", "parent", ",", "instance_id", ",", "instance", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_instance\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_instance\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_instance", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateInstance\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateInstance\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_instance_admin_pb2", ".", "CreateInstanceRequest", "(", "parent", "=", "parent", ",", "instance_id", "=", "instance_id", ",", "instance", "=", "instance", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"create_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "spanner_instance_admin_pb2", ".", "Instance", ",", "metadata_type", "=", "spanner_instance_admin_pb2", ".", "CreateInstanceMetadata", ",", ")" ]
Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "an", "instance", "and", "begins", "preparing", "it", "to", "begin", "serving", ".", "The", "returned", "long", "-", "running", "operation", "can", "be", "used", "to", "track", "the", "progress", "of", "preparing", "the", "new", "instance", ".", "The", "instance", "name", "is", "assigned", "by", "the", "caller", ".", "If", "the", "named", "instance", "already", "exists", "CreateInstance", "returns", "ALREADY_EXISTS", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L594-L725
28,432
googleapis/google-cloud-python
spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py
InstanceAdminClient.update_instance
def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, )
python
def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, )
[ "def", "update_instance", "(", "self", ",", "instance", ",", "field_mask", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"update_instance\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_instance\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_instance", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateInstance\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateInstance\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "spanner_instance_admin_pb2", ".", "UpdateInstanceRequest", "(", "instance", "=", "instance", ",", "field_mask", "=", "field_mask", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"instance.name\"", ",", "instance", ".", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"update_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "spanner_instance_admin_pb2", ".", "Instance", ",", "metadata_type", "=", "spanner_instance_admin_pb2", ".", "UpdateInstanceMetadata", ",", ")" ]
Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask] need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. The field mask must always be specified; this prevents any future fields in [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "an", "instance", "and", "begins", "allocating", "or", "releasing", "resources", "as", "requested", ".", "The", "returned", "long", "-", "running", "operation", "can", "be", "used", "to", "track", "the", "progress", "of", "updating", "the", "instance", ".", "If", "the", "named", "instance", "does", "not", "exist", "returns", "NOT_FOUND", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py#L727-L866
28,433
googleapis/google-cloud-python
websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py
WebSecurityScannerClient.scan_config_path
def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=scan_config, )
python
def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=scan_config, )
[ "def", "scan_config_path", "(", "cls", ",", "project", ",", "scan_config", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/scanConfigs/{scan_config}\"", ",", "project", "=", "project", ",", "scan_config", "=", "scan_config", ",", ")" ]
Return a fully-qualified scan_config string.
[ "Return", "a", "fully", "-", "qualified", "scan_config", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L105-L111
28,434
googleapis/google-cloud-python
websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py
WebSecurityScannerClient.scan_run_path
def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, scan_config=scan_config, scan_run=scan_run, )
python
def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string.""" return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, scan_config=scan_config, scan_run=scan_run, )
[ "def", "scan_run_path", "(", "cls", ",", "project", ",", "scan_config", ",", "scan_run", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}\"", ",", "project", "=", "project", ",", "scan_config", "=", "scan_config", ",", "scan_run", "=", "scan_run", ",", ")" ]
Return a fully-qualified scan_run string.
[ "Return", "a", "fully", "-", "qualified", "scan_run", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L114-L121
28,435
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.copy
def copy(self): """Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client. """ return self.__class__( project=self.project, credentials=self._credentials, user_agent=self.user_agent, )
python
def copy(self): """Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client. """ return self.__class__( project=self.project, credentials=self._credentials, user_agent=self.user_agent, )
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "project", "=", "self", ".", "project", ",", "credentials", "=", "self", ".", "_credentials", ",", "user_agent", "=", "self", ".", "user_agent", ",", ")" ]
Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client.
[ "Make", "a", "copy", "of", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L169-L182
28,436
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.list_instance_configs
def list_instance_configs(self, page_size=None, page_token=None): """List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ instance.v1.InstanceAdmin.ListInstanceConfigs See `RPC docs`_. :type page_size: int :param page_size: Optional. The maximum number of configs in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of configs, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.InstanceConfig` resources within the client's project. """ metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instance_configs( path, page_size=page_size, metadata=metadata ) page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_instance_config return page_iter
python
def list_instance_configs(self, page_size=None, page_token=None): """List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ instance.v1.InstanceAdmin.ListInstanceConfigs See `RPC docs`_. :type page_size: int :param page_size: Optional. The maximum number of configs in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of configs, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.InstanceConfig` resources within the client's project. """ metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instance_configs( path, page_size=page_size, metadata=metadata ) page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_instance_config return page_iter
[ "def", "list_instance_configs", "(", "self", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "metadata", "=", "_metadata_with_prefix", "(", "self", ".", "project_name", ")", "path", "=", "\"projects/%s\"", "%", "(", "self", ".", "project", ",", ")", "page_iter", "=", "self", ".", "instance_admin_api", ".", "list_instance_configs", "(", "path", ",", "page_size", "=", "page_size", ",", "metadata", "=", "metadata", ")", "page_iter", ".", "next_page_token", "=", "page_token", "page_iter", ".", "item_to_value", "=", "_item_to_instance_config", "return", "page_iter" ]
List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ instance.v1.InstanceAdmin.ListInstanceConfigs See `RPC docs`_. :type page_size: int :param page_size: Optional. The maximum number of configs in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of configs, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.InstanceConfig` resources within the client's project.
[ "List", "available", "instance", "configurations", "for", "the", "client", "s", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L184-L220
28,437
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.list_instances
def list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string :param filter_: (Optional) Filter to select instances listed. See the ``ListInstancesRequest`` docs above for examples. :type page_size: int :param page_size: Optional. The maximum number of instances in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of instances, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.Instance` resources within the client's project. """ metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instances( path, page_size=page_size, metadata=metadata ) page_iter.item_to_value = self._item_to_instance page_iter.next_page_token = page_token return page_iter
python
def list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string :param filter_: (Optional) Filter to select instances listed. See the ``ListInstancesRequest`` docs above for examples. :type page_size: int :param page_size: Optional. The maximum number of instances in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of instances, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.Instance` resources within the client's project. """ metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instances( path, page_size=page_size, metadata=metadata ) page_iter.item_to_value = self._item_to_instance page_iter.next_page_token = page_token return page_iter
[ "def", "list_instances", "(", "self", ",", "filter_", "=", "\"\"", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "metadata", "=", "_metadata_with_prefix", "(", "self", ".", "project_name", ")", "path", "=", "\"projects/%s\"", "%", "(", "self", ".", "project", ",", ")", "page_iter", "=", "self", ".", "instance_admin_api", ".", "list_instances", "(", "path", ",", "page_size", "=", "page_size", ",", "metadata", "=", "metadata", ")", "page_iter", ".", "item_to_value", "=", "self", ".", "_item_to_instance", "page_iter", ".", "next_page_token", "=", "page_token", "return", "page_iter" ]
List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string :param filter_: (Optional) Filter to select instances listed. See the ``ListInstancesRequest`` docs above for examples. :type page_size: int :param page_size: Optional. The maximum number of instances in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type page_token: str :param page_token: Optional. If present, return the next batch of instances, using the value, which must correspond to the ``nextPageToken`` value returned in the previous response. Deprecated: use the ``pages`` property of the returned iterator instead of manually passing the token. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.spanner_v1.instance.Instance` resources within the client's project.
[ "List", "instances", "for", "the", "client", "s", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L256-L292
28,438
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/retry.py
_should_retry
def _should_retry(exc): """Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'. """ if not hasattr(exc, "errors"): return False if len(exc.errors) == 0: # Check for unstructured error returns, e.g. from GFE return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES) reason = exc.errors[0]["reason"] return reason in _RETRYABLE_REASONS
python
def _should_retry(exc): """Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'. """ if not hasattr(exc, "errors"): return False if len(exc.errors) == 0: # Check for unstructured error returns, e.g. from GFE return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES) reason = exc.errors[0]["reason"] return reason in _RETRYABLE_REASONS
[ "def", "_should_retry", "(", "exc", ")", ":", "if", "not", "hasattr", "(", "exc", ",", "\"errors\"", ")", ":", "return", "False", "if", "len", "(", "exc", ".", "errors", ")", "==", "0", ":", "# Check for unstructured error returns, e.g. from GFE", "return", "isinstance", "(", "exc", ",", "_UNSTRUCTURED_RETRYABLE_TYPES", ")", "reason", "=", "exc", ".", "errors", "[", "0", "]", "[", "\"reason\"", "]", "return", "reason", "in", "_RETRYABLE_REASONS" ]
Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'.
[ "Predicate", "for", "determining", "when", "to", "retry", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/retry.py#L30-L44
28,439
googleapis/google-cloud-python
logging/google/cloud/logging/_helpers.py
entry_from_resource
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The entry instance, constructed via the resource """ if "textPayload" in resource: return TextEntry.from_api_repr(resource, client, loggers) if "jsonPayload" in resource: return StructEntry.from_api_repr(resource, client, loggers) if "protoPayload" in resource: return ProtobufEntry.from_api_repr(resource, client, loggers) return LogEntry.from_api_repr(resource, client, loggers)
python
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The entry instance, constructed via the resource """ if "textPayload" in resource: return TextEntry.from_api_repr(resource, client, loggers) if "jsonPayload" in resource: return StructEntry.from_api_repr(resource, client, loggers) if "protoPayload" in resource: return ProtobufEntry.from_api_repr(resource, client, loggers) return LogEntry.from_api_repr(resource, client, loggers)
[ "def", "entry_from_resource", "(", "resource", ",", "client", ",", "loggers", ")", ":", "if", "\"textPayload\"", "in", "resource", ":", "return", "TextEntry", ".", "from_api_repr", "(", "resource", ",", "client", ",", "loggers", ")", "if", "\"jsonPayload\"", "in", "resource", ":", "return", "StructEntry", ".", "from_api_repr", "(", "resource", ",", "client", ",", "loggers", ")", "if", "\"protoPayload\"", "in", "resource", ":", "return", "ProtobufEntry", ".", "from_api_repr", "(", "resource", ",", "client", ",", "loggers", ")", "return", "LogEntry", ".", "from_api_repr", "(", "resource", ",", "client", ",", "loggers", ")" ]
Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The entry instance, constructed via the resource
[ "Detect", "correct", "entry", "type", "from", "resource", "and", "instantiate", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_helpers.py#L28-L55
28,440
googleapis/google-cloud-python
logging/google/cloud/logging/_helpers.py
retrieve_metadata_server
def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply query parameters after the metadata key. e.g. "tags?alt=json" :rtype: str :returns: The value of the metadata key returned by the metadata server. """ url = METADATA_URL + metadata_key try: response = requests.get(url, headers=METADATA_HEADERS) if response.status_code == requests.codes.ok: return response.text except requests.exceptions.RequestException: # Ignore the exception, connection failed means the attribute does not # exist in the metadata server. pass return None
python
def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply query parameters after the metadata key. e.g. "tags?alt=json" :rtype: str :returns: The value of the metadata key returned by the metadata server. """ url = METADATA_URL + metadata_key try: response = requests.get(url, headers=METADATA_HEADERS) if response.status_code == requests.codes.ok: return response.text except requests.exceptions.RequestException: # Ignore the exception, connection failed means the attribute does not # exist in the metadata server. pass return None
[ "def", "retrieve_metadata_server", "(", "metadata_key", ")", ":", "url", "=", "METADATA_URL", "+", "metadata_key", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "METADATA_HEADERS", ")", "if", "response", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "return", "response", ".", "text", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "# Ignore the exception, connection failed means the attribute does not", "# exist in the metadata server.", "pass", "return", "None" ]
Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply query parameters after the metadata key. e.g. "tags?alt=json" :rtype: str :returns: The value of the metadata key returned by the metadata server.
[ "Retrieve", "the", "metadata", "key", "in", "the", "metadata", "server", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_helpers.py#L58-L84
28,441
tensorflow/cleverhans
cleverhans/utils_tf.py
batch_eval
def batch_eval(*args, **kwargs): """ Wrapper around deprecated function. """ # Inside function to avoid circular import from cleverhans.evaluation import batch_eval as new_batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on or after " "2019-03-09.") return new_batch_eval(*args, **kwargs)
python
def batch_eval(*args, **kwargs): """ Wrapper around deprecated function. """ # Inside function to avoid circular import from cleverhans.evaluation import batch_eval as new_batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on or after " "2019-03-09.") return new_batch_eval(*args, **kwargs)
[ "def", "batch_eval", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Inside function to avoid circular import", "from", "cleverhans", ".", "evaluation", "import", "batch_eval", "as", "new_batch_eval", "warnings", ".", "warn", "(", "\"batch_eval has moved to cleverhans.evaluation. \"", "\"batch_eval will be removed from utils_tf on or after \"", "\"2019-03-09.\"", ")", "return", "new_batch_eval", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Wrapper around deprecated function.
[ "Wrapper", "around", "deprecated", "function", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L292-L301
28,442
tensorflow/cleverhans
cleverhans/utils_tf.py
get_available_gpus
def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
python
def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
[ "def", "get_available_gpus", "(", ")", ":", "local_device_protos", "=", "device_lib", ".", "list_local_devices", "(", ")", "return", "[", "x", ".", "name", "for", "x", "in", "local_device_protos", "if", "x", ".", "device_type", "==", "'GPU'", "]" ]
Returns a list of string names of all available GPUs
[ "Returns", "a", "list", "of", "string", "names", "of", "all", "available", "GPUs" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L526-L531
28,443
tensorflow/cleverhans
cleverhans/utils_tf.py
clip_by_value
def clip_by_value(t, clip_value_min, clip_value_max, name=None): """ A wrapper for clip_by_value that casts the clipping range if needed. """ def cast_clip(clip): """ Cast clipping range argument if needed. """ if t.dtype in (tf.float32, tf.float64): if hasattr(clip, 'dtype'): # Convert to tf dtype in case this is a numpy dtype clip_dtype = tf.as_dtype(clip.dtype) if clip_dtype != t.dtype: return tf.cast(clip, t.dtype) return clip clip_value_min = cast_clip(clip_value_min) clip_value_max = cast_clip(clip_value_max) return tf.clip_by_value(t, clip_value_min, clip_value_max, name)
python
def clip_by_value(t, clip_value_min, clip_value_max, name=None): """ A wrapper for clip_by_value that casts the clipping range if needed. """ def cast_clip(clip): """ Cast clipping range argument if needed. """ if t.dtype in (tf.float32, tf.float64): if hasattr(clip, 'dtype'): # Convert to tf dtype in case this is a numpy dtype clip_dtype = tf.as_dtype(clip.dtype) if clip_dtype != t.dtype: return tf.cast(clip, t.dtype) return clip clip_value_min = cast_clip(clip_value_min) clip_value_max = cast_clip(clip_value_max) return tf.clip_by_value(t, clip_value_min, clip_value_max, name)
[ "def", "clip_by_value", "(", "t", ",", "clip_value_min", ",", "clip_value_max", ",", "name", "=", "None", ")", ":", "def", "cast_clip", "(", "clip", ")", ":", "\"\"\"\n Cast clipping range argument if needed.\n \"\"\"", "if", "t", ".", "dtype", "in", "(", "tf", ".", "float32", ",", "tf", ".", "float64", ")", ":", "if", "hasattr", "(", "clip", ",", "'dtype'", ")", ":", "# Convert to tf dtype in case this is a numpy dtype", "clip_dtype", "=", "tf", ".", "as_dtype", "(", "clip", ".", "dtype", ")", "if", "clip_dtype", "!=", "t", ".", "dtype", ":", "return", "tf", ".", "cast", "(", "clip", ",", "t", ".", "dtype", ")", "return", "clip", "clip_value_min", "=", "cast_clip", "(", "clip_value_min", ")", "clip_value_max", "=", "cast_clip", "(", "clip_value_max", ")", "return", "tf", ".", "clip_by_value", "(", "t", ",", "clip_value_min", ",", "clip_value_max", ",", "name", ")" ]
A wrapper for clip_by_value that casts the clipping range if needed.
[ "A", "wrapper", "for", "clip_by_value", "that", "casts", "the", "clipping", "range", "if", "needed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L540-L559
28,444
tensorflow/cleverhans
cleverhans/utils_tf.py
mul
def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """ def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
python
def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """ def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
[ "def", "mul", "(", "a", ",", "b", ")", ":", "def", "multiply", "(", "a", ",", "b", ")", ":", "\"\"\"Multiplication\"\"\"", "return", "a", "*", "b", "return", "op_with_scalar_cast", "(", "a", ",", "b", ",", "multiply", ")" ]
A wrapper around tf multiplication that does more automatic casting of the input.
[ "A", "wrapper", "around", "tf", "multiplication", "that", "does", "more", "automatic", "casting", "of", "the", "input", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L561-L569
28,445
tensorflow/cleverhans
cleverhans/utils_tf.py
div
def div(a, b): """ A wrapper around tf division that does more automatic casting of the input. """ def divide(a, b): """Division""" return a / b return op_with_scalar_cast(a, b, divide)
python
def div(a, b): """ A wrapper around tf division that does more automatic casting of the input. """ def divide(a, b): """Division""" return a / b return op_with_scalar_cast(a, b, divide)
[ "def", "div", "(", "a", ",", "b", ")", ":", "def", "divide", "(", "a", ",", "b", ")", ":", "\"\"\"Division\"\"\"", "return", "a", "/", "b", "return", "op_with_scalar_cast", "(", "a", ",", "b", ",", "divide", ")" ]
A wrapper around tf division that does more automatic casting of the input.
[ "A", "wrapper", "around", "tf", "division", "that", "does", "more", "automatic", "casting", "of", "the", "input", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L571-L579
28,446
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase._write_single_batch_images_internal
def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore.""" client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]['images']): img_entity = client.entity( client.key(self._entity_kind_images, img_id, parent=batch_key)) for k, v in iteritems(img): img_entity[k] = v client_batch.put(img_entity)
python
def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore.""" client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]['images']): img_entity = client.entity( client.key(self._entity_kind_images, img_id, parent=batch_key)) for k, v in iteritems(img): img_entity[k] = v client_batch.put(img_entity)
[ "def", "_write_single_batch_images_internal", "(", "self", ",", "batch_id", ",", "client_batch", ")", ":", "client", "=", "self", ".", "_datastore_client", "batch_key", "=", "client", ".", "key", "(", "self", ".", "_entity_kind_batches", ",", "batch_id", ")", "for", "img_id", ",", "img", "in", "iteritems", "(", "self", ".", "_data", "[", "batch_id", "]", "[", "'images'", "]", ")", ":", "img_entity", "=", "client", ".", "entity", "(", "client", ".", "key", "(", "self", ".", "_entity_kind_images", ",", "img_id", ",", "parent", "=", "batch_key", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", "img", ")", ":", "img_entity", "[", "k", "]", "=", "v", "client_batch", ".", "put", "(", "img_entity", ")" ]
Helper method to write images from single batch into datastore.
[ "Helper", "method", "to", "write", "images", "from", "single", "batch", "into", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L72-L81
28,447
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.write_to_datastore
def write_to_datastore(self): """Writes all image batches to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_id) batch_entity = client.entity(batch_key) for k, v in iteritems(batch_data): if k != 'images': batch_entity[k] = v client_batch.put(batch_entity) self._write_single_batch_images_internal(batch_id, client_batch)
python
def write_to_datastore(self): """Writes all image batches to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_id) batch_entity = client.entity(batch_key) for k, v in iteritems(batch_data): if k != 'images': batch_entity[k] = v client_batch.put(batch_entity) self._write_single_batch_images_internal(batch_id, client_batch)
[ "def", "write_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "for", "batch_id", ",", "batch_data", "in", "iteritems", "(", "self", ".", "_data", ")", ":", "batch_key", "=", "client", ".", "key", "(", "self", ".", "_entity_kind_batches", ",", "batch_id", ")", "batch_entity", "=", "client", ".", "entity", "(", "batch_key", ")", "for", "k", ",", "v", "in", "iteritems", "(", "batch_data", ")", ":", "if", "k", "!=", "'images'", ":", "batch_entity", "[", "k", "]", "=", "v", "client_batch", ".", "put", "(", "batch_entity", ")", "self", ".", "_write_single_batch_images_internal", "(", "batch_id", ",", "client_batch", ")" ]
Writes all image batches to the datastore.
[ "Writes", "all", "image", "batches", "to", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L83-L94
28,448
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.write_single_batch_images_to_datastore
def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
python
def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
[ "def", "write_single_batch_images_to_datastore", "(", "self", ",", "batch_id", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "self", ".", "_write_single_batch_images_internal", "(", "batch_id", ",", "client_batch", ")" ]
Writes only images from one batch to the datastore.
[ "Writes", "only", "images", "from", "one", "batch", "to", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L96-L100
28,449
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.init_from_datastore
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['images'] = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_images): batch_id = entity.key.flat_path[-3] image_id = entity.key.flat_path[-1] self._data[batch_id]['images'][image_id] = dict(entity)
python
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['images'] = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_images): batch_id = entity.key.flat_path[-3] image_id = entity.key.flat_path[-1] self._data[batch_id]['images'][image_id] = dict(entity)
[ "def", "init_from_datastore", "(", "self", ")", ":", "self", ".", "_data", "=", "{", "}", "for", "entity", "in", "self", ".", "_datastore_client", ".", "query_fetch", "(", "kind", "=", "self", ".", "_entity_kind_batches", ")", ":", "batch_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "self", ".", "_data", "[", "batch_id", "]", "=", "dict", "(", "entity", ")", "self", ".", "_data", "[", "batch_id", "]", "[", "'images'", "]", "=", "{", "}", "for", "entity", "in", "self", ".", "_datastore_client", ".", "query_fetch", "(", "kind", "=", "self", ".", "_entity_kind_images", ")", ":", "batch_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "3", "]", "image_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "self", ".", "_data", "[", "batch_id", "]", "[", "'images'", "]", "[", "image_id", "]", "=", "dict", "(", "entity", ")" ]
Initializes batches by reading from the datastore.
[ "Initializes", "batches", "by", "reading", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L102-L114
28,450
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.add_batch
def add_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties.""" if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError('batch_properties has to be dict, however it was: ' + str(type(batch_properties))) self._data[batch_id] = batch_properties.copy() self._data[batch_id]['images'] = {}
python
def add_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties.""" if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError('batch_properties has to be dict, however it was: ' + str(type(batch_properties))) self._data[batch_id] = batch_properties.copy() self._data[batch_id]['images'] = {}
[ "def", "add_batch", "(", "self", ",", "batch_id", ",", "batch_properties", "=", "None", ")", ":", "if", "batch_properties", "is", "None", ":", "batch_properties", "=", "{", "}", "if", "not", "isinstance", "(", "batch_properties", ",", "dict", ")", ":", "raise", "ValueError", "(", "'batch_properties has to be dict, however it was: '", "+", "str", "(", "type", "(", "batch_properties", ")", ")", ")", "self", ".", "_data", "[", "batch_id", "]", "=", "batch_properties", ".", "copy", "(", ")", "self", ".", "_data", "[", "batch_id", "]", "[", "'images'", "]", "=", "{", "}" ]
Adds batch with give ID and list of properties.
[ "Adds", "batch", "with", "give", "ID", "and", "list", "of", "properties", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L125-L133
28,451
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.add_image
def add_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch.""" if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstance(image_properties, dict): raise ValueError('image_properties has to be dict, however it was: ' + str(type(image_properties))) self._data[batch_id]['images'][image_id] = image_properties.copy()
python
def add_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch.""" if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstance(image_properties, dict): raise ValueError('image_properties has to be dict, however it was: ' + str(type(image_properties))) self._data[batch_id]['images'][image_id] = image_properties.copy()
[ "def", "add_image", "(", "self", ",", "batch_id", ",", "image_id", ",", "image_properties", "=", "None", ")", ":", "if", "batch_id", "not", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "'Batch with ID \"{0}\" does not exist'", ".", "format", "(", "batch_id", ")", ")", "if", "image_properties", "is", "None", ":", "image_properties", "=", "{", "}", "if", "not", "isinstance", "(", "image_properties", ",", "dict", ")", ":", "raise", "ValueError", "(", "'image_properties has to be dict, however it was: '", "+", "str", "(", "type", "(", "image_properties", ")", ")", ")", "self", ".", "_data", "[", "batch_id", "]", "[", "'images'", "]", "[", "image_id", "]", "=", "image_properties", ".", "copy", "(", ")" ]
Adds image to given batch.
[ "Adds", "image", "to", "given", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L135-L144
28,452
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
DatasetBatches._read_image_list
def _read_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore.""" if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join('dataset', self._dataset_name) + '/') zip_files = [i for i in images if i.endswith('.zip')] if len(zip_files) == 1: # we have a zip archive with images zip_name = zip_files[0] logging.info('Reading list of images from zip file %s', zip_name) blob = self._storage_client.get_blob(zip_name) buf = BytesIO() logging.info('Downloading zip') blob.download_to_file(buf) buf.seek(0) logging.info('Reading content of the zip') with zipfile.ZipFile(buf) as f: images = [os.path.join(zip_name, os.path.basename(n)) for n in f.namelist() if n.endswith('.png')] buf.close() logging.info('Found %d images', len(images)) else: # we have just a directory with images, filter non-PNG files logging.info('Reading list of images from png files in storage') images = [i for i in images if i.endswith('.png')] logging.info('Found %d images', len(images)) # filter images which should be skipped images = [i for i in images if os.path.basename(i)[:-4] not in skip_image_ids] # assign IDs to images images = [(DATASET_IMAGE_ID_PATTERN.format(idx), i) for idx, i in enumerate(sorted(images))] return images
python
def _read_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore.""" if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join('dataset', self._dataset_name) + '/') zip_files = [i for i in images if i.endswith('.zip')] if len(zip_files) == 1: # we have a zip archive with images zip_name = zip_files[0] logging.info('Reading list of images from zip file %s', zip_name) blob = self._storage_client.get_blob(zip_name) buf = BytesIO() logging.info('Downloading zip') blob.download_to_file(buf) buf.seek(0) logging.info('Reading content of the zip') with zipfile.ZipFile(buf) as f: images = [os.path.join(zip_name, os.path.basename(n)) for n in f.namelist() if n.endswith('.png')] buf.close() logging.info('Found %d images', len(images)) else: # we have just a directory with images, filter non-PNG files logging.info('Reading list of images from png files in storage') images = [i for i in images if i.endswith('.png')] logging.info('Found %d images', len(images)) # filter images which should be skipped images = [i for i in images if os.path.basename(i)[:-4] not in skip_image_ids] # assign IDs to images images = [(DATASET_IMAGE_ID_PATTERN.format(idx), i) for idx, i in enumerate(sorted(images))] return images
[ "def", "_read_image_list", "(", "self", ",", "skip_image_ids", "=", "None", ")", ":", "if", "skip_image_ids", "is", "None", ":", "skip_image_ids", "=", "[", "]", "images", "=", "self", ".", "_storage_client", ".", "list_blobs", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "'dataset'", ",", "self", ".", "_dataset_name", ")", "+", "'/'", ")", "zip_files", "=", "[", "i", "for", "i", "in", "images", "if", "i", ".", "endswith", "(", "'.zip'", ")", "]", "if", "len", "(", "zip_files", ")", "==", "1", ":", "# we have a zip archive with images", "zip_name", "=", "zip_files", "[", "0", "]", "logging", ".", "info", "(", "'Reading list of images from zip file %s'", ",", "zip_name", ")", "blob", "=", "self", ".", "_storage_client", ".", "get_blob", "(", "zip_name", ")", "buf", "=", "BytesIO", "(", ")", "logging", ".", "info", "(", "'Downloading zip'", ")", "blob", ".", "download_to_file", "(", "buf", ")", "buf", ".", "seek", "(", "0", ")", "logging", ".", "info", "(", "'Reading content of the zip'", ")", "with", "zipfile", ".", "ZipFile", "(", "buf", ")", "as", "f", ":", "images", "=", "[", "os", ".", "path", ".", "join", "(", "zip_name", ",", "os", ".", "path", ".", "basename", "(", "n", ")", ")", "for", "n", "in", "f", ".", "namelist", "(", ")", "if", "n", ".", "endswith", "(", "'.png'", ")", "]", "buf", ".", "close", "(", ")", "logging", ".", "info", "(", "'Found %d images'", ",", "len", "(", "images", ")", ")", "else", ":", "# we have just a directory with images, filter non-PNG files", "logging", ".", "info", "(", "'Reading list of images from png files in storage'", ")", "images", "=", "[", "i", "for", "i", "in", "images", "if", "i", ".", "endswith", "(", "'.png'", ")", "]", "logging", ".", "info", "(", "'Found %d images'", ",", "len", "(", "images", ")", ")", "# filter images which should be skipped", "images", "=", "[", "i", "for", "i", "in", "images", "if", "os", ".", "path", ".", "basename", "(", "i", ")", "[", ":", "-", "4", "]", "not", "in", "skip_image_ids", "]", "# assign IDs to images", "images", "=", "[", "(", "DATASET_IMAGE_ID_PATTERN", ".", "format", "(", "idx", ")", ",", "i", ")", "for", "idx", ",", "i", "in", "enumerate", "(", "sorted", "(", "images", ")", ")", "]", "return", "images" ]
Reads list of dataset images from the datastore.
[ "Reads", "list", "of", "dataset", "images", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L189-L222
28,453
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
DatasetBatches.init_from_storage_write_to_datastore
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read """ if allowed_epsilon is None: allowed_epsilon = copy.copy(DEFAULT_EPSILON) # init dataset batches from data in storage self._dataset_batches = {} # read all blob names from storage images = self._read_image_list(skip_image_ids) if max_num_images: images = images[:max_num_images] for batch_idx, batch_start in enumerate(range(0, len(images), batch_size)): batch = images[batch_start:batch_start+batch_size] batch_id = DATASET_BATCH_ID_PATTERN.format(batch_idx) batch_epsilon = allowed_epsilon[batch_idx % len(allowed_epsilon)] self.add_batch(batch_id, {'epsilon': batch_epsilon}) for image_id, image_path in batch: self.add_image(batch_id, image_id, {'dataset_image_id': os.path.basename(image_path)[:-4], 'image_path': image_path}) # write data to datastore self.write_to_datastore()
python
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read """ if allowed_epsilon is None: allowed_epsilon = copy.copy(DEFAULT_EPSILON) # init dataset batches from data in storage self._dataset_batches = {} # read all blob names from storage images = self._read_image_list(skip_image_ids) if max_num_images: images = images[:max_num_images] for batch_idx, batch_start in enumerate(range(0, len(images), batch_size)): batch = images[batch_start:batch_start+batch_size] batch_id = DATASET_BATCH_ID_PATTERN.format(batch_idx) batch_epsilon = allowed_epsilon[batch_idx % len(allowed_epsilon)] self.add_batch(batch_id, {'epsilon': batch_epsilon}) for image_id, image_path in batch: self.add_image(batch_id, image_id, {'dataset_image_id': os.path.basename(image_path)[:-4], 'image_path': image_path}) # write data to datastore self.write_to_datastore()
[ "def", "init_from_storage_write_to_datastore", "(", "self", ",", "batch_size", "=", "100", ",", "allowed_epsilon", "=", "None", ",", "skip_image_ids", "=", "None", ",", "max_num_images", "=", "None", ")", ":", "if", "allowed_epsilon", "is", "None", ":", "allowed_epsilon", "=", "copy", ".", "copy", "(", "DEFAULT_EPSILON", ")", "# init dataset batches from data in storage", "self", ".", "_dataset_batches", "=", "{", "}", "# read all blob names from storage", "images", "=", "self", ".", "_read_image_list", "(", "skip_image_ids", ")", "if", "max_num_images", ":", "images", "=", "images", "[", ":", "max_num_images", "]", "for", "batch_idx", ",", "batch_start", "in", "enumerate", "(", "range", "(", "0", ",", "len", "(", "images", ")", ",", "batch_size", ")", ")", ":", "batch", "=", "images", "[", "batch_start", ":", "batch_start", "+", "batch_size", "]", "batch_id", "=", "DATASET_BATCH_ID_PATTERN", ".", "format", "(", "batch_idx", ")", "batch_epsilon", "=", "allowed_epsilon", "[", "batch_idx", "%", "len", "(", "allowed_epsilon", ")", "]", "self", ".", "add_batch", "(", "batch_id", ",", "{", "'epsilon'", ":", "batch_epsilon", "}", ")", "for", "image_id", ",", "image_path", "in", "batch", ":", "self", ".", "add_image", "(", "batch_id", ",", "image_id", ",", "{", "'dataset_image_id'", ":", "os", ".", "path", ".", "basename", "(", "image_path", ")", "[", ":", "-", "4", "]", ",", "'image_path'", ":", "image_path", "}", ")", "# write data to datastore", "self", ".", "write_to_datastore", "(", ")" ]
Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read
[ "Initializes", "dataset", "batches", "from", "the", "list", "of", "images", "in", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L224-L255
28,454
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
AversarialBatches.init_from_dataset_and_submissions_write_to_datastore
def init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids): """Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and nontargeted) attack submissions, could be obtains as CompetitionSubmissions.get_all_attack_ids() """ batches_x_attacks = itertools.product(dataset_batches.data.keys(), attack_submission_ids) for idx, (dataset_batch_id, attack_id) in enumerate(batches_x_attacks): adv_batch_id = ADVERSARIAL_BATCH_ID_PATTERN.format(idx) self.add_batch(adv_batch_id, {'dataset_batch_id': dataset_batch_id, 'submission_id': attack_id}) self.write_to_datastore()
python
def init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids): """Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and nontargeted) attack submissions, could be obtains as CompetitionSubmissions.get_all_attack_ids() """ batches_x_attacks = itertools.product(dataset_batches.data.keys(), attack_submission_ids) for idx, (dataset_batch_id, attack_id) in enumerate(batches_x_attacks): adv_batch_id = ADVERSARIAL_BATCH_ID_PATTERN.format(idx) self.add_batch(adv_batch_id, {'dataset_batch_id': dataset_batch_id, 'submission_id': attack_id}) self.write_to_datastore()
[ "def", "init_from_dataset_and_submissions_write_to_datastore", "(", "self", ",", "dataset_batches", ",", "attack_submission_ids", ")", ":", "batches_x_attacks", "=", "itertools", ".", "product", "(", "dataset_batches", ".", "data", ".", "keys", "(", ")", ",", "attack_submission_ids", ")", "for", "idx", ",", "(", "dataset_batch_id", ",", "attack_id", ")", "in", "enumerate", "(", "batches_x_attacks", ")", ":", "adv_batch_id", "=", "ADVERSARIAL_BATCH_ID_PATTERN", ".", "format", "(", "idx", ")", "self", ".", "add_batch", "(", "adv_batch_id", ",", "{", "'dataset_batch_id'", ":", "dataset_batch_id", ",", "'submission_id'", ":", "attack_id", "}", ")", "self", ".", "write_to_datastore", "(", ")" ]
Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and nontargeted) attack submissions, could be obtains as CompetitionSubmissions.get_all_attack_ids()
[ "Init", "list", "of", "adversarial", "batches", "from", "dataset", "batches", "and", "submissions", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L272-L289
28,455
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
AversarialBatches.count_generated_adv_examples
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
python
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
[ "def", "count_generated_adv_examples", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "data", ")", ":", "s_id", "=", "v", "[", "'submission_id'", "]", "result", "[", "s_id", "]", "=", "result", ".", "get", "(", "s_id", ",", "0", ")", "+", "len", "(", "v", "[", "'images'", "]", ")", "return", "result" ]
Returns total number of all generated adversarial examples.
[ "Returns", "total", "number", "of", "all", "generated", "adversarial", "examples", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L291-L297
28,456
tensorflow/cleverhans
cleverhans/utils.py
create_logger
def create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """ base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)s %(asctime)s %(name)s] ' + '%(message)s') ch.setFormatter(formatter) base.addHandler(ch) return base
python
def create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """ base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)s %(asctime)s %(name)s] ' + '%(message)s') ch.setFormatter(formatter) base.addHandler(ch) return base
[ "def", "create_logger", "(", "name", ")", ":", "base", "=", "logging", ".", "getLogger", "(", "\"cleverhans\"", ")", "if", "len", "(", "base", ".", "handlers", ")", "==", "0", ":", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'[%(levelname)s %(asctime)s %(name)s] '", "+", "'%(message)s'", ")", "ch", ".", "setFormatter", "(", "formatter", ")", "base", ".", "addHandler", "(", "ch", ")", "return", "base" ]
Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter.
[ "Create", "a", "logger", "object", "with", "the", "given", "name", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L247-L262
28,457
tensorflow/cleverhans
cleverhans/utils.py
deterministic_dict
def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """ out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
python
def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """ out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
[ "def", "deterministic_dict", "(", "normal_dict", ")", ":", "out", "=", "OrderedDict", "(", ")", "for", "key", "in", "sorted", "(", "normal_dict", ".", "keys", "(", ")", ")", ":", "out", "[", "key", "]", "=", "normal_dict", "[", "key", "]", "return", "out" ]
Returns a version of `normal_dict` whose iteration order is always the same
[ "Returns", "a", "version", "of", "normal_dict", "whose", "iteration", "order", "is", "always", "the", "same" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L265-L272
28,458
tensorflow/cleverhans
cleverhans/utils.py
shell_call
def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be replaced by value from **kwargs with key 'NAME'. **kwargs: dictionary with argument substitution Returns: output of the command Raises: subprocess.CalledProcessError if command return value is not zero This function is useful when you need to do variable substitution prior running the command. Below are few examples of how it works: shell_call(['cp', 'a', 'b'], a='asd') calls command 'cp a b' shell_call(['cp', '${a}', 'b'], a='asd') calls command 'cp asd b', '${a}; was replaced with 'asd' before calling the command """ # Regular expression to find instances of '${NAME}' in a string CMD_VARIABLE_RE = re.compile('^\\$\\{(\\w+)\\}$') command = list(command) for i in range(len(command)): m = CMD_VARIABLE_RE.match(command[i]) if m: var_id = m.group(1) if var_id in kwargs: command[i] = kwargs[var_id] str_command = ' '.join(command) logging.debug('Executing shell command: %s' % str_command) return subprocess.check_output(command)
python
def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be replaced by value from **kwargs with key 'NAME'. **kwargs: dictionary with argument substitution Returns: output of the command Raises: subprocess.CalledProcessError if command return value is not zero This function is useful when you need to do variable substitution prior running the command. Below are few examples of how it works: shell_call(['cp', 'a', 'b'], a='asd') calls command 'cp a b' shell_call(['cp', '${a}', 'b'], a='asd') calls command 'cp asd b', '${a}; was replaced with 'asd' before calling the command """ # Regular expression to find instances of '${NAME}' in a string CMD_VARIABLE_RE = re.compile('^\\$\\{(\\w+)\\}$') command = list(command) for i in range(len(command)): m = CMD_VARIABLE_RE.match(command[i]) if m: var_id = m.group(1) if var_id in kwargs: command[i] = kwargs[var_id] str_command = ' '.join(command) logging.debug('Executing shell command: %s' % str_command) return subprocess.check_output(command)
[ "def", "shell_call", "(", "command", ",", "*", "*", "kwargs", ")", ":", "# Regular expression to find instances of '${NAME}' in a string", "CMD_VARIABLE_RE", "=", "re", ".", "compile", "(", "'^\\\\$\\\\{(\\\\w+)\\\\}$'", ")", "command", "=", "list", "(", "command", ")", "for", "i", "in", "range", "(", "len", "(", "command", ")", ")", ":", "m", "=", "CMD_VARIABLE_RE", ".", "match", "(", "command", "[", "i", "]", ")", "if", "m", ":", "var_id", "=", "m", ".", "group", "(", "1", ")", "if", "var_id", "in", "kwargs", ":", "command", "[", "i", "]", "=", "kwargs", "[", "var_id", "]", "str_command", "=", "' '", ".", "join", "(", "command", ")", "logging", ".", "debug", "(", "'Executing shell command: %s'", "%", "str_command", ")", "return", "subprocess", ".", "check_output", "(", "command", ")" ]
Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be replaced by value from **kwargs with key 'NAME'. **kwargs: dictionary with argument substitution Returns: output of the command Raises: subprocess.CalledProcessError if command return value is not zero This function is useful when you need to do variable substitution prior running the command. Below are few examples of how it works: shell_call(['cp', 'a', 'b'], a='asd') calls command 'cp a b' shell_call(['cp', '${a}', 'b'], a='asd') calls command 'cp asd b', '${a}; was replaced with 'asd' before calling the command
[ "Calls", "shell", "command", "with", "argument", "substitution", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L304-L339
28,459
tensorflow/cleverhans
cleverhans/utils.py
deep_copy
def deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """ out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
python
def deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """ out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
[ "def", "deep_copy", "(", "numpy_dict", ")", ":", "out", "=", "{", "}", "for", "key", "in", "numpy_dict", ":", "out", "[", "key", "]", "=", "numpy_dict", "[", "key", "]", ".", "copy", "(", ")", "return", "out" ]
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them.
[ "Returns", "a", "copy", "of", "a", "dictionary", "whose", "values", "are", "numpy", "arrays", ".", "Copies", "their", "values", "rather", "than", "copying", "references", "to", "them", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L341-L349
28,460
tensorflow/cleverhans
scripts/compute_accuracy.py
print_accuracies
def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER): """ Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intended for development work and not for publication. A more accurate estimate may be obtained by running an attack bundler instead. :param filepath: path to model to evaluate :param train_start: index of first training set example to use :param train_end: index of last training set example to use :param test_start: index of first test set example to use :param test_end: index of last test set example to use :param batch_size: size of evaluation batches :param which_set: 'train' or 'test' :param base_eps_iter: step size if the data were in [0,1] (Step size will be rescaled proportional to the actual data range) :param nb_iter: Number of iterations of PGD to run per class """ # Set TF random seed to improve reproducibility tf.set_random_seed(20181014) set_log_level(logging.INFO) sess = tf.Session() with sess.as_default(): model = load(filepath) assert len(model.get_params()) > 0 factory = model.dataset_factory factory.kwargs['train_start'] = train_start factory.kwargs['train_end'] = train_end factory.kwargs['test_start'] = test_start factory.kwargs['test_end'] = test_end dataset = factory() x_data, y_data = dataset.get_set(which_set) impl(sess, model, dataset, factory, x_data, y_data, base_eps_iter, nb_iter)
python
def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER): """ Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intended for development work and not for publication. A more accurate estimate may be obtained by running an attack bundler instead. :param filepath: path to model to evaluate :param train_start: index of first training set example to use :param train_end: index of last training set example to use :param test_start: index of first test set example to use :param test_end: index of last test set example to use :param batch_size: size of evaluation batches :param which_set: 'train' or 'test' :param base_eps_iter: step size if the data were in [0,1] (Step size will be rescaled proportional to the actual data range) :param nb_iter: Number of iterations of PGD to run per class """ # Set TF random seed to improve reproducibility tf.set_random_seed(20181014) set_log_level(logging.INFO) sess = tf.Session() with sess.as_default(): model = load(filepath) assert len(model.get_params()) > 0 factory = model.dataset_factory factory.kwargs['train_start'] = train_start factory.kwargs['train_end'] = train_end factory.kwargs['test_start'] = test_start factory.kwargs['test_end'] = test_end dataset = factory() x_data, y_data = dataset.get_set(which_set) impl(sess, model, dataset, factory, x_data, y_data, base_eps_iter, nb_iter)
[ "def", "print_accuracies", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", "WHICH_SET", ",", "base_eps_iter", "=", "BASE_EPS_ITER", ",", "nb_iter", "=", "NB_ITER", ")", ":", "# Set TF random seed to improve reproducibility", "tf", ".", "set_random_seed", "(", "20181014", ")", "set_log_level", "(", "logging", ".", "INFO", ")", "sess", "=", "tf", ".", "Session", "(", ")", "with", "sess", ".", "as_default", "(", ")", ":", "model", "=", "load", "(", "filepath", ")", "assert", "len", "(", "model", ".", "get_params", "(", ")", ")", ">", "0", "factory", "=", "model", ".", "dataset_factory", "factory", ".", "kwargs", "[", "'train_start'", "]", "=", "train_start", "factory", ".", "kwargs", "[", "'train_end'", "]", "=", "train_end", "factory", ".", "kwargs", "[", "'test_start'", "]", "=", "test_start", "factory", ".", "kwargs", "[", "'test_end'", "]", "=", "test_end", "dataset", "=", "factory", "(", ")", "x_data", ",", "y_data", "=", "dataset", ".", "get_set", "(", "which_set", ")", "impl", "(", "sess", ",", "model", ",", "dataset", ",", "factory", ",", "x_data", ",", "y_data", ",", "base_eps_iter", ",", "nb_iter", ")" ]
Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intended for development work and not for publication. A more accurate estimate may be obtained by running an attack bundler instead. :param filepath: path to model to evaluate :param train_start: index of first training set example to use :param train_end: index of last training set example to use :param test_start: index of first test set example to use :param test_end: index of last test set example to use :param batch_size: size of evaluation batches :param which_set: 'train' or 'test' :param base_eps_iter: step size if the data were in [0,1] (Step size will be rescaled proportional to the actual data range) :param nb_iter: Number of iterations of PGD to run per class
[ "Load", "a", "saved", "model", "and", "print", "out", "its", "accuracy", "on", "different", "data", "distributions" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L53-L98
28,461
tensorflow/cleverhans
examples/multigpu_advtrain/trainer.py
TrainerMultiGPU.clone_g0_inputs_on_ngpus
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variables to be cloned. :return: Updated inputs and outputs. """ assert len(inputs) == len(outputs), ( 'Inputs and outputs should have the same number of elements.') inputs[0].update(g0_inputs) outputs[0].update(g0_inputs) # Copy g0_inputs forward for i in range(1, len(inputs)): # Create the graph for i'th step of attack device_name = inputs[i]['x'].device with tf.device(device_name): with tf.variable_scope('step%d' % i): for k, v in g0_inputs.iteritems(): if k not in inputs[i]: v_copy = clone_variable(k, v) inputs[i][k] = v_copy outputs[i][k] = v_copy return inputs, outputs
python
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variables to be cloned. :return: Updated inputs and outputs. """ assert len(inputs) == len(outputs), ( 'Inputs and outputs should have the same number of elements.') inputs[0].update(g0_inputs) outputs[0].update(g0_inputs) # Copy g0_inputs forward for i in range(1, len(inputs)): # Create the graph for i'th step of attack device_name = inputs[i]['x'].device with tf.device(device_name): with tf.variable_scope('step%d' % i): for k, v in g0_inputs.iteritems(): if k not in inputs[i]: v_copy = clone_variable(k, v) inputs[i][k] = v_copy outputs[i][k] = v_copy return inputs, outputs
[ "def", "clone_g0_inputs_on_ngpus", "(", "self", ",", "inputs", ",", "outputs", ",", "g0_inputs", ")", ":", "assert", "len", "(", "inputs", ")", "==", "len", "(", "outputs", ")", ",", "(", "'Inputs and outputs should have the same number of elements.'", ")", "inputs", "[", "0", "]", ".", "update", "(", "g0_inputs", ")", "outputs", "[", "0", "]", ".", "update", "(", "g0_inputs", ")", "# Copy g0_inputs forward", "for", "i", "in", "range", "(", "1", ",", "len", "(", "inputs", ")", ")", ":", "# Create the graph for i'th step of attack", "device_name", "=", "inputs", "[", "i", "]", "[", "'x'", "]", ".", "device", "with", "tf", ".", "device", "(", "device_name", ")", ":", "with", "tf", ".", "variable_scope", "(", "'step%d'", "%", "i", ")", ":", "for", "k", ",", "v", "in", "g0_inputs", ".", "iteritems", "(", ")", ":", "if", "k", "not", "in", "inputs", "[", "i", "]", ":", "v_copy", "=", "clone_variable", "(", "k", ",", "v", ")", "inputs", "[", "i", "]", "[", "k", "]", "=", "v_copy", "outputs", "[", "i", "]", "[", "k", "]", "=", "v_copy", "return", "inputs", ",", "outputs" ]
Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variables to be cloned. :return: Updated inputs and outputs.
[ "Clone", "variables", "unused", "by", "the", "attack", "on", "all", "GPUs", ".", "Specifically", "the", "ground", "-", "truth", "label", "y", "has", "to", "be", "preserved", "until", "the", "training", "step", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/trainer.py#L313-L341
28,462
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
MLPnGPU.set_device
def set_device(self, device_name): """ Set the device before the next fprop to create a new graph on the specified device. """ device_name = unify_device_name(device_name) self.device_name = device_name for layer in self.layers: layer.device_name = device_name
python
def set_device(self, device_name): """ Set the device before the next fprop to create a new graph on the specified device. """ device_name = unify_device_name(device_name) self.device_name = device_name for layer in self.layers: layer.device_name = device_name
[ "def", "set_device", "(", "self", ",", "device_name", ")", ":", "device_name", "=", "unify_device_name", "(", "device_name", ")", "self", ".", "device_name", "=", "device_name", "for", "layer", "in", "self", ".", "layers", ":", "layer", ".", "device_name", "=", "device_name" ]
Set the device before the next fprop to create a new graph on the specified device.
[ "Set", "the", "device", "before", "the", "next", "fprop", "to", "create", "a", "new", "graph", "on", "the", "specified", "device", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L206-L214
28,463
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
LayernGPU.set_input_shape_ngpu
def set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input. """ assert self.device_name, "Device name has not been set." device_name = self.device_name if self.input_shape is None: # First time setting the input shape self.input_shape = [None] + [int(d) for d in list(new_input_shape)] if device_name in self.params_device: # There is a copy of weights on this device self.__dict__.update(self.params_device[device_name]) return # Stop recursion self.params_device[device_name] = {} # Initialize weights on this device with tf.device(device_name): self.set_input_shape(self.input_shape) keys_after = self.__dict__.keys() if self.params_names is None: # Prevent overriding training self.params_names = [k for k in keys_after if isinstance( self.__dict__[k], tf.Variable)] params = {k: self.__dict__[k] for k in self.params_names} self.params_device[device_name] = params
python
def set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input. """ assert self.device_name, "Device name has not been set." device_name = self.device_name if self.input_shape is None: # First time setting the input shape self.input_shape = [None] + [int(d) for d in list(new_input_shape)] if device_name in self.params_device: # There is a copy of weights on this device self.__dict__.update(self.params_device[device_name]) return # Stop recursion self.params_device[device_name] = {} # Initialize weights on this device with tf.device(device_name): self.set_input_shape(self.input_shape) keys_after = self.__dict__.keys() if self.params_names is None: # Prevent overriding training self.params_names = [k for k in keys_after if isinstance( self.__dict__[k], tf.Variable)] params = {k: self.__dict__[k] for k in self.params_names} self.params_device[device_name] = params
[ "def", "set_input_shape_ngpu", "(", "self", ",", "new_input_shape", ")", ":", "assert", "self", ".", "device_name", ",", "\"Device name has not been set.\"", "device_name", "=", "self", ".", "device_name", "if", "self", ".", "input_shape", "is", "None", ":", "# First time setting the input shape", "self", ".", "input_shape", "=", "[", "None", "]", "+", "[", "int", "(", "d", ")", "for", "d", "in", "list", "(", "new_input_shape", ")", "]", "if", "device_name", "in", "self", ".", "params_device", ":", "# There is a copy of weights on this device", "self", ".", "__dict__", ".", "update", "(", "self", ".", "params_device", "[", "device_name", "]", ")", "return", "# Stop recursion", "self", ".", "params_device", "[", "device_name", "]", "=", "{", "}", "# Initialize weights on this device", "with", "tf", ".", "device", "(", "device_name", ")", ":", "self", ".", "set_input_shape", "(", "self", ".", "input_shape", ")", "keys_after", "=", "self", ".", "__dict__", ".", "keys", "(", ")", "if", "self", ".", "params_names", "is", "None", ":", "# Prevent overriding training", "self", ".", "params_names", "=", "[", "k", "for", "k", "in", "keys_after", "if", "isinstance", "(", "self", ".", "__dict__", "[", "k", "]", ",", "tf", ".", "Variable", ")", "]", "params", "=", "{", "k", ":", "self", ".", "__dict__", "[", "k", "]", "for", "k", "in", "self", ".", "params_names", "}", "self", ".", "params_device", "[", "device_name", "]", "=", "params" ]
Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input.
[ "Create", "and", "initialize", "layer", "parameters", "on", "the", "device", "previously", "set", "in", "self", ".", "device_name", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L266-L297
28,464
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
LayernGPU.create_sync_ops
def create_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'. """ sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): if device == host_device: continue for k in self.params_names: if isinstance(params[k], tf.Variable): sync_ops += [tf.assign(params[k], host_params[k])] return sync_ops
python
def create_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'. """ sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): if device == host_device: continue for k in self.params_names: if isinstance(params[k], tf.Variable): sync_ops += [tf.assign(params[k], host_params[k])] return sync_ops
[ "def", "create_sync_ops", "(", "self", ",", "host_device", ")", ":", "sync_ops", "=", "[", "]", "host_params", "=", "self", ".", "params_device", "[", "host_device", "]", "for", "device", ",", "params", "in", "(", "self", ".", "params_device", ")", ".", "iteritems", "(", ")", ":", "if", "device", "==", "host_device", ":", "continue", "for", "k", "in", "self", ".", "params_names", ":", "if", "isinstance", "(", "params", "[", "k", "]", ",", "tf", ".", "Variable", ")", ":", "sync_ops", "+=", "[", "tf", ".", "assign", "(", "params", "[", "k", "]", ",", "host_params", "[", "k", "]", ")", "]", "return", "sync_ops" ]
Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'.
[ "Create", "an", "assignment", "operation", "for", "each", "weight", "on", "all", "devices", ".", "The", "weight", "is", "assigned", "the", "value", "of", "the", "copy", "on", "the", "host_device", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L299-L311
28,465
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
iterate_with_exp_backoff
def iterate_with_exp_backoff(base_iter, max_num_tries=6, max_backoff=300.0, start_backoff=4.0, backoff_multiplier=2.0, frac_random_backoff=0.25): """Iterate with exponential backoff on failures. Useful to wrap results of datastore Query.fetch to avoid 429 error. Args: base_iter: basic iterator of generator object max_num_tries: maximum number of tries for each request max_backoff: maximum backoff, in seconds start_backoff: initial value of backoff backoff_multiplier: backoff multiplier frac_random_backoff: fraction of the value of random part of the backoff Yields: values of yielded by base iterator """ try_number = 0 if hasattr(base_iter, '__iter__'): base_iter = iter(base_iter) while True: try: yield next(base_iter) try_number = 0 except StopIteration: break except TooManyRequests as e: logging.warning('TooManyRequests error: %s', tb.format_exc()) if try_number >= max_num_tries: logging.error('Number of tries exceeded, too many requests: %s', e) raise # compute sleep time for truncated exponential backoff sleep_time = start_backoff * math.pow(backoff_multiplier, try_number) sleep_time *= (1.0 + frac_random_backoff * random.random()) sleep_time = min(sleep_time, max_backoff) logging.warning('Too many requests error, ' 'retrying with exponential backoff %.3f', sleep_time) time.sleep(sleep_time) try_number += 1
python
def iterate_with_exp_backoff(base_iter, max_num_tries=6, max_backoff=300.0, start_backoff=4.0, backoff_multiplier=2.0, frac_random_backoff=0.25): """Iterate with exponential backoff on failures. Useful to wrap results of datastore Query.fetch to avoid 429 error. Args: base_iter: basic iterator of generator object max_num_tries: maximum number of tries for each request max_backoff: maximum backoff, in seconds start_backoff: initial value of backoff backoff_multiplier: backoff multiplier frac_random_backoff: fraction of the value of random part of the backoff Yields: values of yielded by base iterator """ try_number = 0 if hasattr(base_iter, '__iter__'): base_iter = iter(base_iter) while True: try: yield next(base_iter) try_number = 0 except StopIteration: break except TooManyRequests as e: logging.warning('TooManyRequests error: %s', tb.format_exc()) if try_number >= max_num_tries: logging.error('Number of tries exceeded, too many requests: %s', e) raise # compute sleep time for truncated exponential backoff sleep_time = start_backoff * math.pow(backoff_multiplier, try_number) sleep_time *= (1.0 + frac_random_backoff * random.random()) sleep_time = min(sleep_time, max_backoff) logging.warning('Too many requests error, ' 'retrying with exponential backoff %.3f', sleep_time) time.sleep(sleep_time) try_number += 1
[ "def", "iterate_with_exp_backoff", "(", "base_iter", ",", "max_num_tries", "=", "6", ",", "max_backoff", "=", "300.0", ",", "start_backoff", "=", "4.0", ",", "backoff_multiplier", "=", "2.0", ",", "frac_random_backoff", "=", "0.25", ")", ":", "try_number", "=", "0", "if", "hasattr", "(", "base_iter", ",", "'__iter__'", ")", ":", "base_iter", "=", "iter", "(", "base_iter", ")", "while", "True", ":", "try", ":", "yield", "next", "(", "base_iter", ")", "try_number", "=", "0", "except", "StopIteration", ":", "break", "except", "TooManyRequests", "as", "e", ":", "logging", ".", "warning", "(", "'TooManyRequests error: %s'", ",", "tb", ".", "format_exc", "(", ")", ")", "if", "try_number", ">=", "max_num_tries", ":", "logging", ".", "error", "(", "'Number of tries exceeded, too many requests: %s'", ",", "e", ")", "raise", "# compute sleep time for truncated exponential backoff", "sleep_time", "=", "start_backoff", "*", "math", ".", "pow", "(", "backoff_multiplier", ",", "try_number", ")", "sleep_time", "*=", "(", "1.0", "+", "frac_random_backoff", "*", "random", ".", "random", "(", ")", ")", "sleep_time", "=", "min", "(", "sleep_time", ",", "max_backoff", ")", "logging", ".", "warning", "(", "'Too many requests error, '", "'retrying with exponential backoff %.3f'", ",", "sleep_time", ")", "time", ".", "sleep", "(", "sleep_time", ")", "try_number", "+=", "1" ]
Iterate with exponential backoff on failures. Useful to wrap results of datastore Query.fetch to avoid 429 error. Args: base_iter: basic iterator of generator object max_num_tries: maximum number of tries for each request max_backoff: maximum backoff, in seconds start_backoff: initial value of backoff backoff_multiplier: backoff multiplier frac_random_backoff: fraction of the value of random part of the backoff Yields: values of yielded by base iterator
[ "Iterate", "with", "exponential", "backoff", "on", "failures", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L167-L209
28,466
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
CompetitionStorageClient.list_blobs
def list_blobs(self, prefix=''): """Lists names of all blobs by their prefix.""" return [b.name for b in self.bucket.list_blobs(prefix=prefix)]
python
def list_blobs(self, prefix=''): """Lists names of all blobs by their prefix.""" return [b.name for b in self.bucket.list_blobs(prefix=prefix)]
[ "def", "list_blobs", "(", "self", ",", "prefix", "=", "''", ")", ":", "return", "[", "b", ".", "name", "for", "b", "in", "self", ".", "bucket", ".", "list_blobs", "(", "prefix", "=", "prefix", ")", "]" ]
Lists names of all blobs by their prefix.
[ "Lists", "names", "of", "all", "blobs", "by", "their", "prefix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L43-L45
28,467
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.rollback
def rollback(self): """Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able to rollback already committed mutations. """ try: if self._cur_batch: self._cur_batch.rollback() except ValueError: # ignore "Batch must be in progress to rollback" error pass self._cur_batch = None self._num_mutations = 0
python
def rollback(self): """Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able to rollback already committed mutations. """ try: if self._cur_batch: self._cur_batch.rollback() except ValueError: # ignore "Batch must be in progress to rollback" error pass self._cur_batch = None self._num_mutations = 0
[ "def", "rollback", "(", "self", ")", ":", "try", ":", "if", "self", ".", "_cur_batch", ":", "self", ".", "_cur_batch", ".", "rollback", "(", ")", "except", "ValueError", ":", "# ignore \"Batch must be in progress to rollback\" error", "pass", "self", ".", "_cur_batch", "=", "None", "self", ".", "_num_mutations", "=", "0" ]
Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able to rollback already committed mutations.
[ "Rolls", "back", "pending", "mutations", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L107-L122
28,468
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.put
def put(self, entity): """Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore """ self._cur_batch.put(entity) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
python
def put(self, entity): """Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore """ self._cur_batch.put(entity) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
[ "def", "put", "(", "self", ",", "entity", ")", ":", "self", ".", "_cur_batch", ".", "put", "(", "entity", ")", "self", ".", "_num_mutations", "+=", "1", "if", "self", ".", "_num_mutations", ">=", "MAX_MUTATIONS_IN_BATCH", ":", "self", ".", "commit", "(", ")", "self", ".", "begin", "(", ")" ]
Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore
[ "Adds", "mutation", "of", "the", "entity", "to", "the", "mutation", "buffer", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L124-L137
28,469
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.delete
def delete(self, key): """Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted """ self._cur_batch.delete(key) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
python
def delete(self, key): """Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted """ self._cur_batch.delete(key) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
[ "def", "delete", "(", "self", ",", "key", ")", ":", "self", ".", "_cur_batch", ".", "delete", "(", "key", ")", "self", ".", "_num_mutations", "+=", "1", "if", "self", ".", "_num_mutations", ">=", "MAX_MUTATIONS_IN_BATCH", ":", "self", ".", "commit", "(", ")", "self", ".", "begin", "(", ")" ]
Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted
[ "Adds", "deletion", "of", "the", "entity", "with", "given", "key", "to", "the", "mutation", "buffer", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L139-L152
28,470
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
CompetitionDatastoreClient.get
def get(self, key, transaction=None): """Retrieves an entity given its key.""" return self._client.get(key, transaction=transaction)
python
def get(self, key, transaction=None): """Retrieves an entity given its key.""" return self._client.get(key, transaction=transaction)
[ "def", "get", "(", "self", ",", "key", ",", "transaction", "=", "None", ")", ":", "return", "self", ".", "_client", ".", "get", "(", "key", ",", "transaction", "=", "transaction", ")" ]
Retrieves an entity given its key.
[ "Retrieves", "an", "entity", "given", "its", "key", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L239-L241
28,471
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
sudo_remove_dirtree
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ try: subprocess.check_output(['sudo', 'rm', '-rf', dir_name]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t remove directory {0}'.format(dir_name), e)
python
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ try: subprocess.check_output(['sudo', 'rm', '-rf', dir_name]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t remove directory {0}'.format(dir_name), e)
[ "def", "sudo_remove_dirtree", "(", "dir_name", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "'sudo'", ",", "'rm'", ",", "'-rf'", ",", "dir_name", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "WorkerError", "(", "'Can'", "'t remove directory {0}'", ".", "format", "(", "dir_name", ")", ",", "e", ")" ]
Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root.
[ "Removes", "directory", "tree", "as", "a", "superuser", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L116-L129
28,472
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
main
def main(args): """Main function which runs worker.""" title = '## Starting evaluation of round {0} ##'.format(args.round_name) logging.info('\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n' + title + '\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n') if args.blacklisted_submissions: logging.warning('BLACKLISTED SUBMISSIONS: %s', args.blacklisted_submissions) random.seed() logging.info('Running nvidia-docker to ensure that GPU works') shell_call(['docker', 'run', '--runtime=nvidia', '--rm', 'nvidia/cuda', 'nvidia-smi']) eval_worker = EvaluationWorker( worker_id=args.worker_id, storage_client=eval_lib.CompetitionStorageClient( args.project_id, args.storage_bucket), datastore_client=eval_lib.CompetitionDatastoreClient( args.project_id, args.round_name), storage_bucket=args.storage_bucket, round_name=args.round_name, dataset_name=args.dataset_name, blacklisted_submissions=args.blacklisted_submissions, num_defense_shards=args.num_defense_shards) eval_worker.run_work()
python
def main(args): """Main function which runs worker.""" title = '## Starting evaluation of round {0} ##'.format(args.round_name) logging.info('\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n' + title + '\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n') if args.blacklisted_submissions: logging.warning('BLACKLISTED SUBMISSIONS: %s', args.blacklisted_submissions) random.seed() logging.info('Running nvidia-docker to ensure that GPU works') shell_call(['docker', 'run', '--runtime=nvidia', '--rm', 'nvidia/cuda', 'nvidia-smi']) eval_worker = EvaluationWorker( worker_id=args.worker_id, storage_client=eval_lib.CompetitionStorageClient( args.project_id, args.storage_bucket), datastore_client=eval_lib.CompetitionDatastoreClient( args.project_id, args.round_name), storage_bucket=args.storage_bucket, round_name=args.round_name, dataset_name=args.dataset_name, blacklisted_submissions=args.blacklisted_submissions, num_defense_shards=args.num_defense_shards) eval_worker.run_work()
[ "def", "main", "(", "args", ")", ":", "title", "=", "'## Starting evaluation of round {0} ##'", ".", "format", "(", "args", ".", "round_name", ")", "logging", ".", "info", "(", "'\\n'", "+", "'#'", "*", "len", "(", "title", ")", "+", "'\\n'", "+", "'#'", "*", "len", "(", "title", ")", "+", "'\\n'", "+", "'##'", "+", "' '", "*", "(", "len", "(", "title", ")", "-", "2", ")", "+", "'##'", "+", "'\\n'", "+", "title", "+", "'\\n'", "+", "'#'", "*", "len", "(", "title", ")", "+", "'\\n'", "+", "'#'", "*", "len", "(", "title", ")", "+", "'\\n'", "+", "'##'", "+", "' '", "*", "(", "len", "(", "title", ")", "-", "2", ")", "+", "'##'", "+", "'\\n'", ")", "if", "args", ".", "blacklisted_submissions", ":", "logging", ".", "warning", "(", "'BLACKLISTED SUBMISSIONS: %s'", ",", "args", ".", "blacklisted_submissions", ")", "random", ".", "seed", "(", ")", "logging", ".", "info", "(", "'Running nvidia-docker to ensure that GPU works'", ")", "shell_call", "(", "[", "'docker'", ",", "'run'", ",", "'--runtime=nvidia'", ",", "'--rm'", ",", "'nvidia/cuda'", ",", "'nvidia-smi'", "]", ")", "eval_worker", "=", "EvaluationWorker", "(", "worker_id", "=", "args", ".", "worker_id", ",", "storage_client", "=", "eval_lib", ".", "CompetitionStorageClient", "(", "args", ".", "project_id", ",", "args", ".", "storage_bucket", ")", ",", "datastore_client", "=", "eval_lib", ".", "CompetitionDatastoreClient", "(", "args", ".", "project_id", ",", "args", ".", "round_name", ")", ",", "storage_bucket", "=", "args", ".", "storage_bucket", ",", "round_name", "=", "args", ".", "round_name", ",", "dataset_name", "=", "args", ".", "dataset_name", ",", "blacklisted_submissions", "=", "args", ".", "blacklisted_submissions", ",", "num_defense_shards", "=", "args", ".", "num_defense_shards", ")", "eval_worker", ".", "run_work", "(", ")" ]
Main function which runs worker.
[ "Main", "function", "which", "runs", "worker", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L900-L929
28,473
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
ExecutableSubmission.temp_copy_extracted_submission
def temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary copy of submission is deleted. Returns: directory where temporary copy is located """ tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy') shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir), tmp_copy_dir]) return tmp_copy_dir
python
def temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary copy of submission is deleted. Returns: directory where temporary copy is located """ tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy') shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir), tmp_copy_dir]) return tmp_copy_dir
[ "def", "temp_copy_extracted_submission", "(", "self", ")", ":", "tmp_copy_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "submission_dir", ",", "'tmp_copy'", ")", "shell_call", "(", "[", "'cp'", ",", "'-R'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "extracted_submission_dir", ")", ",", "tmp_copy_dir", "]", ")", "return", "tmp_copy_dir" ]
Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary copy of submission is deleted. Returns: directory where temporary copy is located
[ "Creates", "a", "temporary", "copy", "of", "extracted", "submission", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L311-L325
28,474
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
ExecutableSubmission.run_without_time_limit
def run_without_time_limit(self, cmd): """Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission """ cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd logging.info('Docker command: %s', ' '.join(cmd)) start_time = time.time() retval = subprocess.call(cmd) elapsed_time_sec = int(time.time() - start_time) logging.info('Elapsed time of attack: %d', elapsed_time_sec) logging.info('Docker retval: %d', retval) if retval != 0: logging.warning('Docker returned non-zero retval: %d', retval) raise WorkerError('Docker returned non-zero retval ' + str(retval)) return elapsed_time_sec
python
def run_without_time_limit(self, cmd): """Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission """ cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd logging.info('Docker command: %s', ' '.join(cmd)) start_time = time.time() retval = subprocess.call(cmd) elapsed_time_sec = int(time.time() - start_time) logging.info('Elapsed time of attack: %d', elapsed_time_sec) logging.info('Docker retval: %d', retval) if retval != 0: logging.warning('Docker returned non-zero retval: %d', retval) raise WorkerError('Docker returned non-zero retval ' + str(retval)) return elapsed_time_sec
[ "def", "run_without_time_limit", "(", "self", ",", "cmd", ")", ":", "cmd", "=", "[", "DOCKER_BINARY", ",", "'run'", ",", "DOCKER_NVIDIA_RUNTIME", "]", "+", "cmd", "logging", ".", "info", "(", "'Docker command: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "start_time", "=", "time", ".", "time", "(", ")", "retval", "=", "subprocess", ".", "call", "(", "cmd", ")", "elapsed_time_sec", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "logging", ".", "info", "(", "'Elapsed time of attack: %d'", ",", "elapsed_time_sec", ")", "logging", ".", "info", "(", "'Docker retval: %d'", ",", "retval", ")", "if", "retval", "!=", "0", ":", "logging", ".", "warning", "(", "'Docker returned non-zero retval: %d'", ",", "retval", ")", "raise", "WorkerError", "(", "'Docker returned non-zero retval '", "+", "str", "(", "retval", ")", ")", "return", "elapsed_time_sec" ]
Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission
[ "Runs", "docker", "command", "without", "time", "limit", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L327-L350
28,475
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
ExecutableSubmission.run_with_time_limit
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT): """Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no limit. Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission """ if time_limit < 0: return self.run_without_time_limit(cmd) container_name = str(uuid.uuid4()) cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME, '--detach', '--name', container_name] + cmd logging.info('Docker command: %s', ' '.join(cmd)) logging.info('Time limit %d seconds', time_limit) retval = subprocess.call(cmd) start_time = time.time() elapsed_time_sec = 0 while is_docker_still_running(container_name): elapsed_time_sec = int(time.time() - start_time) if elapsed_time_sec < time_limit: time.sleep(1) else: kill_docker_container(container_name) logging.warning('Submission was killed because run out of time') logging.info('Elapsed time of submission: %d', elapsed_time_sec) logging.info('Docker retval: %d', retval) if retval != 0: logging.warning('Docker returned non-zero retval: %d', retval) raise WorkerError('Docker returned non-zero retval ' + str(retval)) return elapsed_time_sec
python
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT): """Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no limit. Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission """ if time_limit < 0: return self.run_without_time_limit(cmd) container_name = str(uuid.uuid4()) cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME, '--detach', '--name', container_name] + cmd logging.info('Docker command: %s', ' '.join(cmd)) logging.info('Time limit %d seconds', time_limit) retval = subprocess.call(cmd) start_time = time.time() elapsed_time_sec = 0 while is_docker_still_running(container_name): elapsed_time_sec = int(time.time() - start_time) if elapsed_time_sec < time_limit: time.sleep(1) else: kill_docker_container(container_name) logging.warning('Submission was killed because run out of time') logging.info('Elapsed time of submission: %d', elapsed_time_sec) logging.info('Docker retval: %d', retval) if retval != 0: logging.warning('Docker returned non-zero retval: %d', retval) raise WorkerError('Docker returned non-zero retval ' + str(retval)) return elapsed_time_sec
[ "def", "run_with_time_limit", "(", "self", ",", "cmd", ",", "time_limit", "=", "SUBMISSION_TIME_LIMIT", ")", ":", "if", "time_limit", "<", "0", ":", "return", "self", ".", "run_without_time_limit", "(", "cmd", ")", "container_name", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "cmd", "=", "[", "DOCKER_BINARY", ",", "'run'", ",", "DOCKER_NVIDIA_RUNTIME", ",", "'--detach'", ",", "'--name'", ",", "container_name", "]", "+", "cmd", "logging", ".", "info", "(", "'Docker command: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "logging", ".", "info", "(", "'Time limit %d seconds'", ",", "time_limit", ")", "retval", "=", "subprocess", ".", "call", "(", "cmd", ")", "start_time", "=", "time", ".", "time", "(", ")", "elapsed_time_sec", "=", "0", "while", "is_docker_still_running", "(", "container_name", ")", ":", "elapsed_time_sec", "=", "int", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "if", "elapsed_time_sec", "<", "time_limit", ":", "time", ".", "sleep", "(", "1", ")", "else", ":", "kill_docker_container", "(", "container_name", ")", "logging", ".", "warning", "(", "'Submission was killed because run out of time'", ")", "logging", ".", "info", "(", "'Elapsed time of submission: %d'", ",", "elapsed_time_sec", ")", "logging", ".", "info", "(", "'Docker retval: %d'", ",", "retval", ")", "if", "retval", "!=", "0", ":", "logging", ".", "warning", "(", "'Docker returned non-zero retval: %d'", ",", "retval", ")", "raise", "WorkerError", "(", "'Docker returned non-zero retval '", "+", "str", "(", "retval", ")", ")", "return", "elapsed_time_sec" ]
Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no limit. Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission
[ "Runs", "docker", "command", "and", "enforces", "time", "limit", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L352-L388
28,476
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
DefenseSubmission.run
def run(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds """ logging.info('Running defense %s', self.submission_id) tmp_run_dir = self.temp_copy_extracted_submission() output_dir = os.path.dirname(output_file_path) output_filename = os.path.basename(output_file_path) cmd = ['--network=none', '-m=24g', '--cpus=3.75', '-v', '{0}:/input_images:ro'.format(input_dir), '-v', '{0}:/output_data'.format(output_dir), '-v', '{0}:/code'.format(tmp_run_dir), '-w', '/code', self.container_name, './' + self.entry_point, '/input_images', '/output_data/' + output_filename] elapsed_time_sec = self.run_with_time_limit(cmd) sudo_remove_dirtree(tmp_run_dir) return elapsed_time_sec
python
def run(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds """ logging.info('Running defense %s', self.submission_id) tmp_run_dir = self.temp_copy_extracted_submission() output_dir = os.path.dirname(output_file_path) output_filename = os.path.basename(output_file_path) cmd = ['--network=none', '-m=24g', '--cpus=3.75', '-v', '{0}:/input_images:ro'.format(input_dir), '-v', '{0}:/output_data'.format(output_dir), '-v', '{0}:/code'.format(tmp_run_dir), '-w', '/code', self.container_name, './' + self.entry_point, '/input_images', '/output_data/' + output_filename] elapsed_time_sec = self.run_with_time_limit(cmd) sudo_remove_dirtree(tmp_run_dir) return elapsed_time_sec
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_file_path", ")", ":", "logging", ".", "info", "(", "'Running defense %s'", ",", "self", ".", "submission_id", ")", "tmp_run_dir", "=", "self", ".", "temp_copy_extracted_submission", "(", ")", "output_dir", "=", "os", ".", "path", ".", "dirname", "(", "output_file_path", ")", "output_filename", "=", "os", ".", "path", ".", "basename", "(", "output_file_path", ")", "cmd", "=", "[", "'--network=none'", ",", "'-m=24g'", ",", "'--cpus=3.75'", ",", "'-v'", ",", "'{0}:/input_images:ro'", ".", "format", "(", "input_dir", ")", ",", "'-v'", ",", "'{0}:/output_data'", ".", "format", "(", "output_dir", ")", ",", "'-v'", ",", "'{0}:/code'", ".", "format", "(", "tmp_run_dir", ")", ",", "'-w'", ",", "'/code'", ",", "self", ".", "container_name", ",", "'./'", "+", "self", ".", "entry_point", ",", "'/input_images'", ",", "'/output_data/'", "+", "output_filename", "]", "elapsed_time_sec", "=", "self", ".", "run_with_time_limit", "(", "cmd", ")", "sudo_remove_dirtree", "(", "tmp_run_dir", ")", "return", "elapsed_time_sec" ]
Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds
[ "Runs", "defense", "inside", "Docker", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L462-L489
28,477
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.read_dataset_metadata
def read_dataset_metadata(self): """Read `dataset_meta` field from bucket""" if self.dataset_meta: return shell_call(['gsutil', 'cp', 'gs://' + self.storage_client.bucket_name + '/' + 'dataset/' + self.dataset_name + '_dataset.csv', LOCAL_DATASET_METADATA_FILE]) with open(LOCAL_DATASET_METADATA_FILE, 'r') as f: self.dataset_meta = eval_lib.DatasetMetadata(f)
python
def read_dataset_metadata(self): """Read `dataset_meta` field from bucket""" if self.dataset_meta: return shell_call(['gsutil', 'cp', 'gs://' + self.storage_client.bucket_name + '/' + 'dataset/' + self.dataset_name + '_dataset.csv', LOCAL_DATASET_METADATA_FILE]) with open(LOCAL_DATASET_METADATA_FILE, 'r') as f: self.dataset_meta = eval_lib.DatasetMetadata(f)
[ "def", "read_dataset_metadata", "(", "self", ")", ":", "if", "self", ".", "dataset_meta", ":", "return", "shell_call", "(", "[", "'gsutil'", ",", "'cp'", ",", "'gs://'", "+", "self", ".", "storage_client", ".", "bucket_name", "+", "'/'", "+", "'dataset/'", "+", "self", ".", "dataset_name", "+", "'_dataset.csv'", ",", "LOCAL_DATASET_METADATA_FILE", "]", ")", "with", "open", "(", "LOCAL_DATASET_METADATA_FILE", ",", "'r'", ")", "as", "f", ":", "self", ".", "dataset_meta", "=", "eval_lib", ".", "DatasetMetadata", "(", "f", ")" ]
Read `dataset_meta` field from bucket
[ "Read", "dataset_meta", "field", "from", "bucket" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L556-L565
28,478
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.fetch_attacks_data
def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop. """ if self.attacks_data_initialized: return # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # copy dataset locally if not os.path.exists(LOCAL_DATASET_DIR): os.makedirs(LOCAL_DATASET_DIR) eval_lib.download_dataset(self.storage_client, self.dataset_batches, LOCAL_DATASET_DIR, os.path.join(LOCAL_DATASET_COPY, self.dataset_name, 'images')) # download dataset metadata self.read_dataset_metadata() # mark as initialized self.attacks_data_initialized = True
python
def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop. """ if self.attacks_data_initialized: return # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # copy dataset locally if not os.path.exists(LOCAL_DATASET_DIR): os.makedirs(LOCAL_DATASET_DIR) eval_lib.download_dataset(self.storage_client, self.dataset_batches, LOCAL_DATASET_DIR, os.path.join(LOCAL_DATASET_COPY, self.dataset_name, 'images')) # download dataset metadata self.read_dataset_metadata() # mark as initialized self.attacks_data_initialized = True
[ "def", "fetch_attacks_data", "(", "self", ")", ":", "if", "self", ".", "attacks_data_initialized", ":", "return", "# init data from datastore", "self", ".", "submissions", ".", "init_from_datastore", "(", ")", "self", ".", "dataset_batches", ".", "init_from_datastore", "(", ")", "self", ".", "adv_batches", ".", "init_from_datastore", "(", ")", "# copy dataset locally", "if", "not", "os", ".", "path", ".", "exists", "(", "LOCAL_DATASET_DIR", ")", ":", "os", ".", "makedirs", "(", "LOCAL_DATASET_DIR", ")", "eval_lib", ".", "download_dataset", "(", "self", ".", "storage_client", ",", "self", ".", "dataset_batches", ",", "LOCAL_DATASET_DIR", ",", "os", ".", "path", ".", "join", "(", "LOCAL_DATASET_COPY", ",", "self", ".", "dataset_name", ",", "'images'", ")", ")", "# download dataset metadata", "self", ".", "read_dataset_metadata", "(", ")", "# mark as initialized", "self", ".", "attacks_data_initialized", "=", "True" ]
Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop.
[ "Initializes", "data", "necessary", "to", "execute", "attacks", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L567-L589
28,479
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_attack_work
def run_attack_work(self, work_id): """Runs one attack work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ adv_batch_id = ( self.attack_work.work[work_id]['output_adversarial_batch_id']) adv_batch = self.adv_batches[adv_batch_id] dataset_batch_id = adv_batch['dataset_batch_id'] submission_id = adv_batch['submission_id'] epsilon = self.dataset_batches[dataset_batch_id]['epsilon'] logging.info('Attack work piece: ' 'dataset_batch_id="%s" submission_id="%s" ' 'epsilon=%d', dataset_batch_id, submission_id, epsilon) if submission_id in self.blacklisted_submissions: raise WorkerError('Blacklisted submission') # get attack attack = AttackSubmission(submission_id, self.submissions, self.storage_bucket) attack.download() # prepare input input_dir = os.path.join(LOCAL_DATASET_DIR, dataset_batch_id) if attack.type == TYPE_TARGETED: # prepare file with target classes target_class_filename = os.path.join(input_dir, 'target_class.csv') self.dataset_meta.save_target_classes_for_batch(target_class_filename, self.dataset_batches, dataset_batch_id) # prepare output directory if os.path.exists(LOCAL_OUTPUT_DIR): sudo_remove_dirtree(LOCAL_OUTPUT_DIR) os.mkdir(LOCAL_OUTPUT_DIR) if os.path.exists(LOCAL_PROCESSED_OUTPUT_DIR): shutil.rmtree(LOCAL_PROCESSED_OUTPUT_DIR) os.mkdir(LOCAL_PROCESSED_OUTPUT_DIR) if os.path.exists(LOCAL_ZIPPED_OUTPUT_DIR): shutil.rmtree(LOCAL_ZIPPED_OUTPUT_DIR) os.mkdir(LOCAL_ZIPPED_OUTPUT_DIR) # run attack elapsed_time_sec = attack.run(input_dir, LOCAL_OUTPUT_DIR, epsilon) if attack.type == TYPE_TARGETED: # remove target class file os.remove(target_class_filename) # enforce epsilon and compute hashes image_hashes = eval_lib.enforce_epsilon_and_compute_hash( input_dir, LOCAL_OUTPUT_DIR, LOCAL_PROCESSED_OUTPUT_DIR, epsilon) if not image_hashes: logging.warning('No images saved by the attack.') return elapsed_time_sec, submission_id # write images back to datastore # rename images and add information to adversarial batch for clean_image_id, hash_val in iteritems(image_hashes): # we will use concatenation of batch_id and image_id # as adversarial image id and as a filename of adversarial images adv_img_id = adv_batch_id + '_' + clean_image_id # rename the image os.rename( os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, clean_image_id + '.png'), os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, adv_img_id + '.png')) # populate values which will be written to datastore image_path = '{0}/adversarial_images/{1}/{1}.zip/{2}.png'.format( self.round_name, adv_batch_id, adv_img_id) # u'' + foo is a a python 2/3 compatible way of casting foo to unicode adv_batch['images'][adv_img_id] = { 'clean_image_id': u'' + str(clean_image_id), 'image_path': u'' + str(image_path), 'image_hash': u'' + str(hash_val), } # archive all images and copy to storage zipped_images_filename = os.path.join(LOCAL_ZIPPED_OUTPUT_DIR, adv_batch_id + '.zip') try: logging.debug('Compressing adversarial images to %s', zipped_images_filename) shell_call([ 'zip', '-j', '-r', zipped_images_filename, LOCAL_PROCESSED_OUTPUT_DIR]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t make archive from adversarial iamges', e) # upload archive to storage dst_filename = '{0}/adversarial_images/{1}/{1}.zip'.format( self.round_name, adv_batch_id) logging.debug( 'Copying archive with adversarial images to %s', dst_filename) self.storage_client.new_blob(dst_filename).upload_from_filename( zipped_images_filename) # writing adv batch to datastore logging.debug('Writing adversarial batch to datastore') self.adv_batches.write_single_batch_images_to_datastore(adv_batch_id) return elapsed_time_sec, submission_id
python
def run_attack_work(self, work_id): """Runs one attack work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ adv_batch_id = ( self.attack_work.work[work_id]['output_adversarial_batch_id']) adv_batch = self.adv_batches[adv_batch_id] dataset_batch_id = adv_batch['dataset_batch_id'] submission_id = adv_batch['submission_id'] epsilon = self.dataset_batches[dataset_batch_id]['epsilon'] logging.info('Attack work piece: ' 'dataset_batch_id="%s" submission_id="%s" ' 'epsilon=%d', dataset_batch_id, submission_id, epsilon) if submission_id in self.blacklisted_submissions: raise WorkerError('Blacklisted submission') # get attack attack = AttackSubmission(submission_id, self.submissions, self.storage_bucket) attack.download() # prepare input input_dir = os.path.join(LOCAL_DATASET_DIR, dataset_batch_id) if attack.type == TYPE_TARGETED: # prepare file with target classes target_class_filename = os.path.join(input_dir, 'target_class.csv') self.dataset_meta.save_target_classes_for_batch(target_class_filename, self.dataset_batches, dataset_batch_id) # prepare output directory if os.path.exists(LOCAL_OUTPUT_DIR): sudo_remove_dirtree(LOCAL_OUTPUT_DIR) os.mkdir(LOCAL_OUTPUT_DIR) if os.path.exists(LOCAL_PROCESSED_OUTPUT_DIR): shutil.rmtree(LOCAL_PROCESSED_OUTPUT_DIR) os.mkdir(LOCAL_PROCESSED_OUTPUT_DIR) if os.path.exists(LOCAL_ZIPPED_OUTPUT_DIR): shutil.rmtree(LOCAL_ZIPPED_OUTPUT_DIR) os.mkdir(LOCAL_ZIPPED_OUTPUT_DIR) # run attack elapsed_time_sec = attack.run(input_dir, LOCAL_OUTPUT_DIR, epsilon) if attack.type == TYPE_TARGETED: # remove target class file os.remove(target_class_filename) # enforce epsilon and compute hashes image_hashes = eval_lib.enforce_epsilon_and_compute_hash( input_dir, LOCAL_OUTPUT_DIR, LOCAL_PROCESSED_OUTPUT_DIR, epsilon) if not image_hashes: logging.warning('No images saved by the attack.') return elapsed_time_sec, submission_id # write images back to datastore # rename images and add information to adversarial batch for clean_image_id, hash_val in iteritems(image_hashes): # we will use concatenation of batch_id and image_id # as adversarial image id and as a filename of adversarial images adv_img_id = adv_batch_id + '_' + clean_image_id # rename the image os.rename( os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, clean_image_id + '.png'), os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, adv_img_id + '.png')) # populate values which will be written to datastore image_path = '{0}/adversarial_images/{1}/{1}.zip/{2}.png'.format( self.round_name, adv_batch_id, adv_img_id) # u'' + foo is a a python 2/3 compatible way of casting foo to unicode adv_batch['images'][adv_img_id] = { 'clean_image_id': u'' + str(clean_image_id), 'image_path': u'' + str(image_path), 'image_hash': u'' + str(hash_val), } # archive all images and copy to storage zipped_images_filename = os.path.join(LOCAL_ZIPPED_OUTPUT_DIR, adv_batch_id + '.zip') try: logging.debug('Compressing adversarial images to %s', zipped_images_filename) shell_call([ 'zip', '-j', '-r', zipped_images_filename, LOCAL_PROCESSED_OUTPUT_DIR]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t make archive from adversarial iamges', e) # upload archive to storage dst_filename = '{0}/adversarial_images/{1}/{1}.zip'.format( self.round_name, adv_batch_id) logging.debug( 'Copying archive with adversarial images to %s', dst_filename) self.storage_client.new_blob(dst_filename).upload_from_filename( zipped_images_filename) # writing adv batch to datastore logging.debug('Writing adversarial batch to datastore') self.adv_batches.write_single_batch_images_to_datastore(adv_batch_id) return elapsed_time_sec, submission_id
[ "def", "run_attack_work", "(", "self", ",", "work_id", ")", ":", "adv_batch_id", "=", "(", "self", ".", "attack_work", ".", "work", "[", "work_id", "]", "[", "'output_adversarial_batch_id'", "]", ")", "adv_batch", "=", "self", ".", "adv_batches", "[", "adv_batch_id", "]", "dataset_batch_id", "=", "adv_batch", "[", "'dataset_batch_id'", "]", "submission_id", "=", "adv_batch", "[", "'submission_id'", "]", "epsilon", "=", "self", ".", "dataset_batches", "[", "dataset_batch_id", "]", "[", "'epsilon'", "]", "logging", ".", "info", "(", "'Attack work piece: '", "'dataset_batch_id=\"%s\" submission_id=\"%s\" '", "'epsilon=%d'", ",", "dataset_batch_id", ",", "submission_id", ",", "epsilon", ")", "if", "submission_id", "in", "self", ".", "blacklisted_submissions", ":", "raise", "WorkerError", "(", "'Blacklisted submission'", ")", "# get attack", "attack", "=", "AttackSubmission", "(", "submission_id", ",", "self", ".", "submissions", ",", "self", ".", "storage_bucket", ")", "attack", ".", "download", "(", ")", "# prepare input", "input_dir", "=", "os", ".", "path", ".", "join", "(", "LOCAL_DATASET_DIR", ",", "dataset_batch_id", ")", "if", "attack", ".", "type", "==", "TYPE_TARGETED", ":", "# prepare file with target classes", "target_class_filename", "=", "os", ".", "path", ".", "join", "(", "input_dir", ",", "'target_class.csv'", ")", "self", ".", "dataset_meta", ".", "save_target_classes_for_batch", "(", "target_class_filename", ",", "self", ".", "dataset_batches", ",", "dataset_batch_id", ")", "# prepare output directory", "if", "os", ".", "path", ".", "exists", "(", "LOCAL_OUTPUT_DIR", ")", ":", "sudo_remove_dirtree", "(", "LOCAL_OUTPUT_DIR", ")", "os", ".", "mkdir", "(", "LOCAL_OUTPUT_DIR", ")", "if", "os", ".", "path", ".", "exists", "(", "LOCAL_PROCESSED_OUTPUT_DIR", ")", ":", "shutil", ".", "rmtree", "(", "LOCAL_PROCESSED_OUTPUT_DIR", ")", "os", ".", "mkdir", "(", "LOCAL_PROCESSED_OUTPUT_DIR", ")", "if", "os", ".", "path", ".", "exists", "(", "LOCAL_ZIPPED_OUTPUT_DIR", ")", ":", "shutil", ".", "rmtree", "(", "LOCAL_ZIPPED_OUTPUT_DIR", ")", "os", ".", "mkdir", "(", "LOCAL_ZIPPED_OUTPUT_DIR", ")", "# run attack", "elapsed_time_sec", "=", "attack", ".", "run", "(", "input_dir", ",", "LOCAL_OUTPUT_DIR", ",", "epsilon", ")", "if", "attack", ".", "type", "==", "TYPE_TARGETED", ":", "# remove target class file", "os", ".", "remove", "(", "target_class_filename", ")", "# enforce epsilon and compute hashes", "image_hashes", "=", "eval_lib", ".", "enforce_epsilon_and_compute_hash", "(", "input_dir", ",", "LOCAL_OUTPUT_DIR", ",", "LOCAL_PROCESSED_OUTPUT_DIR", ",", "epsilon", ")", "if", "not", "image_hashes", ":", "logging", ".", "warning", "(", "'No images saved by the attack.'", ")", "return", "elapsed_time_sec", ",", "submission_id", "# write images back to datastore", "# rename images and add information to adversarial batch", "for", "clean_image_id", ",", "hash_val", "in", "iteritems", "(", "image_hashes", ")", ":", "# we will use concatenation of batch_id and image_id", "# as adversarial image id and as a filename of adversarial images", "adv_img_id", "=", "adv_batch_id", "+", "'_'", "+", "clean_image_id", "# rename the image", "os", ".", "rename", "(", "os", ".", "path", ".", "join", "(", "LOCAL_PROCESSED_OUTPUT_DIR", ",", "clean_image_id", "+", "'.png'", ")", ",", "os", ".", "path", ".", "join", "(", "LOCAL_PROCESSED_OUTPUT_DIR", ",", "adv_img_id", "+", "'.png'", ")", ")", "# populate values which will be written to datastore", "image_path", "=", "'{0}/adversarial_images/{1}/{1}.zip/{2}.png'", ".", "format", "(", "self", ".", "round_name", ",", "adv_batch_id", ",", "adv_img_id", ")", "# u'' + foo is a a python 2/3 compatible way of casting foo to unicode", "adv_batch", "[", "'images'", "]", "[", "adv_img_id", "]", "=", "{", "'clean_image_id'", ":", "u''", "+", "str", "(", "clean_image_id", ")", ",", "'image_path'", ":", "u''", "+", "str", "(", "image_path", ")", ",", "'image_hash'", ":", "u''", "+", "str", "(", "hash_val", ")", ",", "}", "# archive all images and copy to storage", "zipped_images_filename", "=", "os", ".", "path", ".", "join", "(", "LOCAL_ZIPPED_OUTPUT_DIR", ",", "adv_batch_id", "+", "'.zip'", ")", "try", ":", "logging", ".", "debug", "(", "'Compressing adversarial images to %s'", ",", "zipped_images_filename", ")", "shell_call", "(", "[", "'zip'", ",", "'-j'", ",", "'-r'", ",", "zipped_images_filename", ",", "LOCAL_PROCESSED_OUTPUT_DIR", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "WorkerError", "(", "'Can'", "'t make archive from adversarial iamges'", ",", "e", ")", "# upload archive to storage", "dst_filename", "=", "'{0}/adversarial_images/{1}/{1}.zip'", ".", "format", "(", "self", ".", "round_name", ",", "adv_batch_id", ")", "logging", ".", "debug", "(", "'Copying archive with adversarial images to %s'", ",", "dst_filename", ")", "self", ".", "storage_client", ".", "new_blob", "(", "dst_filename", ")", ".", "upload_from_filename", "(", "zipped_images_filename", ")", "# writing adv batch to datastore", "logging", ".", "debug", "(", "'Writing adversarial batch to datastore'", ")", "self", ".", "adv_batches", ".", "write_single_batch_images_to_datastore", "(", "adv_batch_id", ")", "return", "elapsed_time_sec", ",", "submission_id" ]
Runs one attack work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution.
[ "Runs", "one", "attack", "work", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L591-L687
28,480
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_attacks
def run_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """ logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is available self.attack_work.read_all_from_datastore() if not self.attack_work.work: logging.info('Work is not populated, waiting...') time.sleep(SLEEP_TIME) continue if self.attack_work.is_all_work_competed(): logging.info('All attack work completed.') break # download all attacks data and dataset self.fetch_attacks_data() # pick piece of work work_id = self.attack_work.try_pick_piece_of_work( self.worker_id, submission_id=prev_submission_id) if not work_id: logging.info('Failed to pick work, waiting...') time.sleep(SLEEP_TIME_SHORT) continue logging.info('Selected work_id: %s', work_id) # execute work try: elapsed_time_sec, prev_submission_id = self.run_attack_work(work_id) logging.info('Work %s is done', work_id) # indicate that work is completed is_work_update = self.attack_work.update_work_as_completed( self.worker_id, work_id, other_values={'elapsed_time': elapsed_time_sec}) except WorkerError as e: logging.info('Failed to run work:\n%s', str(e)) is_work_update = self.attack_work.update_work_as_completed( self.worker_id, work_id, error=str(e)) if not is_work_update: logging.warning('Can''t update work "%s" as completed by worker %d', work_id, self.worker_id) logging.info('******** Finished evaluation of attacks ********')
python
def run_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """ logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is available self.attack_work.read_all_from_datastore() if not self.attack_work.work: logging.info('Work is not populated, waiting...') time.sleep(SLEEP_TIME) continue if self.attack_work.is_all_work_competed(): logging.info('All attack work completed.') break # download all attacks data and dataset self.fetch_attacks_data() # pick piece of work work_id = self.attack_work.try_pick_piece_of_work( self.worker_id, submission_id=prev_submission_id) if not work_id: logging.info('Failed to pick work, waiting...') time.sleep(SLEEP_TIME_SHORT) continue logging.info('Selected work_id: %s', work_id) # execute work try: elapsed_time_sec, prev_submission_id = self.run_attack_work(work_id) logging.info('Work %s is done', work_id) # indicate that work is completed is_work_update = self.attack_work.update_work_as_completed( self.worker_id, work_id, other_values={'elapsed_time': elapsed_time_sec}) except WorkerError as e: logging.info('Failed to run work:\n%s', str(e)) is_work_update = self.attack_work.update_work_as_completed( self.worker_id, work_id, error=str(e)) if not is_work_update: logging.warning('Can''t update work "%s" as completed by worker %d', work_id, self.worker_id) logging.info('******** Finished evaluation of attacks ********')
[ "def", "run_attacks", "(", "self", ")", ":", "logging", ".", "info", "(", "'******** Start evaluation of attacks ********'", ")", "prev_submission_id", "=", "None", "while", "True", ":", "# wait until work is available", "self", ".", "attack_work", ".", "read_all_from_datastore", "(", ")", "if", "not", "self", ".", "attack_work", ".", "work", ":", "logging", ".", "info", "(", "'Work is not populated, waiting...'", ")", "time", ".", "sleep", "(", "SLEEP_TIME", ")", "continue", "if", "self", ".", "attack_work", ".", "is_all_work_competed", "(", ")", ":", "logging", ".", "info", "(", "'All attack work completed.'", ")", "break", "# download all attacks data and dataset", "self", ".", "fetch_attacks_data", "(", ")", "# pick piece of work", "work_id", "=", "self", ".", "attack_work", ".", "try_pick_piece_of_work", "(", "self", ".", "worker_id", ",", "submission_id", "=", "prev_submission_id", ")", "if", "not", "work_id", ":", "logging", ".", "info", "(", "'Failed to pick work, waiting...'", ")", "time", ".", "sleep", "(", "SLEEP_TIME_SHORT", ")", "continue", "logging", ".", "info", "(", "'Selected work_id: %s'", ",", "work_id", ")", "# execute work", "try", ":", "elapsed_time_sec", ",", "prev_submission_id", "=", "self", ".", "run_attack_work", "(", "work_id", ")", "logging", ".", "info", "(", "'Work %s is done'", ",", "work_id", ")", "# indicate that work is completed", "is_work_update", "=", "self", ".", "attack_work", ".", "update_work_as_completed", "(", "self", ".", "worker_id", ",", "work_id", ",", "other_values", "=", "{", "'elapsed_time'", ":", "elapsed_time_sec", "}", ")", "except", "WorkerError", "as", "e", ":", "logging", ".", "info", "(", "'Failed to run work:\\n%s'", ",", "str", "(", "e", ")", ")", "is_work_update", "=", "self", ".", "attack_work", ".", "update_work_as_completed", "(", "self", ".", "worker_id", ",", "work_id", ",", "error", "=", "str", "(", "e", ")", ")", "if", "not", "is_work_update", ":", "logging", ".", "warning", "(", "'Can'", "'t update work \"%s\" as completed by worker %d'", ",", "work_id", ",", "self", ".", "worker_id", ")", "logging", ".", "info", "(", "'******** Finished evaluation of attacks ********'", ")" ]
Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it.
[ "Method", "which", "evaluates", "all", "attack", "work", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L689-L732
28,481
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.fetch_defense_data
def fetch_defense_data(self): """Lazy initialization of data necessary to execute defenses.""" if self.defenses_data_initialized: return logging.info('Fetching defense data from datastore') # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # read dataset metadata self.read_dataset_metadata() # mark as initialized self.defenses_data_initialized = True
python
def fetch_defense_data(self): """Lazy initialization of data necessary to execute defenses.""" if self.defenses_data_initialized: return logging.info('Fetching defense data from datastore') # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # read dataset metadata self.read_dataset_metadata() # mark as initialized self.defenses_data_initialized = True
[ "def", "fetch_defense_data", "(", "self", ")", ":", "if", "self", ".", "defenses_data_initialized", ":", "return", "logging", ".", "info", "(", "'Fetching defense data from datastore'", ")", "# init data from datastore", "self", ".", "submissions", ".", "init_from_datastore", "(", ")", "self", ".", "dataset_batches", ".", "init_from_datastore", "(", ")", "self", ".", "adv_batches", ".", "init_from_datastore", "(", ")", "# read dataset metadata", "self", ".", "read_dataset_metadata", "(", ")", "# mark as initialized", "self", ".", "defenses_data_initialized", "=", "True" ]
Lazy initialization of data necessary to execute defenses.
[ "Lazy", "initialization", "of", "data", "necessary", "to", "execute", "defenses", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L734-L746
28,482
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_defense_work
def run_defense_work(self, work_id): """Runs one defense work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ class_batch_id = ( self.defense_work.work[work_id]['output_classification_batch_id']) class_batch = self.class_batches.read_batch_from_datastore(class_batch_id) adversarial_batch_id = class_batch['adversarial_batch_id'] submission_id = class_batch['submission_id'] cloud_result_path = class_batch['result_path'] logging.info('Defense work piece: ' 'adversarial_batch_id="%s" submission_id="%s"', adversarial_batch_id, submission_id) if submission_id in self.blacklisted_submissions: raise WorkerError('Blacklisted submission') # get defense defense = DefenseSubmission(submission_id, self.submissions, self.storage_bucket) defense.download() # prepare input - copy adversarial batch locally input_dir = os.path.join(LOCAL_INPUT_DIR, adversarial_batch_id) if os.path.exists(input_dir): sudo_remove_dirtree(input_dir) os.makedirs(input_dir) try: shell_call([ 'gsutil', '-m', 'cp', # typical location of adv batch: # testing-round/adversarial_images/ADVBATCH000/ os.path.join('gs://', self.storage_bucket, self.round_name, 'adversarial_images', adversarial_batch_id, '*'), input_dir ]) adv_images_files = os.listdir(input_dir) if (len(adv_images_files) == 1) and adv_images_files[0].endswith('.zip'): logging.info('Adversarial batch is in zip archive %s', adv_images_files[0]) shell_call([ 'unzip', os.path.join(input_dir, adv_images_files[0]), '-d', input_dir ]) os.remove(os.path.join(input_dir, adv_images_files[0])) adv_images_files = os.listdir(input_dir) logging.info('%d adversarial images copied', len(adv_images_files)) except (subprocess.CalledProcessError, IOError) as e: raise WorkerError('Can''t copy adversarial batch locally', e) # prepare output directory if os.path.exists(LOCAL_OUTPUT_DIR): sudo_remove_dirtree(LOCAL_OUTPUT_DIR) os.mkdir(LOCAL_OUTPUT_DIR) output_filname = os.path.join(LOCAL_OUTPUT_DIR, 'result.csv') # run defense elapsed_time_sec = defense.run(input_dir, output_filname) # evaluate defense result batch_result = eval_lib.analyze_one_classification_result( storage_client=None, file_path=output_filname, adv_batch=self.adv_batches.data[adversarial_batch_id], dataset_batches=self.dataset_batches, dataset_meta=self.dataset_meta) # copy result of the defense into storage try: shell_call([ 'gsutil', 'cp', output_filname, os.path.join('gs://', self.storage_bucket, cloud_result_path) ]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t result to Cloud Storage', e) return elapsed_time_sec, submission_id, batch_result
python
def run_defense_work(self, work_id): """Runs one defense work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ class_batch_id = ( self.defense_work.work[work_id]['output_classification_batch_id']) class_batch = self.class_batches.read_batch_from_datastore(class_batch_id) adversarial_batch_id = class_batch['adversarial_batch_id'] submission_id = class_batch['submission_id'] cloud_result_path = class_batch['result_path'] logging.info('Defense work piece: ' 'adversarial_batch_id="%s" submission_id="%s"', adversarial_batch_id, submission_id) if submission_id in self.blacklisted_submissions: raise WorkerError('Blacklisted submission') # get defense defense = DefenseSubmission(submission_id, self.submissions, self.storage_bucket) defense.download() # prepare input - copy adversarial batch locally input_dir = os.path.join(LOCAL_INPUT_DIR, adversarial_batch_id) if os.path.exists(input_dir): sudo_remove_dirtree(input_dir) os.makedirs(input_dir) try: shell_call([ 'gsutil', '-m', 'cp', # typical location of adv batch: # testing-round/adversarial_images/ADVBATCH000/ os.path.join('gs://', self.storage_bucket, self.round_name, 'adversarial_images', adversarial_batch_id, '*'), input_dir ]) adv_images_files = os.listdir(input_dir) if (len(adv_images_files) == 1) and adv_images_files[0].endswith('.zip'): logging.info('Adversarial batch is in zip archive %s', adv_images_files[0]) shell_call([ 'unzip', os.path.join(input_dir, adv_images_files[0]), '-d', input_dir ]) os.remove(os.path.join(input_dir, adv_images_files[0])) adv_images_files = os.listdir(input_dir) logging.info('%d adversarial images copied', len(adv_images_files)) except (subprocess.CalledProcessError, IOError) as e: raise WorkerError('Can''t copy adversarial batch locally', e) # prepare output directory if os.path.exists(LOCAL_OUTPUT_DIR): sudo_remove_dirtree(LOCAL_OUTPUT_DIR) os.mkdir(LOCAL_OUTPUT_DIR) output_filname = os.path.join(LOCAL_OUTPUT_DIR, 'result.csv') # run defense elapsed_time_sec = defense.run(input_dir, output_filname) # evaluate defense result batch_result = eval_lib.analyze_one_classification_result( storage_client=None, file_path=output_filname, adv_batch=self.adv_batches.data[adversarial_batch_id], dataset_batches=self.dataset_batches, dataset_meta=self.dataset_meta) # copy result of the defense into storage try: shell_call([ 'gsutil', 'cp', output_filname, os.path.join('gs://', self.storage_bucket, cloud_result_path) ]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t result to Cloud Storage', e) return elapsed_time_sec, submission_id, batch_result
[ "def", "run_defense_work", "(", "self", ",", "work_id", ")", ":", "class_batch_id", "=", "(", "self", ".", "defense_work", ".", "work", "[", "work_id", "]", "[", "'output_classification_batch_id'", "]", ")", "class_batch", "=", "self", ".", "class_batches", ".", "read_batch_from_datastore", "(", "class_batch_id", ")", "adversarial_batch_id", "=", "class_batch", "[", "'adversarial_batch_id'", "]", "submission_id", "=", "class_batch", "[", "'submission_id'", "]", "cloud_result_path", "=", "class_batch", "[", "'result_path'", "]", "logging", ".", "info", "(", "'Defense work piece: '", "'adversarial_batch_id=\"%s\" submission_id=\"%s\"'", ",", "adversarial_batch_id", ",", "submission_id", ")", "if", "submission_id", "in", "self", ".", "blacklisted_submissions", ":", "raise", "WorkerError", "(", "'Blacklisted submission'", ")", "# get defense", "defense", "=", "DefenseSubmission", "(", "submission_id", ",", "self", ".", "submissions", ",", "self", ".", "storage_bucket", ")", "defense", ".", "download", "(", ")", "# prepare input - copy adversarial batch locally", "input_dir", "=", "os", ".", "path", ".", "join", "(", "LOCAL_INPUT_DIR", ",", "adversarial_batch_id", ")", "if", "os", ".", "path", ".", "exists", "(", "input_dir", ")", ":", "sudo_remove_dirtree", "(", "input_dir", ")", "os", ".", "makedirs", "(", "input_dir", ")", "try", ":", "shell_call", "(", "[", "'gsutil'", ",", "'-m'", ",", "'cp'", ",", "# typical location of adv batch:", "# testing-round/adversarial_images/ADVBATCH000/", "os", ".", "path", ".", "join", "(", "'gs://'", ",", "self", ".", "storage_bucket", ",", "self", ".", "round_name", ",", "'adversarial_images'", ",", "adversarial_batch_id", ",", "'*'", ")", ",", "input_dir", "]", ")", "adv_images_files", "=", "os", ".", "listdir", "(", "input_dir", ")", "if", "(", "len", "(", "adv_images_files", ")", "==", "1", ")", "and", "adv_images_files", "[", "0", "]", ".", "endswith", "(", "'.zip'", ")", ":", "logging", ".", "info", "(", "'Adversarial batch is in zip archive %s'", ",", "adv_images_files", "[", "0", "]", ")", "shell_call", "(", "[", "'unzip'", ",", "os", ".", "path", ".", "join", "(", "input_dir", ",", "adv_images_files", "[", "0", "]", ")", ",", "'-d'", ",", "input_dir", "]", ")", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "input_dir", ",", "adv_images_files", "[", "0", "]", ")", ")", "adv_images_files", "=", "os", ".", "listdir", "(", "input_dir", ")", "logging", ".", "info", "(", "'%d adversarial images copied'", ",", "len", "(", "adv_images_files", ")", ")", "except", "(", "subprocess", ".", "CalledProcessError", ",", "IOError", ")", "as", "e", ":", "raise", "WorkerError", "(", "'Can'", "'t copy adversarial batch locally'", ",", "e", ")", "# prepare output directory", "if", "os", ".", "path", ".", "exists", "(", "LOCAL_OUTPUT_DIR", ")", ":", "sudo_remove_dirtree", "(", "LOCAL_OUTPUT_DIR", ")", "os", ".", "mkdir", "(", "LOCAL_OUTPUT_DIR", ")", "output_filname", "=", "os", ".", "path", ".", "join", "(", "LOCAL_OUTPUT_DIR", ",", "'result.csv'", ")", "# run defense", "elapsed_time_sec", "=", "defense", ".", "run", "(", "input_dir", ",", "output_filname", ")", "# evaluate defense result", "batch_result", "=", "eval_lib", ".", "analyze_one_classification_result", "(", "storage_client", "=", "None", ",", "file_path", "=", "output_filname", ",", "adv_batch", "=", "self", ".", "adv_batches", ".", "data", "[", "adversarial_batch_id", "]", ",", "dataset_batches", "=", "self", ".", "dataset_batches", ",", "dataset_meta", "=", "self", ".", "dataset_meta", ")", "# copy result of the defense into storage", "try", ":", "shell_call", "(", "[", "'gsutil'", ",", "'cp'", ",", "output_filname", ",", "os", ".", "path", ".", "join", "(", "'gs://'", ",", "self", ".", "storage_bucket", ",", "cloud_result_path", ")", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "WorkerError", "(", "'Can'", "'t result to Cloud Storage'", ",", "e", ")", "return", "elapsed_time_sec", ",", "submission_id", ",", "batch_result" ]
Runs one defense work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution.
[ "Runs", "one", "defense", "work", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L748-L824
28,483
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_defenses
def run_defenses(self): """Method which evaluates all defense work. In a loop this method queries not completed defense work, picks one defense work and runs it. """ logging.info('******** Start evaluation of defenses ********') prev_submission_id = None need_reload_work = True while True: # wait until work is available if need_reload_work: if self.num_defense_shards: shard_with_work = self.defense_work.read_undone_from_datastore( shard_id=(self.worker_id % self.num_defense_shards), num_shards=self.num_defense_shards) else: shard_with_work = self.defense_work.read_undone_from_datastore() logging.info('Loaded %d records of undone work from shard %s', len(self.defense_work), str(shard_with_work)) if not self.defense_work.work: logging.info('Work is not populated, waiting...') time.sleep(SLEEP_TIME) continue if self.defense_work.is_all_work_competed(): logging.info('All defense work completed.') break # download all defense data and dataset self.fetch_defense_data() need_reload_work = False # pick piece of work work_id = self.defense_work.try_pick_piece_of_work( self.worker_id, submission_id=prev_submission_id) if not work_id: need_reload_work = True logging.info('Failed to pick work, waiting...') time.sleep(SLEEP_TIME_SHORT) continue logging.info('Selected work_id: %s', work_id) # execute work try: elapsed_time_sec, prev_submission_id, batch_result = ( self.run_defense_work(work_id)) logging.info('Work %s is done', work_id) # indicate that work is completed is_work_update = self.defense_work.update_work_as_completed( self.worker_id, work_id, other_values={'elapsed_time': elapsed_time_sec, 'stat_correct': batch_result[0], 'stat_error': batch_result[1], 'stat_target_class': batch_result[2], 'stat_num_images': batch_result[3]}) except WorkerError as e: logging.info('Failed to run work:\n%s', str(e)) if str(e).startswith('Docker returned non-zero retval'): logging.info('Running nvidia-docker to ensure that GPU works') shell_call(['nvidia-docker', 'run', '--rm', 'nvidia/cuda', 'nvidia-smi']) is_work_update = self.defense_work.update_work_as_completed( self.worker_id, work_id, error=str(e)) if not is_work_update: logging.warning('Can''t update work "%s" as completed by worker %d', work_id, self.worker_id) need_reload_work = True logging.info('******** Finished evaluation of defenses ********')
python
def run_defenses(self): """Method which evaluates all defense work. In a loop this method queries not completed defense work, picks one defense work and runs it. """ logging.info('******** Start evaluation of defenses ********') prev_submission_id = None need_reload_work = True while True: # wait until work is available if need_reload_work: if self.num_defense_shards: shard_with_work = self.defense_work.read_undone_from_datastore( shard_id=(self.worker_id % self.num_defense_shards), num_shards=self.num_defense_shards) else: shard_with_work = self.defense_work.read_undone_from_datastore() logging.info('Loaded %d records of undone work from shard %s', len(self.defense_work), str(shard_with_work)) if not self.defense_work.work: logging.info('Work is not populated, waiting...') time.sleep(SLEEP_TIME) continue if self.defense_work.is_all_work_competed(): logging.info('All defense work completed.') break # download all defense data and dataset self.fetch_defense_data() need_reload_work = False # pick piece of work work_id = self.defense_work.try_pick_piece_of_work( self.worker_id, submission_id=prev_submission_id) if not work_id: need_reload_work = True logging.info('Failed to pick work, waiting...') time.sleep(SLEEP_TIME_SHORT) continue logging.info('Selected work_id: %s', work_id) # execute work try: elapsed_time_sec, prev_submission_id, batch_result = ( self.run_defense_work(work_id)) logging.info('Work %s is done', work_id) # indicate that work is completed is_work_update = self.defense_work.update_work_as_completed( self.worker_id, work_id, other_values={'elapsed_time': elapsed_time_sec, 'stat_correct': batch_result[0], 'stat_error': batch_result[1], 'stat_target_class': batch_result[2], 'stat_num_images': batch_result[3]}) except WorkerError as e: logging.info('Failed to run work:\n%s', str(e)) if str(e).startswith('Docker returned non-zero retval'): logging.info('Running nvidia-docker to ensure that GPU works') shell_call(['nvidia-docker', 'run', '--rm', 'nvidia/cuda', 'nvidia-smi']) is_work_update = self.defense_work.update_work_as_completed( self.worker_id, work_id, error=str(e)) if not is_work_update: logging.warning('Can''t update work "%s" as completed by worker %d', work_id, self.worker_id) need_reload_work = True logging.info('******** Finished evaluation of defenses ********')
[ "def", "run_defenses", "(", "self", ")", ":", "logging", ".", "info", "(", "'******** Start evaluation of defenses ********'", ")", "prev_submission_id", "=", "None", "need_reload_work", "=", "True", "while", "True", ":", "# wait until work is available", "if", "need_reload_work", ":", "if", "self", ".", "num_defense_shards", ":", "shard_with_work", "=", "self", ".", "defense_work", ".", "read_undone_from_datastore", "(", "shard_id", "=", "(", "self", ".", "worker_id", "%", "self", ".", "num_defense_shards", ")", ",", "num_shards", "=", "self", ".", "num_defense_shards", ")", "else", ":", "shard_with_work", "=", "self", ".", "defense_work", ".", "read_undone_from_datastore", "(", ")", "logging", ".", "info", "(", "'Loaded %d records of undone work from shard %s'", ",", "len", "(", "self", ".", "defense_work", ")", ",", "str", "(", "shard_with_work", ")", ")", "if", "not", "self", ".", "defense_work", ".", "work", ":", "logging", ".", "info", "(", "'Work is not populated, waiting...'", ")", "time", ".", "sleep", "(", "SLEEP_TIME", ")", "continue", "if", "self", ".", "defense_work", ".", "is_all_work_competed", "(", ")", ":", "logging", ".", "info", "(", "'All defense work completed.'", ")", "break", "# download all defense data and dataset", "self", ".", "fetch_defense_data", "(", ")", "need_reload_work", "=", "False", "# pick piece of work", "work_id", "=", "self", ".", "defense_work", ".", "try_pick_piece_of_work", "(", "self", ".", "worker_id", ",", "submission_id", "=", "prev_submission_id", ")", "if", "not", "work_id", ":", "need_reload_work", "=", "True", "logging", ".", "info", "(", "'Failed to pick work, waiting...'", ")", "time", ".", "sleep", "(", "SLEEP_TIME_SHORT", ")", "continue", "logging", ".", "info", "(", "'Selected work_id: %s'", ",", "work_id", ")", "# execute work", "try", ":", "elapsed_time_sec", ",", "prev_submission_id", ",", "batch_result", "=", "(", "self", ".", "run_defense_work", "(", "work_id", ")", ")", "logging", ".", "info", "(", "'Work %s is done'", ",", "work_id", ")", "# indicate that work is completed", "is_work_update", "=", "self", ".", "defense_work", ".", "update_work_as_completed", "(", "self", ".", "worker_id", ",", "work_id", ",", "other_values", "=", "{", "'elapsed_time'", ":", "elapsed_time_sec", ",", "'stat_correct'", ":", "batch_result", "[", "0", "]", ",", "'stat_error'", ":", "batch_result", "[", "1", "]", ",", "'stat_target_class'", ":", "batch_result", "[", "2", "]", ",", "'stat_num_images'", ":", "batch_result", "[", "3", "]", "}", ")", "except", "WorkerError", "as", "e", ":", "logging", ".", "info", "(", "'Failed to run work:\\n%s'", ",", "str", "(", "e", ")", ")", "if", "str", "(", "e", ")", ".", "startswith", "(", "'Docker returned non-zero retval'", ")", ":", "logging", ".", "info", "(", "'Running nvidia-docker to ensure that GPU works'", ")", "shell_call", "(", "[", "'nvidia-docker'", ",", "'run'", ",", "'--rm'", ",", "'nvidia/cuda'", ",", "'nvidia-smi'", "]", ")", "is_work_update", "=", "self", ".", "defense_work", ".", "update_work_as_completed", "(", "self", ".", "worker_id", ",", "work_id", ",", "error", "=", "str", "(", "e", ")", ")", "if", "not", "is_work_update", ":", "logging", ".", "warning", "(", "'Can'", "'t update work \"%s\" as completed by worker %d'", ",", "work_id", ",", "self", ".", "worker_id", ")", "need_reload_work", "=", "True", "logging", ".", "info", "(", "'******** Finished evaluation of defenses ********'", ")" ]
Method which evaluates all defense work. In a loop this method queries not completed defense work, picks one defense work and runs it.
[ "Method", "which", "evaluates", "all", "defense", "work", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L826-L890
28,484
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_work
def run_work(self): """Run attacks and defenses""" if os.path.exists(LOCAL_EVAL_ROOT_DIR): sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR) self.run_attacks() self.run_defenses()
python
def run_work(self): """Run attacks and defenses""" if os.path.exists(LOCAL_EVAL_ROOT_DIR): sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR) self.run_attacks() self.run_defenses()
[ "def", "run_work", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "LOCAL_EVAL_ROOT_DIR", ")", ":", "sudo_remove_dirtree", "(", "LOCAL_EVAL_ROOT_DIR", ")", "self", ".", "run_attacks", "(", ")", "self", ".", "run_defenses", "(", ")" ]
Run attacks and defenses
[ "Run", "attacks", "and", "defenses" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L892-L897
28,485
tensorflow/cleverhans
cleverhans/attacks/attack.py
Attack.construct_graph
def construct_graph(self, fixed, feedable, x_val, hash_key): """ Construct the graph required to run the attack through generate_np. :param fixed: Structural elements that require defining a new graph. :param feedable: Arguments that can be fed to the same graph when they take different values. :param x_val: symbolic adversarial example :param hash_key: the key used to store this graph in our cache """ # try our very best to create a TF placeholder for each of the # feedable keyword arguments, and check the types are one of # the allowed types class_name = str(self.__class__).split(".")[-1][:-2] _logger.info("Constructing new graph for attack " + class_name) # remove the None arguments, they are just left blank for k in list(feedable.keys()): if feedable[k] is None: del feedable[k] # process all of the rest and create placeholders for them new_kwargs = dict(x for x in fixed.items()) for name, value in feedable.items(): given_type = value.dtype if isinstance(value, np.ndarray): if value.ndim == 0: # This is pretty clearly not a batch of data new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name) else: # Assume that this is a batch of data, make the first axis variable # in size new_shape = [None] + list(value.shape[1:]) new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name) elif isinstance(value, utils.known_number_types): new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name) else: raise ValueError("Could not identify type of argument " + name + ": " + str(value)) # x is a special placeholder we always want to have x_shape = [None] + list(x_val.shape)[1:] x = tf.placeholder(self.tf_dtype, shape=x_shape) # now we generate the graph that we want x_adv = self.generate(x, **new_kwargs) self.graphs[hash_key] = (x, new_kwargs, x_adv) if len(self.graphs) >= 10: warnings.warn("Calling generate_np() with multiple different " "structural parameters is inefficient and should" " be avoided. Calling generate() is preferred.")
python
def construct_graph(self, fixed, feedable, x_val, hash_key): """ Construct the graph required to run the attack through generate_np. :param fixed: Structural elements that require defining a new graph. :param feedable: Arguments that can be fed to the same graph when they take different values. :param x_val: symbolic adversarial example :param hash_key: the key used to store this graph in our cache """ # try our very best to create a TF placeholder for each of the # feedable keyword arguments, and check the types are one of # the allowed types class_name = str(self.__class__).split(".")[-1][:-2] _logger.info("Constructing new graph for attack " + class_name) # remove the None arguments, they are just left blank for k in list(feedable.keys()): if feedable[k] is None: del feedable[k] # process all of the rest and create placeholders for them new_kwargs = dict(x for x in fixed.items()) for name, value in feedable.items(): given_type = value.dtype if isinstance(value, np.ndarray): if value.ndim == 0: # This is pretty clearly not a batch of data new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name) else: # Assume that this is a batch of data, make the first axis variable # in size new_shape = [None] + list(value.shape[1:]) new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name) elif isinstance(value, utils.known_number_types): new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name) else: raise ValueError("Could not identify type of argument " + name + ": " + str(value)) # x is a special placeholder we always want to have x_shape = [None] + list(x_val.shape)[1:] x = tf.placeholder(self.tf_dtype, shape=x_shape) # now we generate the graph that we want x_adv = self.generate(x, **new_kwargs) self.graphs[hash_key] = (x, new_kwargs, x_adv) if len(self.graphs) >= 10: warnings.warn("Calling generate_np() with multiple different " "structural parameters is inefficient and should" " be avoided. Calling generate() is preferred.")
[ "def", "construct_graph", "(", "self", ",", "fixed", ",", "feedable", ",", "x_val", ",", "hash_key", ")", ":", "# try our very best to create a TF placeholder for each of the", "# feedable keyword arguments, and check the types are one of", "# the allowed types", "class_name", "=", "str", "(", "self", ".", "__class__", ")", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "[", ":", "-", "2", "]", "_logger", ".", "info", "(", "\"Constructing new graph for attack \"", "+", "class_name", ")", "# remove the None arguments, they are just left blank", "for", "k", "in", "list", "(", "feedable", ".", "keys", "(", ")", ")", ":", "if", "feedable", "[", "k", "]", "is", "None", ":", "del", "feedable", "[", "k", "]", "# process all of the rest and create placeholders for them", "new_kwargs", "=", "dict", "(", "x", "for", "x", "in", "fixed", ".", "items", "(", ")", ")", "for", "name", ",", "value", "in", "feedable", ".", "items", "(", ")", ":", "given_type", "=", "value", ".", "dtype", "if", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", ":", "if", "value", ".", "ndim", "==", "0", ":", "# This is pretty clearly not a batch of data", "new_kwargs", "[", "name", "]", "=", "tf", ".", "placeholder", "(", "given_type", ",", "shape", "=", "[", "]", ",", "name", "=", "name", ")", "else", ":", "# Assume that this is a batch of data, make the first axis variable", "# in size", "new_shape", "=", "[", "None", "]", "+", "list", "(", "value", ".", "shape", "[", "1", ":", "]", ")", "new_kwargs", "[", "name", "]", "=", "tf", ".", "placeholder", "(", "given_type", ",", "new_shape", ",", "name", "=", "name", ")", "elif", "isinstance", "(", "value", ",", "utils", ".", "known_number_types", ")", ":", "new_kwargs", "[", "name", "]", "=", "tf", ".", "placeholder", "(", "given_type", ",", "shape", "=", "[", "]", ",", "name", "=", "name", ")", "else", ":", "raise", "ValueError", "(", "\"Could not identify type of argument \"", "+", "name", "+", "\": \"", "+", "str", "(", "value", ")", ")", "# x is a special placeholder we always want to have", "x_shape", "=", "[", "None", "]", "+", "list", "(", "x_val", ".", "shape", ")", "[", "1", ":", "]", "x", "=", "tf", ".", "placeholder", "(", "self", ".", "tf_dtype", ",", "shape", "=", "x_shape", ")", "# now we generate the graph that we want", "x_adv", "=", "self", ".", "generate", "(", "x", ",", "*", "*", "new_kwargs", ")", "self", ".", "graphs", "[", "hash_key", "]", "=", "(", "x", ",", "new_kwargs", ",", "x_adv", ")", "if", "len", "(", "self", ".", "graphs", ")", ">=", "10", ":", "warnings", ".", "warn", "(", "\"Calling generate_np() with multiple different \"", "\"structural parameters is inefficient and should\"", "\" be avoided. Calling generate() is preferred.\"", ")" ]
Construct the graph required to run the attack through generate_np. :param fixed: Structural elements that require defining a new graph. :param feedable: Arguments that can be fed to the same graph when they take different values. :param x_val: symbolic adversarial example :param hash_key: the key used to store this graph in our cache
[ "Construct", "the", "graph", "required", "to", "run", "the", "attack", "through", "generate_np", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L113-L165
28,486
tensorflow/cleverhans
cleverhans/attacks/attack.py
Attack.construct_variables
def construct_variables(self, kwargs): """ Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key """ if isinstance(self.feedable_kwargs, dict): warnings.warn("Using a dict for `feedable_kwargs is deprecated." "Switch to using a tuple." "It is not longer necessary to specify the types " "of the arguments---we build a different graph " "for each received type." "Using a dict may become an error on or after " "2019-04-18.") feedable_names = tuple(sorted(self.feedable_kwargs.keys())) else: feedable_names = self.feedable_kwargs if not isinstance(feedable_names, tuple): raise TypeError("Attack.feedable_kwargs should be a tuple, but " "for subclass " + str(type(self)) + " it is " + str(self.feedable_kwargs) + " of type " + str(type(self.feedable_kwargs))) # the set of arguments that are structural properties of the attack # if these arguments are different, we must construct a new graph fixed = dict( (k, v) for k, v in kwargs.items() if k in self.structural_kwargs) # the set of arguments that are passed as placeholders to the graph # on each call, and can change without constructing a new graph feedable = {k: v for k, v in kwargs.items() if k in feedable_names} for k in feedable: if isinstance(feedable[k], (float, int)): feedable[k] = np.array(feedable[k]) for key in kwargs: if key not in fixed and key not in feedable: raise ValueError(str(type(self)) + ": Undeclared argument: " + key) feed_arg_type = arg_type(feedable_names, feedable) if not all(isinstance(value, collections.Hashable) for value in fixed.values()): # we have received a fixed value that isn't hashable # this means we can't cache this graph for later use, # and it will have to be discarded later hash_key = None else: # create a unique key for this set of fixed paramaters hash_key = tuple(sorted(fixed.items())) + tuple([feed_arg_type]) return fixed, feedable, feed_arg_type, hash_key
python
def construct_variables(self, kwargs): """ Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key """ if isinstance(self.feedable_kwargs, dict): warnings.warn("Using a dict for `feedable_kwargs is deprecated." "Switch to using a tuple." "It is not longer necessary to specify the types " "of the arguments---we build a different graph " "for each received type." "Using a dict may become an error on or after " "2019-04-18.") feedable_names = tuple(sorted(self.feedable_kwargs.keys())) else: feedable_names = self.feedable_kwargs if not isinstance(feedable_names, tuple): raise TypeError("Attack.feedable_kwargs should be a tuple, but " "for subclass " + str(type(self)) + " it is " + str(self.feedable_kwargs) + " of type " + str(type(self.feedable_kwargs))) # the set of arguments that are structural properties of the attack # if these arguments are different, we must construct a new graph fixed = dict( (k, v) for k, v in kwargs.items() if k in self.structural_kwargs) # the set of arguments that are passed as placeholders to the graph # on each call, and can change without constructing a new graph feedable = {k: v for k, v in kwargs.items() if k in feedable_names} for k in feedable: if isinstance(feedable[k], (float, int)): feedable[k] = np.array(feedable[k]) for key in kwargs: if key not in fixed and key not in feedable: raise ValueError(str(type(self)) + ": Undeclared argument: " + key) feed_arg_type = arg_type(feedable_names, feedable) if not all(isinstance(value, collections.Hashable) for value in fixed.values()): # we have received a fixed value that isn't hashable # this means we can't cache this graph for later use, # and it will have to be discarded later hash_key = None else: # create a unique key for this set of fixed paramaters hash_key = tuple(sorted(fixed.items())) + tuple([feed_arg_type]) return fixed, feedable, feed_arg_type, hash_key
[ "def", "construct_variables", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "feedable_kwargs", ",", "dict", ")", ":", "warnings", ".", "warn", "(", "\"Using a dict for `feedable_kwargs is deprecated.\"", "\"Switch to using a tuple.\"", "\"It is not longer necessary to specify the types \"", "\"of the arguments---we build a different graph \"", "\"for each received type.\"", "\"Using a dict may become an error on or after \"", "\"2019-04-18.\"", ")", "feedable_names", "=", "tuple", "(", "sorted", "(", "self", ".", "feedable_kwargs", ".", "keys", "(", ")", ")", ")", "else", ":", "feedable_names", "=", "self", ".", "feedable_kwargs", "if", "not", "isinstance", "(", "feedable_names", ",", "tuple", ")", ":", "raise", "TypeError", "(", "\"Attack.feedable_kwargs should be a tuple, but \"", "\"for subclass \"", "+", "str", "(", "type", "(", "self", ")", ")", "+", "\" it is \"", "+", "str", "(", "self", ".", "feedable_kwargs", ")", "+", "\" of type \"", "+", "str", "(", "type", "(", "self", ".", "feedable_kwargs", ")", ")", ")", "# the set of arguments that are structural properties of the attack", "# if these arguments are different, we must construct a new graph", "fixed", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "k", "in", "self", ".", "structural_kwargs", ")", "# the set of arguments that are passed as placeholders to the graph", "# on each call, and can change without constructing a new graph", "feedable", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "k", "in", "feedable_names", "}", "for", "k", "in", "feedable", ":", "if", "isinstance", "(", "feedable", "[", "k", "]", ",", "(", "float", ",", "int", ")", ")", ":", "feedable", "[", "k", "]", "=", "np", ".", "array", "(", "feedable", "[", "k", "]", ")", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "fixed", "and", "key", "not", "in", "feedable", ":", "raise", "ValueError", "(", "str", "(", "type", "(", "self", ")", ")", "+", "\": Undeclared argument: \"", "+", "key", ")", "feed_arg_type", "=", "arg_type", "(", "feedable_names", ",", "feedable", ")", "if", "not", "all", "(", "isinstance", "(", "value", ",", "collections", ".", "Hashable", ")", "for", "value", "in", "fixed", ".", "values", "(", ")", ")", ":", "# we have received a fixed value that isn't hashable", "# this means we can't cache this graph for later use,", "# and it will have to be discarded later", "hash_key", "=", "None", "else", ":", "# create a unique key for this set of fixed paramaters", "hash_key", "=", "tuple", "(", "sorted", "(", "fixed", ".", "items", "(", ")", ")", ")", "+", "tuple", "(", "[", "feed_arg_type", "]", ")", "return", "fixed", ",", "feedable", ",", "feed_arg_type", ",", "hash_key" ]
Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key
[ "Construct", "the", "inputs", "to", "the", "attack", "graph", "to", "be", "used", "by", "generate_np", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L202-L258
28,487
tensorflow/cleverhans
examples/multigpu_advtrain/evaluator.py
create_adv_by_name
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless a different value is given in kwargs. :param model: an object of Model class :param x: Symbolic input to the attack. :param attack_type: A string that is the name of an attack. :param sess: Tensorflow session. :param dataset: The name of the dataset as a string to use for default params. :param y: (optional) a symbolic variable for the labels. :param kwargs: (optional) additional parameters to be passed to the attack. """ # TODO: black box attacks attack_names = {'FGSM': FastGradientMethod, 'MadryEtAl': MadryEtAl, 'MadryEtAl_y': MadryEtAl, 'MadryEtAl_multigpu': MadryEtAlMultiGPU, 'MadryEtAl_y_multigpu': MadryEtAlMultiGPU } if attack_type not in attack_names: raise Exception('Attack %s not defined.' % attack_type) attack_params_shared = { 'mnist': {'eps': .3, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1., 'nb_iter': 40}, 'cifar10': {'eps': 8./255, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1., 'nb_iter': 20} } with tf.variable_scope(attack_type): attack_class = attack_names[attack_type] attack = attack_class(model, sess=sess) # Extract feedable and structural keyword arguments from kwargs fd_kwargs = attack.feedable_kwargs.keys() + attack.structural_kwargs params = attack_params_shared[dataset].copy() params.update({k: v for k, v in kwargs.items() if v is not None}) params = {k: v for k, v in params.items() if k in fd_kwargs} if '_y' in attack_type: params['y'] = y logging.info(params) adv_x = attack.generate(x, **params) return adv_x
python
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless a different value is given in kwargs. :param model: an object of Model class :param x: Symbolic input to the attack. :param attack_type: A string that is the name of an attack. :param sess: Tensorflow session. :param dataset: The name of the dataset as a string to use for default params. :param y: (optional) a symbolic variable for the labels. :param kwargs: (optional) additional parameters to be passed to the attack. """ # TODO: black box attacks attack_names = {'FGSM': FastGradientMethod, 'MadryEtAl': MadryEtAl, 'MadryEtAl_y': MadryEtAl, 'MadryEtAl_multigpu': MadryEtAlMultiGPU, 'MadryEtAl_y_multigpu': MadryEtAlMultiGPU } if attack_type not in attack_names: raise Exception('Attack %s not defined.' % attack_type) attack_params_shared = { 'mnist': {'eps': .3, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1., 'nb_iter': 40}, 'cifar10': {'eps': 8./255, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1., 'nb_iter': 20} } with tf.variable_scope(attack_type): attack_class = attack_names[attack_type] attack = attack_class(model, sess=sess) # Extract feedable and structural keyword arguments from kwargs fd_kwargs = attack.feedable_kwargs.keys() + attack.structural_kwargs params = attack_params_shared[dataset].copy() params.update({k: v for k, v in kwargs.items() if v is not None}) params = {k: v for k, v in params.items() if k in fd_kwargs} if '_y' in attack_type: params['y'] = y logging.info(params) adv_x = attack.generate(x, **params) return adv_x
[ "def", "create_adv_by_name", "(", "model", ",", "x", ",", "attack_type", ",", "sess", ",", "dataset", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# TODO: black box attacks", "attack_names", "=", "{", "'FGSM'", ":", "FastGradientMethod", ",", "'MadryEtAl'", ":", "MadryEtAl", ",", "'MadryEtAl_y'", ":", "MadryEtAl", ",", "'MadryEtAl_multigpu'", ":", "MadryEtAlMultiGPU", ",", "'MadryEtAl_y_multigpu'", ":", "MadryEtAlMultiGPU", "}", "if", "attack_type", "not", "in", "attack_names", ":", "raise", "Exception", "(", "'Attack %s not defined.'", "%", "attack_type", ")", "attack_params_shared", "=", "{", "'mnist'", ":", "{", "'eps'", ":", ".3", ",", "'eps_iter'", ":", "0.01", ",", "'clip_min'", ":", "0.", ",", "'clip_max'", ":", "1.", ",", "'nb_iter'", ":", "40", "}", ",", "'cifar10'", ":", "{", "'eps'", ":", "8.", "/", "255", ",", "'eps_iter'", ":", "0.01", ",", "'clip_min'", ":", "0.", ",", "'clip_max'", ":", "1.", ",", "'nb_iter'", ":", "20", "}", "}", "with", "tf", ".", "variable_scope", "(", "attack_type", ")", ":", "attack_class", "=", "attack_names", "[", "attack_type", "]", "attack", "=", "attack_class", "(", "model", ",", "sess", "=", "sess", ")", "# Extract feedable and structural keyword arguments from kwargs", "fd_kwargs", "=", "attack", ".", "feedable_kwargs", ".", "keys", "(", ")", "+", "attack", ".", "structural_kwargs", "params", "=", "attack_params_shared", "[", "dataset", "]", ".", "copy", "(", ")", "params", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", ")", "params", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "if", "k", "in", "fd_kwargs", "}", "if", "'_y'", "in", "attack_type", ":", "params", "[", "'y'", "]", "=", "y", "logging", ".", "info", "(", "params", ")", "adv_x", "=", "attack", ".", "generate", "(", "x", ",", "*", "*", "params", ")", "return", "adv_x" ]
Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless a different value is given in kwargs. :param model: an object of Model class :param x: Symbolic input to the attack. :param attack_type: A string that is the name of an attack. :param sess: Tensorflow session. :param dataset: The name of the dataset as a string to use for default params. :param y: (optional) a symbolic variable for the labels. :param kwargs: (optional) additional parameters to be passed to the attack.
[ "Creates", "the", "symbolic", "graph", "of", "an", "adversarial", "example", "given", "the", "name", "of", "an", "attack", ".", "Simplifies", "creating", "the", "symbolic", "graph", "of", "an", "attack", "by", "defining", "dataset", "-", "specific", "parameters", ".", "Dataset", "-", "specific", "default", "parameters", "are", "used", "unless", "a", "different", "value", "is", "given", "in", "kwargs", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L16-L66
28,488
tensorflow/cleverhans
examples/multigpu_advtrain/evaluator.py
Evaluator.log_value
def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed. """ logging.info('%s (%s): %.4f' % (desc, tag, val)) self.summary.value.add(tag=tag, simple_value=val)
python
def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed. """ logging.info('%s (%s): %.4f' % (desc, tag, val)) self.summary.value.add(tag=tag, simple_value=val)
[ "def", "log_value", "(", "self", ",", "tag", ",", "val", ",", "desc", "=", "''", ")", ":", "logging", ".", "info", "(", "'%s (%s): %.4f'", "%", "(", "desc", ",", "tag", ",", "val", ")", ")", "self", ".", "summary", ".", "value", ".", "add", "(", "tag", "=", "tag", ",", "simple_value", "=", "val", ")" ]
Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed.
[ "Log", "values", "to", "standard", "output", "and", "Tensorflow", "summary", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L127-L136
28,489
tensorflow/cleverhans
examples/multigpu_advtrain/evaluator.py
Evaluator.eval_advs
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial example. :param X_test: NumPy array of test set inputs. :param Y_test: NumPy array of test set labels. :param att_type: name of the attack. """ end = (len(X_test) // self.batch_size) * self.batch_size if self.hparams.fast_tests: end = 10*self.batch_size acc = model_eval(self.sess, x, y, preds_adv, X_test[:end], Y_test[:end], args=self.eval_params) self.log_value('test_accuracy_%s' % att_type, acc, 'Test accuracy on adversarial examples') return acc
python
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial example. :param X_test: NumPy array of test set inputs. :param Y_test: NumPy array of test set labels. :param att_type: name of the attack. """ end = (len(X_test) // self.batch_size) * self.batch_size if self.hparams.fast_tests: end = 10*self.batch_size acc = model_eval(self.sess, x, y, preds_adv, X_test[:end], Y_test[:end], args=self.eval_params) self.log_value('test_accuracy_%s' % att_type, acc, 'Test accuracy on adversarial examples') return acc
[ "def", "eval_advs", "(", "self", ",", "x", ",", "y", ",", "preds_adv", ",", "X_test", ",", "Y_test", ",", "att_type", ")", ":", "end", "=", "(", "len", "(", "X_test", ")", "//", "self", ".", "batch_size", ")", "*", "self", ".", "batch_size", "if", "self", ".", "hparams", ".", "fast_tests", ":", "end", "=", "10", "*", "self", ".", "batch_size", "acc", "=", "model_eval", "(", "self", ".", "sess", ",", "x", ",", "y", ",", "preds_adv", ",", "X_test", "[", ":", "end", "]", ",", "Y_test", "[", ":", "end", "]", ",", "args", "=", "self", ".", "eval_params", ")", "self", ".", "log_value", "(", "'test_accuracy_%s'", "%", "att_type", ",", "acc", ",", "'Test accuracy on adversarial examples'", ")", "return", "acc" ]
Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial example. :param X_test: NumPy array of test set inputs. :param Y_test: NumPy array of test set labels. :param att_type: name of the attack.
[ "Evaluate", "the", "accuracy", "of", "the", "model", "on", "adversarial", "examples" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L138-L159
28,490
tensorflow/cleverhans
examples/multigpu_advtrain/evaluator.py
Evaluator.eval_multi
def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """ sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summary = tf.Summary() report = {} # Evaluate on train set subsample_factor = 100 X_train_subsampled = X_train[::subsample_factor] Y_train_subsampled = Y_train[::subsample_factor] acc_train = model_eval(sess, x, y, preds, X_train_subsampled, Y_train_subsampled, args=self.eval_params) self.log_value('train_accuracy_subsampled', acc_train, 'Clean accuracy, subsampled train') report['train'] = acc_train # Evaluate on the test set acc = model_eval(sess, x, y, preds, X_test, Y_test, args=self.eval_params) self.log_value('test_accuracy_natural', acc, 'Clean accuracy, natural test') report['test'] = acc # Evaluate against adversarial attacks if self.epoch % self.hparams.eval_iters == 0: for att_type in self.attack_type_test: _, preds_adv = self.attacks[att_type] acc = self.eval_advs(x, y, preds_adv, X_test, Y_test, att_type) report[att_type] = acc if self.writer: writer.add_summary(self.summary, self.epoch) # Add examples of adversarial examples to the summary if self.writer and self.epoch % 20 == 0 and self.sum_op is not None: sm_val = self.sess.run(self.sum_op, feed_dict={x: X_test[:self.batch_size], y: Y_test[:self.batch_size]}) if self.writer: writer.add_summary(sm_val) self.epoch += 1 if inc_epoch else 0 return report
python
def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """ sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summary = tf.Summary() report = {} # Evaluate on train set subsample_factor = 100 X_train_subsampled = X_train[::subsample_factor] Y_train_subsampled = Y_train[::subsample_factor] acc_train = model_eval(sess, x, y, preds, X_train_subsampled, Y_train_subsampled, args=self.eval_params) self.log_value('train_accuracy_subsampled', acc_train, 'Clean accuracy, subsampled train') report['train'] = acc_train # Evaluate on the test set acc = model_eval(sess, x, y, preds, X_test, Y_test, args=self.eval_params) self.log_value('test_accuracy_natural', acc, 'Clean accuracy, natural test') report['test'] = acc # Evaluate against adversarial attacks if self.epoch % self.hparams.eval_iters == 0: for att_type in self.attack_type_test: _, preds_adv = self.attacks[att_type] acc = self.eval_advs(x, y, preds_adv, X_test, Y_test, att_type) report[att_type] = acc if self.writer: writer.add_summary(self.summary, self.epoch) # Add examples of adversarial examples to the summary if self.writer and self.epoch % 20 == 0 and self.sum_op is not None: sm_val = self.sess.run(self.sum_op, feed_dict={x: X_test[:self.batch_size], y: Y_test[:self.batch_size]}) if self.writer: writer.add_summary(sm_val) self.epoch += 1 if inc_epoch else 0 return report
[ "def", "eval_multi", "(", "self", ",", "inc_epoch", "=", "True", ")", ":", "sess", "=", "self", ".", "sess", "preds", "=", "self", ".", "preds", "x", "=", "self", ".", "x_pre", "y", "=", "self", ".", "y", "X_train", "=", "self", ".", "X_train", "Y_train", "=", "self", ".", "Y_train", "X_test", "=", "self", ".", "X_test", "Y_test", "=", "self", ".", "Y_test", "writer", "=", "self", ".", "writer", "self", ".", "summary", "=", "tf", ".", "Summary", "(", ")", "report", "=", "{", "}", "# Evaluate on train set", "subsample_factor", "=", "100", "X_train_subsampled", "=", "X_train", "[", ":", ":", "subsample_factor", "]", "Y_train_subsampled", "=", "Y_train", "[", ":", ":", "subsample_factor", "]", "acc_train", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "preds", ",", "X_train_subsampled", ",", "Y_train_subsampled", ",", "args", "=", "self", ".", "eval_params", ")", "self", ".", "log_value", "(", "'train_accuracy_subsampled'", ",", "acc_train", ",", "'Clean accuracy, subsampled train'", ")", "report", "[", "'train'", "]", "=", "acc_train", "# Evaluate on the test set", "acc", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "preds", ",", "X_test", ",", "Y_test", ",", "args", "=", "self", ".", "eval_params", ")", "self", ".", "log_value", "(", "'test_accuracy_natural'", ",", "acc", ",", "'Clean accuracy, natural test'", ")", "report", "[", "'test'", "]", "=", "acc", "# Evaluate against adversarial attacks", "if", "self", ".", "epoch", "%", "self", ".", "hparams", ".", "eval_iters", "==", "0", ":", "for", "att_type", "in", "self", ".", "attack_type_test", ":", "_", ",", "preds_adv", "=", "self", ".", "attacks", "[", "att_type", "]", "acc", "=", "self", ".", "eval_advs", "(", "x", ",", "y", ",", "preds_adv", ",", "X_test", ",", "Y_test", ",", "att_type", ")", "report", "[", "att_type", "]", "=", "acc", "if", "self", ".", "writer", ":", "writer", ".", "add_summary", "(", "self", ".", "summary", ",", "self", ".", "epoch", ")", "# Add examples of adversarial examples to the summary", "if", "self", ".", "writer", "and", "self", ".", "epoch", "%", "20", "==", "0", "and", "self", ".", "sum_op", "is", "not", "None", ":", "sm_val", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "sum_op", ",", "feed_dict", "=", "{", "x", ":", "X_test", "[", ":", "self", ".", "batch_size", "]", ",", "y", ":", "Y_test", "[", ":", "self", ".", "batch_size", "]", "}", ")", "if", "self", ".", "writer", ":", "writer", ".", "add_summary", "(", "sm_val", ")", "self", ".", "epoch", "+=", "1", "if", "inc_epoch", "else", "0", "return", "report" ]
Run the evaluation on multiple attacks.
[ "Run", "the", "evaluation", "on", "multiple", "attacks", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L161-L215
28,491
tensorflow/cleverhans
cleverhans/compat.py
_wrap
def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """ def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. " " This function was originally needed as a compatibility layer for old versions of tensorflow, " " but support for those versions has now been dropped.") return f(*args, **kwargs) return wrapper
python
def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """ def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. " " This function was originally needed as a compatibility layer for old versions of tensorflow, " " but support for those versions has now been dropped.") return f(*args, **kwargs) return wrapper
[ "def", "_wrap", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Issues a deprecation warning and passes through the arguments.\n \"\"\"", "warnings", ".", "warn", "(", "str", "(", "f", ")", "+", "\" is deprecated. Switch to calling the equivalent function in tensorflow. \"", "\" This function was originally needed as a compatibility layer for old versions of tensorflow, \"", "\" but support for those versions has now been dropped.\"", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Wraps a callable `f` in a function that warns that the function is deprecated.
[ "Wraps", "a", "callable", "f", "in", "a", "function", "that", "warns", "that", "the", "function", "is", "deprecated", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L14-L26
28,492
tensorflow/cleverhans
cleverhans/compat.py
softmax_cross_entropy_with_logits
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning """ # Make sure that all arguments were passed as named arguments. if sentinel is not None: name = "softmax_cross_entropy_with_logits" raise ValueError("Only call `%s` with " "named arguments (labels=..., logits=..., ...)" % name) if labels is None or logits is None: raise ValueError("Both labels and logits must be provided.") try: f = tf.nn.softmax_cross_entropy_with_logits_v2 except AttributeError: raise RuntimeError("This version of TensorFlow is no longer supported. See cleverhans/README.md") labels = tf.stop_gradient(labels) loss = f(labels=labels, logits=logits, dim=dim) return loss
python
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning """ # Make sure that all arguments were passed as named arguments. if sentinel is not None: name = "softmax_cross_entropy_with_logits" raise ValueError("Only call `%s` with " "named arguments (labels=..., logits=..., ...)" % name) if labels is None or logits is None: raise ValueError("Both labels and logits must be provided.") try: f = tf.nn.softmax_cross_entropy_with_logits_v2 except AttributeError: raise RuntimeError("This version of TensorFlow is no longer supported. See cleverhans/README.md") labels = tf.stop_gradient(labels) loss = f(labels=labels, logits=logits, dim=dim) return loss
[ "def", "softmax_cross_entropy_with_logits", "(", "sentinel", "=", "None", ",", "labels", "=", "None", ",", "logits", "=", "None", ",", "dim", "=", "-", "1", ")", ":", "# Make sure that all arguments were passed as named arguments.", "if", "sentinel", "is", "not", "None", ":", "name", "=", "\"softmax_cross_entropy_with_logits\"", "raise", "ValueError", "(", "\"Only call `%s` with \"", "\"named arguments (labels=..., logits=..., ...)\"", "%", "name", ")", "if", "labels", "is", "None", "or", "logits", "is", "None", ":", "raise", "ValueError", "(", "\"Both labels and logits must be provided.\"", ")", "try", ":", "f", "=", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits_v2", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"This version of TensorFlow is no longer supported. See cleverhans/README.md\"", ")", "labels", "=", "tf", ".", "stop_gradient", "(", "labels", ")", "loss", "=", "f", "(", "labels", "=", "labels", ",", "logits", "=", "logits", ",", "dim", "=", "dim", ")", "return", "loss" ]
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning
[ "Wrapper", "around", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits_v2", "to", "handle", "deprecated", "warning" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L56-L81
28,493
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
enforce_epsilon_and_compute_hash
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with generated adversarial images output_dir: directory where to copy result epsilon: size of perturbation Returns: dictionary with mapping form image ID to hash. """ dataset_images = [f for f in os.listdir(dataset_batch_dir) if f.endswith('.png')] image_hashes = {} resize_warning = False for img_name in dataset_images: if not os.path.exists(os.path.join(adv_dir, img_name)): logging.warning('Image %s not found in the output', img_name) continue image = np.array( Image.open(os.path.join(dataset_batch_dir, img_name)).convert('RGB')) image = image.astype('int32') image_max_clip = np.clip(image + epsilon, 0, 255).astype('uint8') image_min_clip = np.clip(image - epsilon, 0, 255).astype('uint8') # load and resize adversarial image if needed adv_image = Image.open(os.path.join(adv_dir, img_name)).convert('RGB') # Image.size is reversed compared to np.array.shape if adv_image.size[::-1] != image.shape[:2]: resize_warning = True adv_image = adv_image.resize((image.shape[1], image.shape[0]), Image.BICUBIC) adv_image = np.array(adv_image) clipped_adv_image = np.clip(adv_image, image_min_clip, image_max_clip) Image.fromarray(clipped_adv_image).save(os.path.join(output_dir, img_name)) # compute hash image_hashes[img_name[:-4]] = hashlib.sha1( clipped_adv_image.view(np.uint8)).hexdigest() if resize_warning: logging.warning('One or more adversarial images had incorrect size') return image_hashes
python
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with generated adversarial images output_dir: directory where to copy result epsilon: size of perturbation Returns: dictionary with mapping form image ID to hash. """ dataset_images = [f for f in os.listdir(dataset_batch_dir) if f.endswith('.png')] image_hashes = {} resize_warning = False for img_name in dataset_images: if not os.path.exists(os.path.join(adv_dir, img_name)): logging.warning('Image %s not found in the output', img_name) continue image = np.array( Image.open(os.path.join(dataset_batch_dir, img_name)).convert('RGB')) image = image.astype('int32') image_max_clip = np.clip(image + epsilon, 0, 255).astype('uint8') image_min_clip = np.clip(image - epsilon, 0, 255).astype('uint8') # load and resize adversarial image if needed adv_image = Image.open(os.path.join(adv_dir, img_name)).convert('RGB') # Image.size is reversed compared to np.array.shape if adv_image.size[::-1] != image.shape[:2]: resize_warning = True adv_image = adv_image.resize((image.shape[1], image.shape[0]), Image.BICUBIC) adv_image = np.array(adv_image) clipped_adv_image = np.clip(adv_image, image_min_clip, image_max_clip) Image.fromarray(clipped_adv_image).save(os.path.join(output_dir, img_name)) # compute hash image_hashes[img_name[:-4]] = hashlib.sha1( clipped_adv_image.view(np.uint8)).hexdigest() if resize_warning: logging.warning('One or more adversarial images had incorrect size') return image_hashes
[ "def", "enforce_epsilon_and_compute_hash", "(", "dataset_batch_dir", ",", "adv_dir", ",", "output_dir", ",", "epsilon", ")", ":", "dataset_images", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "dataset_batch_dir", ")", "if", "f", ".", "endswith", "(", "'.png'", ")", "]", "image_hashes", "=", "{", "}", "resize_warning", "=", "False", "for", "img_name", "in", "dataset_images", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "adv_dir", ",", "img_name", ")", ")", ":", "logging", ".", "warning", "(", "'Image %s not found in the output'", ",", "img_name", ")", "continue", "image", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "dataset_batch_dir", ",", "img_name", ")", ")", ".", "convert", "(", "'RGB'", ")", ")", "image", "=", "image", ".", "astype", "(", "'int32'", ")", "image_max_clip", "=", "np", ".", "clip", "(", "image", "+", "epsilon", ",", "0", ",", "255", ")", ".", "astype", "(", "'uint8'", ")", "image_min_clip", "=", "np", ".", "clip", "(", "image", "-", "epsilon", ",", "0", ",", "255", ")", ".", "astype", "(", "'uint8'", ")", "# load and resize adversarial image if needed", "adv_image", "=", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "adv_dir", ",", "img_name", ")", ")", ".", "convert", "(", "'RGB'", ")", "# Image.size is reversed compared to np.array.shape", "if", "adv_image", ".", "size", "[", ":", ":", "-", "1", "]", "!=", "image", ".", "shape", "[", ":", "2", "]", ":", "resize_warning", "=", "True", "adv_image", "=", "adv_image", ".", "resize", "(", "(", "image", ".", "shape", "[", "1", "]", ",", "image", ".", "shape", "[", "0", "]", ")", ",", "Image", ".", "BICUBIC", ")", "adv_image", "=", "np", ".", "array", "(", "adv_image", ")", "clipped_adv_image", "=", "np", ".", "clip", "(", "adv_image", ",", "image_min_clip", ",", "image_max_clip", ")", "Image", ".", "fromarray", "(", "clipped_adv_image", ")", ".", "save", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "img_name", ")", ")", "# compute hash", "image_hashes", "[", "img_name", "[", ":", "-", "4", "]", "]", "=", "hashlib", ".", "sha1", "(", "clipped_adv_image", ".", "view", "(", "np", ".", "uint8", ")", ")", ".", "hexdigest", "(", ")", "if", "resize_warning", ":", "logging", ".", "warning", "(", "'One or more adversarial images had incorrect size'", ")", "return", "image_hashes" ]
Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with generated adversarial images output_dir: directory where to copy result epsilon: size of perturbation Returns: dictionary with mapping form image ID to hash.
[ "Enforces", "size", "of", "perturbation", "on", "images", "and", "compute", "hashes", "for", "all", "images", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L81-L124
28,494
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
download_dataset
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images target_dir: target directory, should exist and be empty local_dataset_copy: directory with local dataset copy, if local copy is available then images will be takes from there instead of Cloud Storage Data in the target directory will be organized into subdirectories by batches, thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png" where BATCH_ID - ID of the batch (key of image_batches.data), IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images']) """ for batch_id, batch_value in iteritems(image_batches.data): batch_dir = os.path.join(target_dir, batch_id) os.mkdir(batch_dir) for image_id, image_val in iteritems(batch_value['images']): dst_filename = os.path.join(batch_dir, image_id + '.png') # try to use local copy first if local_dataset_copy: local_filename = os.path.join(local_dataset_copy, os.path.basename(image_val['image_path'])) if os.path.exists(local_filename): shutil.copyfile(local_filename, dst_filename) continue # download image from cloud cloud_path = ('gs://' + storage_client.bucket_name + '/' + image_val['image_path']) if not os.path.exists(dst_filename): subprocess.call(['gsutil', 'cp', cloud_path, dst_filename])
python
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images target_dir: target directory, should exist and be empty local_dataset_copy: directory with local dataset copy, if local copy is available then images will be takes from there instead of Cloud Storage Data in the target directory will be organized into subdirectories by batches, thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png" where BATCH_ID - ID of the batch (key of image_batches.data), IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images']) """ for batch_id, batch_value in iteritems(image_batches.data): batch_dir = os.path.join(target_dir, batch_id) os.mkdir(batch_dir) for image_id, image_val in iteritems(batch_value['images']): dst_filename = os.path.join(batch_dir, image_id + '.png') # try to use local copy first if local_dataset_copy: local_filename = os.path.join(local_dataset_copy, os.path.basename(image_val['image_path'])) if os.path.exists(local_filename): shutil.copyfile(local_filename, dst_filename) continue # download image from cloud cloud_path = ('gs://' + storage_client.bucket_name + '/' + image_val['image_path']) if not os.path.exists(dst_filename): subprocess.call(['gsutil', 'cp', cloud_path, dst_filename])
[ "def", "download_dataset", "(", "storage_client", ",", "image_batches", ",", "target_dir", ",", "local_dataset_copy", "=", "None", ")", ":", "for", "batch_id", ",", "batch_value", "in", "iteritems", "(", "image_batches", ".", "data", ")", ":", "batch_dir", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "batch_id", ")", "os", ".", "mkdir", "(", "batch_dir", ")", "for", "image_id", ",", "image_val", "in", "iteritems", "(", "batch_value", "[", "'images'", "]", ")", ":", "dst_filename", "=", "os", ".", "path", ".", "join", "(", "batch_dir", ",", "image_id", "+", "'.png'", ")", "# try to use local copy first", "if", "local_dataset_copy", ":", "local_filename", "=", "os", ".", "path", ".", "join", "(", "local_dataset_copy", ",", "os", ".", "path", ".", "basename", "(", "image_val", "[", "'image_path'", "]", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "local_filename", ")", ":", "shutil", ".", "copyfile", "(", "local_filename", ",", "dst_filename", ")", "continue", "# download image from cloud", "cloud_path", "=", "(", "'gs://'", "+", "storage_client", ".", "bucket_name", "+", "'/'", "+", "image_val", "[", "'image_path'", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dst_filename", ")", ":", "subprocess", ".", "call", "(", "[", "'gsutil'", ",", "'cp'", ",", "cloud_path", ",", "dst_filename", "]", ")" ]
Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images target_dir: target directory, should exist and be empty local_dataset_copy: directory with local dataset copy, if local copy is available then images will be takes from there instead of Cloud Storage Data in the target directory will be organized into subdirectories by batches, thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png" where BATCH_ID - ID of the batch (key of image_batches.data), IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images'])
[ "Downloads", "dataset", "organize", "it", "by", "batches", "and", "rename", "images", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L127-L159
28,495
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
DatasetMetadata.save_target_classes_for_batch
def save_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of ImageBatchesBase with dataset batches batch_id: dataset batch ID """ images = image_batches.data[batch_id]['images'] with open(filename, 'w') as f: for image_id, image_val in iteritems(images): target_class = self.get_target_class(image_val['dataset_image_id']) f.write('{0}.png,{1}\n'.format(image_id, target_class))
python
def save_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of ImageBatchesBase with dataset batches batch_id: dataset batch ID """ images = image_batches.data[batch_id]['images'] with open(filename, 'w') as f: for image_id, image_val in iteritems(images): target_class = self.get_target_class(image_val['dataset_image_id']) f.write('{0}.png,{1}\n'.format(image_id, target_class))
[ "def", "save_target_classes_for_batch", "(", "self", ",", "filename", ",", "image_batches", ",", "batch_id", ")", ":", "images", "=", "image_batches", ".", "data", "[", "batch_id", "]", "[", "'images'", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "image_id", ",", "image_val", "in", "iteritems", "(", "images", ")", ":", "target_class", "=", "self", ".", "get_target_class", "(", "image_val", "[", "'dataset_image_id'", "]", ")", "f", ".", "write", "(", "'{0}.png,{1}\\n'", ".", "format", "(", "image_id", ",", "target_class", ")", ")" ]
Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of ImageBatchesBase with dataset batches batch_id: dataset batch ID
[ "Saves", "file", "with", "target", "class", "for", "given", "dataset", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L63-L78
28,496
tensorflow/cleverhans
cleverhans/experimental/certification/optimization.py
Optimization.tf_min_eig_vec
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) return tf.reshape( eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
python
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) return tf.reshape( eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
[ "def", "tf_min_eig_vec", "(", "self", ")", ":", "# Full eigen decomposition requires the explicit psd matrix M", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", "self_adjoint_eig", "(", "matrix_m", ")", "index", "=", "tf", ".", "argmin", "(", "eig_vals", ")", "return", "tf", ".", "reshape", "(", "eig_vectors", "[", ":", ",", "index", "]", ",", "shape", "=", "[", "eig_vectors", ".", "shape", "[", "0", "]", ".", "value", ",", "1", "]", ")" ]
Function for min eigen vector using tf's full eigen decomposition.
[ "Function", "for", "min", "eigen", "vector", "using", "tf", "s", "full", "eigen", "decomposition", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L56-L63
28,497
tensorflow/cleverhans
cleverhans/experimental/certification/optimization.py
Optimization.tf_smooth_eig_vec
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_placeholder)) scaling_factor = tf.reduce_sum(exp_eig_vals) # Multiplying each eig vector by exponential of corresponding eig value # Scaling factor normalizes the vector to be unit norm eig_vec_smooth = tf.divide( tf.matmul(eig_vectors, tf.diag(tf.sqrt(exp_eig_vals))), tf.sqrt(scaling_factor)) return tf.reshape( tf.reduce_sum(eig_vec_smooth, axis=1), shape=[eig_vec_smooth.shape[0].value, 1])
python
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_placeholder)) scaling_factor = tf.reduce_sum(exp_eig_vals) # Multiplying each eig vector by exponential of corresponding eig value # Scaling factor normalizes the vector to be unit norm eig_vec_smooth = tf.divide( tf.matmul(eig_vectors, tf.diag(tf.sqrt(exp_eig_vals))), tf.sqrt(scaling_factor)) return tf.reshape( tf.reduce_sum(eig_vec_smooth, axis=1), shape=[eig_vec_smooth.shape[0].value, 1])
[ "def", "tf_smooth_eig_vec", "(", "self", ")", ":", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "# Easier to think in terms of max so negating the matrix", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", "self_adjoint_eig", "(", "-", "matrix_m", ")", "exp_eig_vals", "=", "tf", ".", "exp", "(", "tf", ".", "divide", "(", "eig_vals", ",", "self", ".", "smooth_placeholder", ")", ")", "scaling_factor", "=", "tf", ".", "reduce_sum", "(", "exp_eig_vals", ")", "# Multiplying each eig vector by exponential of corresponding eig value", "# Scaling factor normalizes the vector to be unit norm", "eig_vec_smooth", "=", "tf", ".", "divide", "(", "tf", ".", "matmul", "(", "eig_vectors", ",", "tf", ".", "diag", "(", "tf", ".", "sqrt", "(", "exp_eig_vals", ")", ")", ")", ",", "tf", ".", "sqrt", "(", "scaling_factor", ")", ")", "return", "tf", ".", "reshape", "(", "tf", ".", "reduce_sum", "(", "eig_vec_smooth", ",", "axis", "=", "1", ")", ",", "shape", "=", "[", "eig_vec_smooth", ".", "shape", "[", "0", "]", ".", "value", ",", "1", "]", ")" ]
Function that returns smoothed version of min eigen vector.
[ "Function", "that", "returns", "smoothed", "version", "of", "min", "eigen", "vector", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L65-L79
28,498
tensorflow/cleverhans
cleverhans/experimental/certification/optimization.py
Optimization.get_min_eig_vec_proxy
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if use_tf_eig: # If smoothness parameter is too small, essentially no smoothing # Just output the eigen vector corresponding to min return tf.cond(self.smooth_placeholder < 1E-8, self.tf_min_eig_vec, self.tf_smooth_eig_vec) # Using autograph to automatically handle # the control flow of minimum_eigen_vector min_eigen_tf = autograph.to_graph(utils.minimum_eigen_vector) def _vector_prod_fn(x): return self.dual_object.get_psd_product(x) estimated_eigen_vector = min_eigen_tf( x=self.eig_init_vec_placeholder, num_steps=self.eig_num_iter_placeholder, learning_rate=self.params['eig_learning_rate'], vector_prod_fn=_vector_prod_fn) return estimated_eigen_vector
python
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if use_tf_eig: # If smoothness parameter is too small, essentially no smoothing # Just output the eigen vector corresponding to min return tf.cond(self.smooth_placeholder < 1E-8, self.tf_min_eig_vec, self.tf_smooth_eig_vec) # Using autograph to automatically handle # the control flow of minimum_eigen_vector min_eigen_tf = autograph.to_graph(utils.minimum_eigen_vector) def _vector_prod_fn(x): return self.dual_object.get_psd_product(x) estimated_eigen_vector = min_eigen_tf( x=self.eig_init_vec_placeholder, num_steps=self.eig_num_iter_placeholder, learning_rate=self.params['eig_learning_rate'], vector_prod_fn=_vector_prod_fn) return estimated_eigen_vector
[ "def", "get_min_eig_vec_proxy", "(", "self", ",", "use_tf_eig", "=", "False", ")", ":", "if", "use_tf_eig", ":", "# If smoothness parameter is too small, essentially no smoothing", "# Just output the eigen vector corresponding to min", "return", "tf", ".", "cond", "(", "self", ".", "smooth_placeholder", "<", "1E-8", ",", "self", ".", "tf_min_eig_vec", ",", "self", ".", "tf_smooth_eig_vec", ")", "# Using autograph to automatically handle", "# the control flow of minimum_eigen_vector", "min_eigen_tf", "=", "autograph", ".", "to_graph", "(", "utils", ".", "minimum_eigen_vector", ")", "def", "_vector_prod_fn", "(", "x", ")", ":", "return", "self", ".", "dual_object", ".", "get_psd_product", "(", "x", ")", "estimated_eigen_vector", "=", "min_eigen_tf", "(", "x", "=", "self", ".", "eig_init_vec_placeholder", ",", "num_steps", "=", "self", ".", "eig_num_iter_placeholder", ",", "learning_rate", "=", "self", ".", "params", "[", "'eig_learning_rate'", "]", ",", "vector_prod_fn", "=", "_vector_prod_fn", ")", "return", "estimated_eigen_vector" ]
Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
[ "Computes", "the", "min", "eigen", "value", "and", "corresponding", "vector", "of", "matrix", "M", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L81-L109
28,499
tensorflow/cleverhans
cleverhans/experimental/certification/optimization.py
Optimization.get_scipy_eig_vec
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR', tol=1E-4) min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1]) return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val else: dim = self.dual_object.matrix_m_dimension input_vector = tf.placeholder(tf.float32, shape=(dim, 1)) output_vector = self.dual_object.get_psd_product(input_vector) def np_vector_prod_fn(np_vector): np_vector = np.reshape(np_vector, [-1, 1]) output_np_vector = self.sess.run(output_vector, feed_dict={input_vector:np_vector}) return output_np_vector linear_operator = LinearOperator((dim, dim), matvec=np_vector_prod_fn) # Performing shift invert scipy operation when eig val estimate is available min_eig_vec_val, estimated_eigen_vector = eigs(linear_operator, k=1, which='SR', tol=1E-4) min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1]) return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
python
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR', tol=1E-4) min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1]) return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val else: dim = self.dual_object.matrix_m_dimension input_vector = tf.placeholder(tf.float32, shape=(dim, 1)) output_vector = self.dual_object.get_psd_product(input_vector) def np_vector_prod_fn(np_vector): np_vector = np.reshape(np_vector, [-1, 1]) output_np_vector = self.sess.run(output_vector, feed_dict={input_vector:np_vector}) return output_np_vector linear_operator = LinearOperator((dim, dim), matvec=np_vector_prod_fn) # Performing shift invert scipy operation when eig val estimate is available min_eig_vec_val, estimated_eigen_vector = eigs(linear_operator, k=1, which='SR', tol=1E-4) min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1]) return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
[ "def", "get_scipy_eig_vec", "(", "self", ")", ":", "if", "not", "self", ".", "params", "[", "'has_conv'", "]", ":", "matrix_m", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "dual_object", ".", "matrix_m", ")", "min_eig_vec_val", ",", "estimated_eigen_vector", "=", "eigs", "(", "matrix_m", ",", "k", "=", "1", ",", "which", "=", "'SR'", ",", "tol", "=", "1E-4", ")", "min_eig_vec_val", "=", "np", ".", "reshape", "(", "np", ".", "real", "(", "min_eig_vec_val", ")", ",", "[", "1", ",", "1", "]", ")", "return", "np", ".", "reshape", "(", "estimated_eigen_vector", ",", "[", "-", "1", ",", "1", "]", ")", ",", "min_eig_vec_val", "else", ":", "dim", "=", "self", ".", "dual_object", ".", "matrix_m_dimension", "input_vector", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "dim", ",", "1", ")", ")", "output_vector", "=", "self", ".", "dual_object", ".", "get_psd_product", "(", "input_vector", ")", "def", "np_vector_prod_fn", "(", "np_vector", ")", ":", "np_vector", "=", "np", ".", "reshape", "(", "np_vector", ",", "[", "-", "1", ",", "1", "]", ")", "output_np_vector", "=", "self", ".", "sess", ".", "run", "(", "output_vector", ",", "feed_dict", "=", "{", "input_vector", ":", "np_vector", "}", ")", "return", "output_np_vector", "linear_operator", "=", "LinearOperator", "(", "(", "dim", ",", "dim", ")", ",", "matvec", "=", "np_vector_prod_fn", ")", "# Performing shift invert scipy operation when eig val estimate is available", "min_eig_vec_val", ",", "estimated_eigen_vector", "=", "eigs", "(", "linear_operator", ",", "k", "=", "1", ",", "which", "=", "'SR'", ",", "tol", "=", "1E-4", ")", "min_eig_vec_val", "=", "np", ".", "reshape", "(", "np", ".", "real", "(", "min_eig_vec_val", ")", ",", "[", "1", ",", "1", "]", ")", "return", "np", ".", "reshape", "(", "estimated_eigen_vector", ",", "[", "-", "1", ",", "1", "]", ")", ",", "min_eig_vec_val" ]
Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
[ "Computes", "scipy", "estimate", "of", "min", "eigenvalue", "for", "matrix", "M", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L111-L138