code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def print_segments(segments_response): """Prints all the segment info in the Segments collection. Args: segments_response: The response object returned from querying the Segments collection. """ print("------ Segments Collection -------") print_pagination_info(segments_response) ...
Prints all the segment info in the Segments collection. Args: segments_response: The response object returned from querying the Segments collection.
print_segments
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_pagination_info(management_response): """Prints common pagination details. Args: management_response: The common reponse object for each collection in the Management API. """ print("Items per page = %s" % management_response.get("itemsPerPage")) print("Total Results = %s...
Prints common pagination details. Args: management_response: The common reponse object for each collection in the Management API.
print_pagination_info
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def access_settings(service, groupId, settings): """Retrieves a group's settings and updates the access permissions to it. Args: service: object service for the Group Settings API. groupId: string identifier of the group@domain. settings: dictionary key-value pairs of properties of group. ...
Retrieves a group's settings and updates the access permissions to it. Args: service: object service for the Group Settings API. groupId: string identifier of the group@domain. settings: dictionary key-value pairs of properties of group.
access_settings
python
googleapis/google-api-python-client
samples/groupssettings/groupsettings.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/groupssettings/groupsettings.py
Apache-2.0
def main(argv): """Demos the setting of the access properties by the Groups Settings API.""" usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("--groupId", help="Group email address") parser.add_option( "--whoCanInvite", help="Possible values: ALL_...
Demos the setting of the access properties by the Groups Settings API.
main
python
googleapis/google-api-python-client
samples/groupssettings/groupsettings.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/groupssettings/groupsettings.py
Apache-2.0
def UploadShapefile(service, project_id, shapefile_prefix): """Upload a shapefile to a given project, and display status when complete. Args: service: The service object built by the Google API Python client library. project_id: string, id of the GME project. shapefile_prefix: string, the sha...
Upload a shapefile to a given project, and display status when complete. Args: service: The service object built by the Google API Python client library. project_id: string, id of the GME project. shapefile_prefix: string, the shapefile without the .shp suffix. Returns: String id of th...
UploadShapefile
python
googleapis/google-api-python-client
samples/maps_engine/maps_engine.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/maps_engine/maps_engine.py
Apache-2.0
def print_header(line): """Format and print header block sized to length of line""" header_str = "=" header_line = header_str * len(line) print("\n" + header_line) print(line) print(header_line)
Format and print header block sized to length of line
print_header
python
googleapis/google-api-python-client
samples/prediction/prediction.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/prediction/prediction.py
Apache-2.0
def print_table(response, title): """Prints out a response table. Each row contains key(s), clicks, impressions, CTR, and average position. Args: response: The server response to be printed as a table. title: The title of the table. """ print("\n --" + title + ":") if "rows" not i...
Prints out a response table. Each row contains key(s), clicks, impressions, CTR, and average position. Args: response: The server response to be printed as a table. title: The title of the table.
print_table
python
googleapis/google-api-python-client
samples/searchconsole/search_analytics_api_sample.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchconsole/search_analytics_api_sample.py
Apache-2.0
def main(): """Get and print a feed of all public products available in the United States. Note: The source and country arguments are required to pass to the list method. """ client = build("shopping", SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY) resource = client.products() reques...
Get and print a feed of all public products available in the United States. Note: The source and country arguments are required to pass to the list method.
main
python
googleapis/google-api-python-client
samples/searchforshopping/basic.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/basic.py
Apache-2.0
def main(): """Get and print a feed of public products in the United States mathing a text search query for 'digital camera' and grouped by the 8 top brands. The list method of the resource should be called with the "crowdBy" parameter. Each parameter should be designed as <attribute>:<occurence>, ...
Get and print a feed of public products in the United States mathing a text search query for 'digital camera' and grouped by the 8 top brands. The list method of the resource should be called with the "crowdBy" parameter. Each parameter should be designed as <attribute>:<occurence>, where <occurrence>...
main
python
googleapis/google-api-python-client
samples/searchforshopping/crowding.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/crowding.py
Apache-2.0
def main(): """Get and print a feed of all public products matching the search query "digital camera". This is achieved by using the q query parameter to the list method. The "|" operator can be used to search for alternative search terms, for example: q = 'banana|apple' will search for bananas or...
Get and print a feed of all public products matching the search query "digital camera". This is achieved by using the q query parameter to the list method. The "|" operator can be used to search for alternative search terms, for example: q = 'banana|apple' will search for bananas or apples. Searc...
main
python
googleapis/google-api-python-client
samples/searchforshopping/fulltextsearch.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/fulltextsearch.py
Apache-2.0
def main(): """Get and print a histogram of the top 15 brand distribution for a search query. Histograms are created by using the "Facets" functionality of the API. A Facet is a view of a certain property of products, containing a number of buckets, one for each value of that property. Or concretel...
Get and print a histogram of the top 15 brand distribution for a search query. Histograms are created by using the "Facets" functionality of the API. A Facet is a view of a certain property of products, containing a number of buckets, one for each value of that property. Or concretely, for a parameter ...
main
python
googleapis/google-api-python-client
samples/searchforshopping/histograms.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/histograms.py
Apache-2.0
def print_item(item): """Displays a single item: title, merchant, link.""" product = item["product"] print( "- %s [%s] (%s)" % (product["title"], product["author"]["name"], product["link"]) )
Displays a single item: title, merchant, link.
print_item
python
googleapis/google-api-python-client
samples/searchforshopping/main.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/main.py
Apache-2.0
def main(): """Get and print a the entire paginated feed of public products in the United States. Pagination is controlled with the "startIndex" parameter passed to the list method of the resource. """ client = build("shopping", SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY) resource = c...
Get and print a the entire paginated feed of public products in the United States. Pagination is controlled with the "startIndex" parameter passed to the list method of the resource.
main
python
googleapis/google-api-python-client
samples/searchforshopping/pagination.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/pagination.py
Apache-2.0
def main(): """Get and print a feed of all public products matching the search query "digital camera", that are created by "Canon" available in the United States. The "restrictBy" parameter controls which types of results are returned. Multiple values for a single restrictBy can be separated by th...
Get and print a feed of all public products matching the search query "digital camera", that are created by "Canon" available in the United States. The "restrictBy" parameter controls which types of results are returned. Multiple values for a single restrictBy can be separated by the "|" operator, ...
main
python
googleapis/google-api-python-client
samples/searchforshopping/restricting.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/searchforshopping/restricting.py
Apache-2.0
def generate_pr_body(self): """ Generates a PR body given an input file `'allapis.dataframe'` and writes it to disk with file name `'allapis.summary'`. """ directory = pathlib.Path(self._change_summary_directory) dataframe = pd.read_csv(directory / "allapis.dataframe") ...
Generates a PR body given an input file `'allapis.dataframe'` and writes it to disk with file name `'allapis.summary'`.
generate_pr_body
python
googleapis/google-api-python-client
scripts/buildprbody.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/buildprbody.py
Apache-2.0
def __init__(self, new_artifacts_dir, current_artifacts_dir, temp_dir, file_list): """Initializes an instance of a ChangeSummary. Args: new_artifacts_dir (str): The relative path to the directory with the new discovery artifacts. current_artifacts_dir (str): The ...
Initializes an instance of a ChangeSummary. Args: new_artifacts_dir (str): The relative path to the directory with the new discovery artifacts. current_artifacts_dir (str): The relative path to the directory with the current discovery artifacts. ...
__init__
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _raise_if_directory_not_found(self, directory): """Raises if the `directory` doesn't exist args: directory (str): The relative path to the `directory` """ if not pathlib.Path(directory).exists(): raise DirectoryDoesNotExist( "Directory does n...
Raises if the `directory` doesn't exist args: directory (str): The relative path to the `directory`
_raise_if_directory_not_found
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _load_json_to_dataframe(self, file_path): """Returns a pandas dataframe from the json file provided. args: file_path (str): The relative path to the discovery artifact to parse. """ # Create an empty dataframe as we will need to return it if the file ...
Returns a pandas dataframe from the json file provided. args: file_path (str): The relative path to the discovery artifact to parse.
_load_json_to_dataframe
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _get_discovery_differences(self, filename): """Returns a pandas dataframe which contains the differences with the current and new discovery artifact directories, corresponding to the file name provided. args: filename (str): The name of the discovery artifact to parse. ...
Returns a pandas dataframe which contains the differences with the current and new discovery artifact directories, corresponding to the file name provided. args: filename (str): The name of the discovery artifact to parse.
_get_discovery_differences
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _build_summary_message(self, api_name, is_feature): """Returns a string containing the summary for a given api. The string returned will be in the format `fix(<api_name>): update the API` when `is_feature=False` and `feat(<api_name>)!: update the API` when `is_feature=True`. ...
Returns a string containing the summary for a given api. The string returned will be in the format `fix(<api_name>): update the API` when `is_feature=False` and `feat(<api_name>)!: update the API` when `is_feature=True`. args: api_name (str): The name of the api to include i...
_build_summary_message
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _get_keys_to_ignore(self): """Returns a list of strings with keys to ignore because they rarely affect functionality. args: None """ keys_to_ignore = [ "description", "documentation", "enum", "etag", "revision",...
Returns a list of strings with keys to ignore because they rarely affect functionality. args: None
_get_keys_to_ignore
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _get_stable_versions(self, versions): """Returns a pandas series `pd.Series()` of boolean values, corresponding to the given series, indicating whether the version is considered stable or not. args: versions (object): a pandas series containing version inf...
Returns a pandas series `pd.Series()` of boolean values, corresponding to the given series, indicating whether the version is considered stable or not. args: versions (object): a pandas series containing version information for all discovery artifacts.
_get_stable_versions
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _get_summary_and_write_to_disk(self, dataframe, directory): """Writes summary information to file about changes made to discovery artifacts based on the provided dataframe and returns a dataframe with the same. The file `'allapis.dataframe'` is saved to the current working directory....
Writes summary information to file about changes made to discovery artifacts based on the provided dataframe and returns a dataframe with the same. The file `'allapis.dataframe'` is saved to the current working directory. args: dataframe (object): a pandas dataframe containin...
_get_summary_and_write_to_disk
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def _write_verbose_changes_to_disk(self, dataframe, directory, summary_df): """Writes verbose information to file about changes made to discovery artifacts based on the provided dataframe. A separate file is saved for each api in the current working directory. The extension of the files ...
Writes verbose information to file about changes made to discovery artifacts based on the provided dataframe. A separate file is saved for each api in the current working directory. The extension of the files will be `'.verbose'`. args: dataframe (object): a pandas dataframe...
_write_verbose_changes_to_disk
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def detect_discovery_changes(self): """Writes a summary of the changes to the discovery artifacts to disk at the path specified in `temp_dir`. args: None """ result = pd.DataFrame() # Process files in parallel to improve performance with Pool(processes=MULTIP...
Writes a summary of the changes to the discovery artifacts to disk at the path specified in `temp_dir`. args: None
detect_discovery_changes
python
googleapis/google-api-python-client
scripts/changesummary.py
https://github.com/googleapis/google-api-python-client/blob/master/scripts/changesummary.py
Apache-2.0
def assertUrisEqual(testcase, expected, actual): """Test that URIs are the same, up to reordering of query parameters.""" expected = urllib.parse.urlparse(expected) actual = urllib.parse.urlparse(actual) testcase.assertEqual(expected.scheme, actual.scheme) testcase.assertEqual(expected.netloc, actua...
Test that URIs are the same, up to reordering of query parameters.
assertUrisEqual
python
googleapis/google-api-python-client
tests/test_discovery.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_discovery.py
Apache-2.0
def assert_discovery_uri(testcase, actual, service_name, version, discovery): """Assert that discovery URI used was the one that was expected for a given service and version.""" params = {"api": service_name, "apiVersion": version} expanded_requested_uri = uritemplate.expand(discovery, params) asser...
Assert that discovery URI used was the one that was expected for a given service and version.
assert_discovery_uri
python
googleapis/google-api-python-client
tests/test_discovery.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_discovery.py
Apache-2.0
def validate_discovery_requests(testcase, http_mock, service_name, version, discovery): """Validates that there have > 0 calls to Http Discovery and that LAST discovery URI used was the one that was expected for a given service and version.""" testcase.assertTrue(len(http_mock.request_sequence) > 0) ...
Validates that there have > 0 calls to Http Discovery and that LAST discovery URI used was the one that was expected for a given service and version.
validate_discovery_requests
python
googleapis/google-api-python-client
tests/test_discovery.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_discovery.py
Apache-2.0
def test_json_body(self): """Test a nicely formed, expected error response.""" resp, content = fake_response( JSON_ERROR_CONTENT, {"status": "400", "content-type": "application/json"}, reason="Failed", ) error = HttpError(resp, content, uri="http://exa...
Test a nicely formed, expected error response.
test_json_body
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_bad_json_body(self): """Test handling of bodies with invalid json.""" resp, content = fake_response( b"{", {"status": "400", "content-type": "application/json"}, reason="Failed" ) error = HttpError(resp, content) self.assertEqual( str(error), ...
Test handling of bodies with invalid json.
test_bad_json_body
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_with_uri(self): """Test handling of passing in the request uri.""" resp, content = fake_response( b"{", {"status": "400", "content-type": "application/json"}, reason="Failure", ) error = HttpError(resp, content, uri="http://example.org") ...
Test handling of passing in the request uri.
test_with_uri
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_missing_message_json_body(self): """Test handling of bodies with missing expected 'message' element.""" resp, content = fake_response( b"{}", {"status": "400", "content-type": "application/json"}, reason="Failed", ) error = HttpError(resp, con...
Test handling of bodies with missing expected 'message' element.
test_missing_message_json_body
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_non_json(self): """Test handling of non-JSON bodies""" resp, content = fake_response(b"Invalid request", {"status": "400"}) error = HttpError(resp, content) self.assertEqual( str(error), '<HttpError 400 when requesting None returned "Ok". Details: "Invali...
Test handling of non-JSON bodies
test_non_json
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_missing_reason(self): """Test an empty dict with a missing resp.reason.""" resp, content = fake_response(b"}NOT OK", {"status": "400"}, reason=None) error = HttpError(resp, content) self.assertEqual( str(error), '<HttpError 400 when requesting None return...
Test an empty dict with a missing resp.reason.
test_missing_reason
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_error_detail_for_missing_message_in_error(self): """Test handling of data with missing 'details' or 'detail' element.""" resp, content = fake_response( JSON_ERROR_CONTENT_NO_DETAIL, {"status": "400", "content-type": "application/json"}, reason="Failed", ...
Test handling of data with missing 'details' or 'detail' element.
test_error_detail_for_missing_message_in_error
python
googleapis/google-api-python-client
tests/test_errors.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_errors.py
Apache-2.0
def test_json_body_default_data(self): """Test that a 'data' wrapper doesn't get added if one is already present.""" model = JsonModel(data_wrapper=True) headers = {} path_params = {} query_params = {} body = {"data": "foo"} headers, unused_params, query, body =...
Test that a 'data' wrapper doesn't get added if one is already present.
test_json_body_default_data
python
googleapis/google-api-python-client
tests/test_json_model.py
https://github.com/googleapis/google-api-python-client/blob/master/tests/test_json_model.py
Apache-2.0
def __init__(self, token=None, phone_number_id=None): """ Initialize the WhatsApp Object Args: token[str]: Token for the WhatsApp cloud API obtained from the developer portal phone_number_id[str]: Phone number id for the WhatsApp cloud API obtained from the developer por...
Initialize the WhatsApp Object Args: token[str]: Token for the WhatsApp cloud API obtained from the developer portal phone_number_id[str]: Phone number id for the WhatsApp cloud API obtained from the developer portal
__init__
python
Neurotech-HQ/heyoo
heyoo/__init__.py
https://github.com/Neurotech-HQ/heyoo/blob/master/heyoo/__init__.py
MIT
async def send_message( self, message, recipient_id, recipient_type="individual", preview_url=True ): """ Sends a text message to a WhatsApp user Args: message[str]: Message to be sent to the user recipient_id[str]: Phone number of the user with...
Sends a text message to a WhatsApp user Args: message[str]: Message to be sent to the user recipient_id[str]: Phone number of the user with country code wihout + recipient_type[str]: Type of the recipient, either individual or group pre...
send_message
python
Neurotech-HQ/heyoo
heyoo/__init__.py
https://github.com/Neurotech-HQ/heyoo/blob/master/heyoo/__init__.py
MIT
def findUser(): "Try to return logged-in (usually non-root) user" return ( # If we're running sudo os.environ.get( 'SUDO_USER', False ) or # Logged-in user (if we have a tty) ( quietRun( 'who am i' ).split() or [ False ] )[ 0 ] or # Give up and return ...
Try to return logged-in (usually non-root) user
findUser
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def add( cls, server, user='' ): "Add an entry to server: user dict" if not cls.inited: addCleanupCallback( cls.cleanup ) if not user: user = findUser() cls.serveruser[ server ] = user
Add an entry to server: user dict
add
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def __init__( self, name, server='localhost', user=None, serverIP=None, controlPath=False, splitInit=False, **kwargs): """Instantiate a remote node name: name of remote node server: remote server (optional) user: user on remote server (optional) cont...
Instantiate a remote node name: name of remote node server: remote server (optional) user: user on remote server (optional) controlPath: specify shared ssh control path (optional) splitInit: split initialization? **kwargs: see Node()
__init__
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def startShell( self, *args, **kwargs ): "Start a shell process for running commands" if self.isRemote: kwargs.update( mnopts='-c' ) super( RemoteMixin, self ).startShell( *args, **kwargs ) # Optional split initialization self.sendCmd( 'echo $$' ) if not self....
Start a shell process for running commands
startShell
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def finishInit( self ): "Wait for split initialization to complete" self.pid = int( self.waitOutput() )
Wait for split initialization to complete
finishInit
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def rpopen( self, *cmd, **opts ): "Return a Popen object on underlying server in root namespace" params = { 'stdin': PIPE, 'stdout': PIPE, 'stderr': STDOUT, 'sudo': True } params.update( opts ) return self._popen( *cmd, **params )
Return a Popen object on underlying server in root namespace
rpopen
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def rcmd( self, *cmd, **opts): """rcmd: run a command on underlying server in root namespace args: string or list of strings returns: stdout and stderr""" popen = self.rpopen( *cmd, **opts ) # info( 'RCMD: POPEN:', popen, '\n' ) # These loops are tricky t...
rcmd: run a command on underlying server in root namespace args: string or list of strings returns: stdout and stderr
rcmd
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def _popen( self, cmd, sudo=True, tt=True, **params): """Spawn a process on a remote node cmd: remote command to run (list) **params: parameters to Popen() returns: Popen() object""" if isinstance( cmd, str): cmd = cmd.split() if self.isRemote: ...
Spawn a process on a remote node cmd: remote command to run (list) **params: parameters to Popen() returns: Popen() object
_popen
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def isOldOVS( self ): # pylint: disable=arguments-differ "Is remote switch using an old OVS version?" cls = type( self ) if self.server not in cls.OVSVersions: # pylint: disable=not-callable vers = self.cmd( 'ovs-vsctl --version' ) # pylint: enable=not-callab...
Is remote switch using an old OVS version?
isOldOVS
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def batchStartup( cls, switches, **_kwargs ): "Start up switches in per-server batches" key = attrgetter( 'server' ) for server, switchGroup in groupby( sorted( switches, key=key ), key ): info( '(%s)' % server ) group = tuple( switchGroup ) switch = group[ 0 ...
Start up switches in per-server batches
batchStartup
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def batchShutdown( cls, switches, **_kwargs ): "Stop switches in per-server batches" key = attrgetter( 'server' ) for server, switchGroup in groupby( sorted( switches, key=key ), key ): info( '(%s)' % server ) group = tuple( switchGroup ) switch = group[ 0 ] ...
Stop switches in per-server batches
batchShutdown
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def __init__( self, node1, node2, **kwargs ): """Initialize a RemoteLink see Link() for parameters""" # Create links on remote node self.node1 = node1 self.node2 = node2 self.tunnel = None kwargs.setdefault( 'params1', {} ) kwargs.setdefault( 'params2',...
Initialize a RemoteLink see Link() for parameters
__init__
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def makeIntfPair( self, # pylint: disable=arguments-renamed intfname1, intfname2, addr1=None, addr2=None, node1=None, node2=None, deleteIntfs=True ): """Create pair of interfaces intfname1: name of interface 1 intfname2: name of interface 2 ...
Create pair of interfaces intfname1: name of interface 1 intfname2: name of interface 2 (override this method [and possibly delete()] to change link type)
makeIntfPair
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def moveIntf( intf, node ): """Move remote interface from root ns to node intf: string, interface dstNode: destination Node srcNode: source Node or None (default) for root ns""" intf = str( intf ) cmd = 'ip link set %s netns %s' % ( intf, node.pid ) re...
Move remote interface from root ns to node intf: string, interface dstNode: destination Node srcNode: source Node or None (default) for root ns
moveIntf
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def makeTunnel( self, node1, node2, intfname1, intfname2, addr1=None, addr2=None ): "Make a tunnel across switches on different servers" # We should never try to create a tunnel to ourselves! assert node1.server != node2.server # And we can't ssh into this server remo...
Make a tunnel across switches on different servers
makeTunnel
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def __init__( self, servers=None, nodes=None, hosts=None, switches=None, controllers=None, links=None ): """Initialize placement object servers: list of servers nodes: list of all nodes hosts: list of hosts switches: list of switches contr...
Initialize placement object servers: list of servers nodes: list of all nodes hosts: list of hosts switches: list of switches controllers: list of controllers links: list of links (all arguments are optional) returns: server
__init__
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def place( self, node ): """Round-robin placement function node: node""" assert node # please pylint # This may be slow with lots of servers server = self.servers[ self.next ] self.next = ( self.next + 1 ) % len( self.servers ) return server
Round-robin placement function node: node
place
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def place( self, node ): """Simple placement algorithm: place nodes into evenly sized bins""" # Place nodes into bins if node in self.hset: server = self.servdict[ self.hind / self.hbin ] self.hind += 1 elif node in self.sset: server = self...
Simple placement algorithm: place nodes into evenly sized bins
place
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def __init__( self, *args, **kwargs ): """servers: a list of servers to use (note: include localhost or None to use local system as well) user: user name for server ssh placement: Placer() subclass""" params = { 'host': RemoteHost, 'switch': RemoteOVSS...
servers: a list of servers to use (note: include localhost or None to use local system as well) user: user name for server ssh placement: Placer() subclass
__init__
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def precheck( self ): """Pre-check to make sure connection works and that we can call sudo without a password""" result = 0 info( '*** Checking servers\n' ) for server in self.servers: ip = self.serverIP[ server ] if not server or server == 'localhost':...
Pre-check to make sure connection works and that we can call sudo without a password
precheck
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def placeNodes( self ): """Place nodes on servers (if they don't have a server), and start shell processes""" if not self.servers or not self.topo: # No shirt, no shoes, no service return nodes = self.topo.nodes() placer = self.placement( servers=self.s...
Place nodes on servers (if they don't have a server), and start shell processes
placeNodes
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def addController( self, *args, **kwargs ): "Patch to update IP address to global IP address" controller = Mininet.addController( self, *args, **kwargs ) controllerIP = controller.IP() if ( not isinstance( controller, Controller ) or not self.isLoopback( controller.IP() ) ):...
Patch to update IP address to global IP address
addController
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def testNsTunnels( remote=remoteServer, link=RemoteGRELink ): "Test tunnels between nodes in namespaces" net = Mininet( host=RemoteHost, link=link, waitConnected=True ) h1 = net.addHost( 'h1') h2 = net.addHost( 'h2', server=remote ) net.addLink( h1, h2 ) net.start() net.pingAll() net.sto...
Test tunnels between nodes in namespaces
testNsTunnels
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def HostPlacer( name, *args, **params ): "Custom Host() constructor which places hosts on servers" if name in remoteHosts: return RemoteHost( name, *args, server=remoteServer, **params ) else: return Host( name, *args, **params )
Custom Host() constructor which places hosts on servers
HostPlacer
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def SwitchPlacer( name, *args, **params ): "Custom Switch() constructor which places switches on servers" if name in remoteSwitches: return RemoteOVSSwitch( name, *args, server=remoteServer, **params ) else: return RemoteOVSSwitch( name, *args, **params )
Custom Switch() constructor which places switches on servers
SwitchPlacer
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def ClusterController( *args, **kwargs): "Custom Controller() constructor which updates its intf IP address" intf = kwargs.pop( 'intf', '' ) controller = Controller( *args, **kwargs ) # Find out its IP address so that cluster switches can connect if not intf: output = controller.cmd( ...
Custom Controller() constructor which updates its intf IP address
ClusterController
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def testRemoteTopo( link=RemoteGRELink ): "Test remote Node classes using Mininet()/Topo() API" topo = LinearTopo( 2 ) net = Mininet( topo=topo, host=HostPlacer, switch=SwitchPlacer, link=link, controller=ClusterController ) net.start() net.pingAll() net.stop()
Test remote Node classes using Mininet()/Topo() API
testRemoteTopo
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def testRemoteSwitches( remote=remoteServer, link=RemoteGRELink ): "Test with local hosts and remote switches" servers = [ 'localhost', remote] topo = TreeTopo( depth=4, fanout=2 ) net = MininetCluster( topo=topo, servers=servers, link=link, placement=RoundRobinPlacer ) net...
Test with local hosts and remote switches
testRemoteSwitches
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def signalTest( remote=remoteServer): "Make sure hosts are robust to signals" h = RemoteHost( 'h0', server=remote ) h.shell.send_signal( SIGINT ) h.shell.poll() if h.shell.returncode is None: info( 'signalTest: SUCCESS: ', h, 'has not exited after SIGINT', '\n' ) else: info( 'sig...
Make sure hosts are robust to signals
signalTest
python
mininet/mininet
examples/cluster.py
https://github.com/mininet/mininet/blob/master/examples/cluster.py
BSD-3-Clause
def colorsFor( seq ): "Return a list of background colors for a sequence" colors = [ 'red', 'lightgreen', 'cyan', 'yellow', 'orange', 'magenta', 'pink', 'grey', 'brown', 'white' ] slen, clen = len( seq ), len( colors ) reps = max( 1, slen / clen ) ...
Return a list of background colors for a sequence
colorsFor
python
mininet/mininet
examples/clustercli.py
https://github.com/mininet/mininet/blob/master/examples/clustercli.py
BSD-3-Clause
def do_plot( self, _line ): "Plot topology colored by node placement" # Import networkx if needed global nx, plt, graphviz_layout if not nx: try: # pylint: disable=import-error,no-member # pylint: disable=import-outside-toplevel ...
Plot topology colored by node placement
do_plot
python
mininet/mininet
examples/clustercli.py
https://github.com/mininet/mininet/blob/master/examples/clustercli.py
BSD-3-Clause
def perf(Link): "Test connectivity nand performance over Link" net = Mininet( host=RemoteHost, link=Link, waitConnected=True ) h1 = net.addHost( 'h1') h2 = net.addHost( 'h2', server='ubuntu2' ) net.addLink( h1, h2 ) net.start() net.pingAll() net.iperf() net.stop()
Test connectivity nand performance over Link
perf
python
mininet/mininet
examples/clusterperf.py
https://github.com/mininet/mininet/blob/master/examples/clusterperf.py
BSD-3-Clause
def makeWidgets( self ): "Make a label, a text area, and a scroll bar." def newTerm( net=self.net, node=self.node, title=self.title ): "Pop up a new terminal window for a node." net.terms += makeTerms( [ node ], title ) label = Button( self, text=self.node.name, command=...
Make a label, a text area, and a scroll bar.
makeWidgets
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def newTerm( net=self.net, node=self.node, title=self.title ): "Pop up a new terminal window for a node." net.terms += makeTerms( [ node ], title )
Pop up a new terminal window for a node.
newTerm
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def append( self, text ): "Append something to our text frame." text = self.ignoreChars.sub( '', text ) self.text.insert( 'end', text ) self.text.mark_set( 'insert', 'end' ) self.text.see( 'insert' ) if callable( self.outputHook ): self.outputHook( self, text ...
Append something to our text frame.
append
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def handleKey( self, event ): "If it's an interactive command, send it to the node." char = event.char if self.node.waiting: self.node.write( char )
If it's an interactive command, send it to the node.
handleKey
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def createScale( self ): "Create a and return a new canvas with scale markers." height = float( self.gheight ) width = 25 ymax = self.ymax scale = Canvas( self, width=width, height=height, background=self.bg ) opts = { 'fill': 'red' } # Dra...
Create a and return a new canvas with scale markers.
createScale
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def updateScrollRegions( self ): "Update graph and scale scroll regions." ofs = 20 height = self.gheight + ofs self.graph.configure( scrollregion=( 0, -ofs, self.xpos * self.barwidth, height ) ) self.scale.configure( scrollregion=( 0, -ofs, 0, height...
Update graph and scale scroll regions.
updateScrollRegions
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def addBar( self, yval ): "Add a new bar to our graph." percent = yval / self.ymax c = self.graph x0 = self.xpos * self.barwidth x1 = x0 + self.barwidth y0 = self.gheight y1 = ( 1 - percent ) * self.gheight c.create_rectangle( x0, y0, x1, y1, fill='green' ...
Add a new bar to our graph.
addBar
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def setOutputHook( self, fn=None, consoles=None ): "Register fn as output hook [on specific consoles.]" if consoles is None: consoles = self.consoles[ 'hosts' ].consoles for console in consoles: console.outputHook = fn
Register fn as output hook [on specific consoles.]
setOutputHook
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def createConsoles( self, parent, nodes, width, title ): "Create a grid of consoles in a frame." f = Frame( parent ) # Create consoles consoles = [] index = 0 for node in nodes: console = Console( f, self.net, node, title=title ) consoles.append( c...
Create a grid of consoles in a frame.
createConsoles
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def select( self, groupName ): "Select a group of consoles to display." if self.selected is not None: self.selected.frame.pack_forget() self.selected = self.consoles[ groupName ] self.selected.frame.pack( expand=True, fill='both' )
Select a group of consoles to display.
select
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def createMenuBar( self ): "Create and return a menu (really button) bar." f = Frame( self ) buttons = [ ( 'Hosts', lambda: self.select( 'hosts' ) ), ( 'Switches', lambda: self.select( 'switches' ) ), ( 'Controllers', lambda: self.select( 'controllers' ) ), ...
Create and return a menu (really button) bar.
createMenuBar
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def waiting( self, consoles=None ): "Are any of our hosts waiting for output?" if consoles is None: consoles = self.consoles[ 'hosts' ].consoles for console in consoles: if console.waiting(): return True return False
Are any of our hosts waiting for output?
waiting
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def ping( self ): "Tell each host to ping the next one." consoles = self.consoles[ 'hosts' ].consoles if self.waiting( consoles ): return count = len( consoles ) i = 0 for console in consoles: i = ( i + 1 ) % count ip = consoles[ i ].no...
Tell each host to ping the next one.
ping
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def iperf( self ): "Tell each host to iperf to the next one." consoles = self.consoles[ 'hosts' ].consoles if self.waiting( consoles ): return count = len( consoles ) self.setOutputHook( self.updateGraph ) for console in consoles: # Sometimes iperf...
Tell each host to iperf to the next one.
iperf
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def assign( obj, **kwargs ): "Set a bunch of fields in an object." obj.__dict__.update( kwargs )
Set a bunch of fields in an object.
assign
python
mininet/mininet
examples/consoles.py
https://github.com/mininet/mininet/blob/master/examples/consoles.py
BSD-3-Clause
def multiControllerNet(): "Create a network from semi-scratch with multiple controllers." net = Mininet( controller=Controller, switch=OVSSwitch, waitConnected=True ) info( "*** Creating (reference) controllers\n" ) c1 = net.addController( 'c1', port=6633 ) c2 = net.addControlle...
Create a network from semi-scratch with multiple controllers.
multiControllerNet
python
mininet/mininet
examples/controllers2.py
https://github.com/mininet/mininet/blob/master/examples/controllers2.py
BSD-3-Clause
def __init__( self, net, *args, **kwargs ): """Create MininetFacade object. net: Primary Mininet object args: unnamed networks passed as arguments kwargs: named networks passed as arguments""" self.net = net self.nets = [ net ] + list( args ) + list( kwargs.value...
Create MininetFacade object. net: Primary Mininet object args: unnamed networks passed as arguments kwargs: named networks passed as arguments
__init__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def __getattr__( self, name ): "returns attribute from Primary Mininet object" return getattr( self.net, name )
returns attribute from Primary Mininet object
__getattr__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def __getitem__( self, key ): "returns primary/named networks or node from any net" # search kwargs for net named key if key in self.nameToNet: return self.nameToNet[ key ] # search each net for node named key for net in self.nets: if key in net: ...
returns primary/named networks or node from any net
__getitem__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def __iter__( self ): "Iterate through all nodes in all Mininet objects" for net in self.nets: for node in net: yield node
Iterate through all nodes in all Mininet objects
__iter__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def __len__( self ): "returns aggregate number of nodes in all nets" count = 0 for net in self.nets: count += len(net) return count
returns aggregate number of nodes in all nets
__len__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def __contains__( self, key ): "returns True if node is a member of any net" return key in self.keys()
returns True if node is a member of any net
__contains__
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def keys( self ): "returns a list of all node names in all networks" return list( self )
returns a list of all node names in all networks
keys
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def values( self ): "returns a list of all nodes in all networks" return [ self[ key ] for key in self ]
returns a list of all nodes in all networks
values
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def items( self ): "returns (key,value) tuple list for every node in all networks" return zip( self.keys(), self.values() )
returns (key,value) tuple list for every node in all networks
items
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def build( self, n, dataController=DataController, **_kwargs ): """n: number of data network controller nodes dataController: class for data network controllers""" # Connect everything to a single switch cs0 = self.addSwitch( 'cs0' ) # Add hosts which will serve as data networ...
n: number of data network controller nodes dataController: class for data network controllers
build
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def run(): "Create control and data networks, and invoke the CLI" info( '* Creating Control Network\n' ) ctopo = ControlNetwork( n=4, dataController=DataController ) cnet = Mininet( topo=ctopo, ipBase='192.168.123.0/24', controller=None, waitConnected=True ) info( '* Adding Cont...
Create control and data networks, and invoke the CLI
run
python
mininet/mininet
examples/controlnet.py
https://github.com/mininet/mininet/blob/master/examples/controlnet.py
BSD-3-Clause
def emptyNet(): "Create an empty network and add nodes to it." net = Mininet( controller=Controller, waitConnected=True ) info( '*** Adding controller\n' ) net.addController( 'c0' ) info( '*** Adding hosts\n' ) h1 = net.addHost( 'h1', ip='10.0.0.1' ) h2 = net.addHost( 'h2', ip='10.0.0.2'...
Create an empty network and add nodes to it.
emptyNet
python
mininet/mininet
examples/emptynet.py
https://github.com/mininet/mininet/blob/master/examples/emptynet.py
BSD-3-Clause
def checkIntf( intf ): "Make sure intf exists and is not configured." config = quietRun( 'ifconfig %s 2>/dev/null' % intf, shell=True ) if not config: error( 'Error:', intf, 'does not exist!\n' ) exit( 1 ) ips = re.findall( r'\d+\.\d+\.\d+\.\d+', config ) if ips: error( 'Erro...
Make sure intf exists and is not configured.
checkIntf
python
mininet/mininet
examples/hwintf.py
https://github.com/mininet/mininet/blob/master/examples/hwintf.py
BSD-3-Clause
def intfOptions(): "run various traffic control commands on a single interface" net = Mininet( autoStaticArp=True, waitConnected=True ) net.addController( 'c0' ) h1 = net.addHost( 'h1' ) h2 = net.addHost( 'h2' ) s1 = net.addSwitch( 's1' ) link1 = net.addLink( h1, s1, cls=TCLink ) net.add...
run various traffic control commands on a single interface
intfOptions
python
mininet/mininet
examples/intfoptions.py
https://github.com/mininet/mininet/blob/master/examples/intfoptions.py
BSD-3-Clause