docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Extract the labels into a 1D uint8 numpy array [index].
Args:
f: A file object that can be passed into a gzip reader.
one_hot: Does one hot encoding for the result.
num_classes: Number of classes for the one hot encoding.
Returns:
labels: a 1D unit8 numpy array.
... | def extract_labels(self, f, one_hot=False, num_classes=10):
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = self._read32(bytestream)
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST label file: %s' %
... | 978,187 |
Will try to read configuration from environment variables and ini
files, if no value found in either of those ``None`` is
returned.
Args:
prefix: The environment variable prefix.
section: The ini file section this configuration is scoped to
filename: The path... | def __init__(self, prefix, section, filename=None):
options = dict(prefix=prefix, section=section, filename=filename)
super(Settings, self).__init__(**options) | 978,318 |
Expands ~/path to /home/<current_user>/path
On POSIX systems does it by getting the home directory for the
current effective user from the passwd database. On other systems
do it by using :func:`os.path.expanduser`
Args:
path (str): A path to expand to a user's home folder
Returns:
... | def expand_user(path):
if not path.startswith('~'):
return path
if os.name == 'posix':
user = pwd.getpwuid(os.geteuid())
return path.replace('~', user.pw_dir, 1)
else:
return os.path.expanduser(path) | 978,549 |
Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
Returns:
([positional_args], {kwar... | def format_arguments(*args):
positional_args = []
kwargs = {}
split_key = None
for arg in args:
if arg.startswith('--'):
arg = arg[2:]
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key.replace('-', '_')] = value
el... | 978,551 |
Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance | def get_go_server(settings=None):
if not settings:
settings = get_settings()
return gocd.Server(
settings.get('server'),
user=settings.get('user'),
password=settings.get('password'),
) | 978,554 |
Extract an expression from the flow of tokens.
Args:
rbp (int): the "right binding power" of the previous token.
This represents the (right) precedence of the previous token,
and will be compared to the (left) precedence of next tokens.
Returns:
... | def expression(self, rbp=0):
prev_token = self.consume()
# Retrieve the value from the previous token situated at the
# leftmost point in the expression
left = prev_token.nud(context=self)
while rbp < self.current_token.lbp:
# Read incoming tokens with a hi... | 978,823 |
Register a token.
Args:
token (Token): the token class to register
regexp (str): the regexp for that token | def register(self, token, regexp):
self._tokens.append((token, re.compile(regexp))) | 978,897 |
Retrieve all token definitions matching the beginning of a text.
Args:
text (str): the text to test
start (int): the position where matches should be searched in the
string (see re.match(rx, txt, pos))
Yields:
(token_class, re.Match): all token class... | def matching_tokens(self, text, start=0):
for token_class, regexp in self._tokens:
match = regexp.match(text, pos=start)
if match:
yield token_class, match | 978,898 |
Retrieve the next token from some text.
Args:
text (str): the text from which tokens should be extracted
Returns:
(token_kind, token_text): the token kind and its content. | def get_token(self, text, start=0):
best_class = best_match = None
for token_class, match in self.matching_tokens(text):
if best_match and best_match.end() >= match.end():
continue
best_match = match
best_class = token_class
return b... | 978,899 |
Register a token class.
Args:
token_class (tdparser.Token): the token class to register
regexp (optional str): the regexp for elements of that token.
Defaults to the `regexp` attribute of the token class. | def register_token(self, token_class, regexp=None):
if regexp is None:
regexp = token_class.regexp
self.tokens.register(token_class, regexp) | 978,901 |
Split self.text into a list of tokens.
Args:
text (str): text to parse
Yields:
Token: the tokens generated from the given text. | def lex(self, text):
pos = 0
while text:
token_class, match = self.tokens.get_token(text)
if token_class is not None:
matched_text = text[match.start():match.end()]
yield token_class(matched_text)
text = text[match.end():]
... | 978,902 |
Parse self.text.
Args:
text (str): the text to lex
Returns:
object: a node representing the current rule. | def parse(self, text):
tokens = self.lex(text)
parser = Parser(tokens)
return parser.parse() | 978,903 |
Parse a stream.
Args:
ifp (string or file-like object): input stream.
pb_cls (protobuf.message.Message.__class__): The class object of
the protobuf message type encoded in the stream. | def parse(ifp, pb_cls, **kwargs):
mode = 'rb'
if isinstance(ifp, str):
istream = open(ifp, mode=mode, **kwargs)
else:
istream = open(fileobj=ifp, mode=mode, **kwargs)
with istream:
for data in istream:
pb_obj = pb_cls()
pb_obj.ParseFromString(data)
... | 979,173 |
Write to a stream.
Args:
ofp (string or file-like object): output stream.
pb_objs (*protobuf.message.Message): list of protobuf message objects
to be written. | def dump(ofp, *pb_objs, **kwargs):
mode = 'wb'
if isinstance(ofp, str):
ostream = open(ofp, mode=mode, **kwargs)
else:
ostream = open(fileobj=ofp, mode=mode, **kwargs)
with ostream:
ostream.write(*pb_objs) | 979,174 |
Write a group of one or more protobuf objects to the file. Multiple
object groups can be written by calling this method several times
before closing stream or exiting the runtime context.
The input protobuf objects get buffered and will be written down when
the number of buffered object... | def write(self, *pb2_obj):
base = len(self._write_buff)
for idx, obj in enumerate(pb2_obj):
if self._buffer_size > 0 and \
(idx + base) != 0 and \
(idx + base) % self._buffer_size == 0:
self.flush()
self._write_buf... | 979,179 |
Called to store the ticket data for a request.
Ticket data is stored in the aiohttp_session object
Args:
request: aiohttp Request object.
ticket: String like object representing the ticket to be stored. | async def remember_ticket(self, request, ticket):
session = await get_session(request)
session[self.cookie_name] = ticket | 979,457 |
Called to forget the ticket data a request
Args:
request: aiohttp Request object. | async def forget_ticket(self, request):
session = await get_session(request)
session.pop(self.cookie_name, '') | 979,458 |
Called to return the ticket for a request.
Args:
request: aiohttp Request object.
Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request. | async def get_ticket(self, request):
session = await get_session(request)
return session.get(self.cookie_name) | 979,459 |
Returns a aiohttp_auth middleware factory for use by the aiohttp
application object.
Args:
policy: A authentication policy with a base class of
AbstractAuthentication. | def auth_middleware(policy):
assert isinstance(policy, AbstractAuthentication)
async def _auth_middleware_factory(app, handler):
async def _middleware_handler(request):
# Save the policy in the request
request[POLICY_KEY] = policy
# Call the next handler in th... | 979,471 |
Returns the user_id associated with a particular request.
Args:
request: aiohttp Request object.
Returns:
The user_id associated with the request, or None if no user is
associated with the request.
Raises:
RuntimeError: Middleware is not installed | async def get_auth(request):
auth_val = request.get(AUTH_KEY)
if auth_val:
return auth_val
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
request[AUTH_KEY] = await auth_policy.get(request)
return request[A... | 979,472 |
Called to store and remember the userid for a request
Args:
request: aiohttp Request object.
user_id: String representing the user_id to remember
Raises:
RuntimeError: Middleware is not installed | async def remember(request, user_id):
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.remember(request, user_id) | 979,473 |
Called to forget the userid for a request
Args:
request: aiohttp Request object
Raises:
RuntimeError: Middleware is not installed | async def forget(request):
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.forget(request) | 979,474 |
Called to store the userid for a request.
This function creates a ticket from the request and user_id, and calls
the abstract function remember_ticket() to store the ticket.
Args:
request: aiohttp Request object.
user_id: String representing the user_id to remember | async def remember(self, request, user_id):
ticket = self._new_ticket(request, user_id)
await self.remember_ticket(request, ticket) | 979,522 |
Gets the user_id for the request.
Gets the ticket for the request using the get_ticket() function, and
authenticates the ticket.
Args:
request: aiohttp Request object.
Returns:
The userid for the request, or None if the ticket is not
authenticated. | async def get(self, request):
ticket = await self.get_ticket(request)
if ticket is None:
return None
try:
# Returns a tuple of (user_id, token, userdata, validuntil)
now = time.time()
fields = self._ticket.validate(ticket, self._get_ip(re... | 979,523 |
Unnest collection structure extracting all its datasets and converting \
them to Pandas Dataframes.
Args:
collection (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
json.l... | def unnest_collection(collection, df_list):
for item in collection['link']['item']:
if item['class'] == 'dataset':
df_list.append(Dataset.read(item['href']).write('dataframe'))
elif item['class'] == 'collection':
nested_collection = request(item['href'])
unne... | 979,579 |
Get dimensions from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
naming (string, optional): dimension naming. Possible values: 'label' \
or 'id'.
Returns:
dimensions (list): list of pandas data frames with dimension \
... | def get_dimensions(js_dict, naming):
dimensions = []
dim_names = []
if check_version_2(js_dict):
dimension_dict = js_dict
else:
dimension_dict = js_dict['dimension']
for dim in dimension_dict['id']:
dim_name = js_dict['dimension'][dim]['label']
if not dim_name:
... | 979,580 |
Get label from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_label(pandas.DataFrame): DataFrame with label-based dimension data. | def get_dim_label(js_dict, dim, input="dataset"):
if input == 'dataset':
input = js_dict['dimension'][dim]
label_col = 'label'
elif input == 'dimension':
label_col = js_dict['label']
input = js_dict
else:
raise ValueError
try:
dim_label = input['cat... | 979,581 |
Get index from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_index (pandas.DataFrame): DataFrame with index-based dimension data. | def get_dim_index(js_dict, dim):
try:
dim_index = js_dict['dimension'][dim]['category']['index']
except KeyError:
dim_label = get_dim_label(js_dict, dim)
dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])),
index=[0],
... | 979,582 |
Get values from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
value (string, optional): name of the value column. Defaults to 'value'.
Returns:
values (list): list of dataset values. | def get_values(js_dict, value='value'):
values = js_dict[value]
if type(values) is list:
if type(values[0]) is not dict or tuple:
return values
# being not a list of dicts or tuples leaves us with a dict...
values = {int(key): value for (key, value) in values.items()}
if j... | 979,583 |
Return unique values in a list in the original order. See: \
http://www.peterbe.com/plog/uniqifiers-benchmark
Args:
seq (list): original list.
Returns:
list: list without duplicates preserving original order. | def uniquify(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)] | 979,585 |
Send a request to a given URL accepting JSON format and return a \
deserialized Python object.
Args:
path (str): The URI to be requested.
Returns:
response: Deserialized JSON Python object.
Raises:
HTTPError: the HTTP error returned by the requested server.
InvalidURL: an i... | def request(path):
headers = {'Accept': 'application/json'}
try:
requested_object = requests.get(path, headers=headers)
requested_object.raise_for_status()
except requests.exceptions.HTTPError as exception:
LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' +
... | 979,589 |
Reads data from URL, Dataframe, JSON string, JSON file or
OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON file, a JSON string,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class Dataset populated with data. | def read(cls, data):
if isinstance(data, pd.DataFrame):
return cls((json.loads(
to_json_stat(data, output='dict', version='2.0'),
object_pairs_hook=OrderedDict)))
elif isinstance(data, OrderedDict):
return cls(data)
elif (isinstanc... | 979,590 |
Converts a dimension ID string and a categody ID string into the \
numeric index of that category in that dimension
Args:
name(string): ID string of the dimension.
value(string): ID string of the category.
Returns:
ndx[value](int): index of the category in th... | def get_dimension_index(self, name, value):
if 'index' not in self.get('dimension', {}). \
get(name, {}).get('category', {}):
return 0
ndx = self['dimension'][name]['category']['index']
if isinstance(ndx, list):
return ndx.index(value)
e... | 979,591 |
Converts a dimension/category list of dicts into a list of \
dimensions’ indices.
Args:
query(list): dimension/category list of dicts.
Returns:
indices(list): list of dimensions' indices. | def get_dimension_indices(self, query):
ids = self['id'] if self.get('id') else self['dimension']['id']
indices = []
for idx, id in enumerate(ids):
indices.append(self.get_dimension_index(id,
[d.get(id) for d in query
... | 979,592 |
Converts a list of dimensions’ indices into a numeric value index.
Args:
indices(list): list of dimension's indices.
Returns:
num(int): numeric value index. | def get_value_index(self, indices):
size = self['size'] if self.get('size') else self['dimension']['size']
ndims = len(size)
mult = 1
num = 0
for idx, dim in enumerate(size):
mult *= size[ndims - idx] if (idx > 0) else 1
num += mult * indices[ndim... | 979,593 |
Converts a dimension/category list of dicts into a data value \
in three steps.
Args:
query(list): list of dicts with the desired query.
Returns:
value(float): numeric data value. | def get_value(self, query):
indices = self.get_dimension_indices(query)
index = self.get_value_index(indices)
value = self.get_value_by_index(index)
return value | 979,594 |
Reads data from URL, Dataframe, JSON string, JSON file
or OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON string, a JSON file,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class Dimension populated with data. | def read(cls, data):
if isinstance(data, pd.DataFrame):
output = OrderedDict({})
output['version'] = '2.0'
output['class'] = 'dimension'
[label] = [x for x in list(data.columns.values) if
x not in ['id', 'index']]
output... | 979,596 |
Writes data from a Dataset object to JSONstat or Pandas Dataframe.
Args:
output(string): can accept 'jsonstat' or 'dataframe'
Returns:
Serialized JSONstat or a Pandas Dataframe,depending on the \
'output' parameter. | def write(self, output='jsonstat'):
if output == 'jsonstat':
return json.dumps(OrderedDict(self), cls=NumpyEncoder)
elif output == 'dataframe':
return get_dim_label(self, self['label'], 'dimension')
else:
raise ValueError("Allowed arguments are 'json... | 979,597 |
Reads data from URL or OrderedDict.
Args:
data: can be a URL pointing to a JSONstat file, a JSON string
or an OrderedDict.
Returns:
An object of class Collection populated with data. | def read(cls, data):
if isinstance(data, OrderedDict):
return cls(data)
elif isinstance(data, basestring)\
and data.startswith(("http://", "https://", "ftp://", "ftps://")):
return cls(request(data))
elif isinstance(data, basestring):
try... | 979,599 |
Writes data from a Collection object to JSONstat or list of \
Pandas Dataframes.
Args:
output(string): can accept 'jsonstat' or 'dataframe_list'
Returns:
Serialized JSONstat or a list of Pandas Dataframes,depending on \
the 'output' parameter. | def write(self, output='jsonstat'):
if output == 'jsonstat':
return json.dumps(self)
elif output == 'dataframe_list':
df_list = []
unnest_collection(self, df_list)
return df_list
else:
raise ValueError(
"Allowe... | 979,600 |
Gets ith element of a collection in an object of the corresponding \
class.
Args:
output(string): can accept 'jsonstat' or 'dataframe_list'
Returns:
Serialized JSONstat or a list of Pandas Dataframes,depending on \
the 'output' parameter. | def get(self, element):
if self['link']['item'][element]['class'] == 'dataset':
return Dataset.read(self['link']['item'][element]['href'])
elif self['link']['item'][element]['class'] == 'collection':
return Collection.read(self['link']['item'][element]['href'])
... | 979,601 |
Make a (deep) copy of self.
Parameters:
deep : bool
Make a deep copy.
name : str
Name of the copy, with default self.name + '_copy'. | def copy(self, deep=False, name=None):
if deep:
other = deepcopy(self)
else:
other = copy(self)
if hasattr(self, 'name'):
other.name = get_default(name, self.name + '_copy')
return other | 981,109 |
Parses Crianza source code and returns a native Python function.
Args:
args: The resulting function's number of input parameters.
Returns:
A callable Python function. | def xcompile(source_code, args=0, optimize=True):
code = crianza.compile(crianza.parse(source_code), optimize=optimize)
return crianza.native.compile(code, args=args) | 981,961 |
Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.
Args:
optimize: Whether to optimize the code after parsing it.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contain... | def xeval(source, optimize=True):
native = xcompile(source, optimize=optimize)
return native() | 981,962 |
Constant-folds simple expressions like 2 3 + to 5.
Args:
code: Code in non-native types.
silent: Flag that controls whether to print optimizations made.
ignore_errors: Whether to raise exceptions on found errors. | def constant_fold(code, silent=True, ignore_errors=True):
# Loop until we haven't done any optimizations. E.g., "2 3 + 5 *" will be
# optimized to "5 5 *" and in the next iteration to 25. Yes, this is
# extremely slow, big-O wise. We'll fix that some other time. (TODO)
arithmetic = list(map(inst... | 982,550 |
Parses source code returns an array of instructions suitable for
optimization and execution by a Machine.
Args:
source: A string or stream containing source code. | def parse(source):
if isinstance(source, str):
return parse_stream(six.StringIO(source))
else:
return parse_stream(source) | 982,641 |
Compiles and runs program, returning the machine used to execute the
code.
Args:
optimize: Whether to optimize the code after parsing it.
output: Stream which program can write output to.
input: Stream which program can read input from.
steps: An optional maximum number of instr... | def execute(source, optimize=True, output=sys.stdout, input=sys.stdin, steps=-1):
from crianza import compiler
code = compiler.compile(parser.parse(source), optimize=optimize)
machine = Machine(code, output=output, input=input)
return machine.run(steps) | 982,720 |
Run threaded code in machine.
Args:
steps: If specified, run that many number of instructions before
stopping. | def run(self, steps=None):
try:
while self.instruction_pointer < len(self.code):
self.step()
if steps is not None:
steps -= 1
if steps == 0:
break
except StopIteration:
pass
... | 982,727 |
Upload a file to a server
Attempts to upload a local file with path filepath, to the server, where it
will be named filename.
Args:
:param file_name: The name that the uploaded file will be called on the server.
:param file_path: The path of the local file to upload.
... | def upload_file(self, file_name, file_path):
request = urllib.request.Request(self.url + '/rest/v1/data/upload/job_input?name=' + file_name)
if self.authorization_header() is not None:
request.add_header('Authorization', self.authorization_header())
request.add_header('User... | 982,815 |
Starts a simple REPL for this machine.
Args:
optimize: Controls whether to run inputted code through the
optimizer.
persist: If True, the machine is not deleted after each line. | def repl(optimize=True, persist=True):
print("Extra commands for the REPL:")
print(".code - print code")
print(".raw - print raw code")
print(".quit - exit immediately")
print(".reset - reset machine (IP and stacks)")
print(".restart - create a clean, new machine")
print(".c... | 982,860 |
Construct an iterator.
Args:
timeseries: the timeseries to iterate over
loop: The asyncio loop to use for iterating | def __init__(self, timeseries, loop=None):
self.timeseries = timeseries
self.queue = deque()
self.continuation_url = timeseries._base_url | 984,405 |
Get a URL.
Args:
callback(func): The response callback function
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
headers(dict): Additional headers for the request
Returns:
The result o... | def get(self, url, callback,
params=None, json=None, headers=None):
return self.adapter.get(url, callback,
params=params, json=json, headers=headers) | 984,540 |
Put to a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
headers(dict): HTTP headers for the request
... | def put(self, url, callback,
params=None, json=None, headers=None):
return self.adapter.put(url, callback, params=params, json=json) | 984,541 |
Patch a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
headers(dict): HTTP headers for the request
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
... | def patch(self, url, callback,
params=None, json=None, headers=None):
return self.adapter.patch(url, callback,
params=params, json=json, headers=headers) | 984,542 |
Delete a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
Keyword Args:
json(dict): JSON body for the request
Returns:
The result of the callback handling the resopnse from the
execut... | def delete(self, url, callback, json=None):
return self.adapter.delete(url, callback, json=json) | 984,543 |
Build a relationship list.
A relationship list is used to update relationships between two
resources. Setting sensors on a label, for example, uses this
function to construct the list of sensor ids to pass to the Helium
API.
Args:
type(string): The resource type for the ids in the relatio... | def build_request_relationship(type, ids):
if ids is None:
return {
'data': None
}
elif isinstance(ids, str):
return {
'data': {'id': ids, 'type': type}
}
else:
return {
"data": [{"id": id, "type": type} for id in ids]
... | 985,203 |
Create a basic json based object.
Arguments:
json(dict): A json dictionary to base attributes on | def __init__(self, json):
super(Base, self).__init__()
self._json_data = json
self._update_attributes(json) | 985,205 |
Create a Resource.
Args:
json(dict): The json to construct the resource from.
session(Session): The session use for this resource
Keyword Args:
include([Resource class]): Resource classes that are included
included([json]): A list of all included json re... | def __init__(self, json, session, include=None, included=None):
self._session = session
self._include = include
self._included = included
super(Resource, self).__init__(json) | 985,207 |
Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
include: Resource classes to include
Returns:
... | def find(cls, session, resource_id, include=None):
url = session._build_url(cls._resource_path(), resource_id)
params = build_request_include(include, None)
process = cls._mk_one(session, include=include)
return session.get(url, CB.json(200, process), params=params) | 985,211 |
Create a resource of the resource.
This should only be called from sub-classes
Args:
session(Session): The session to create the resource in.
attributes(dict): Any attributes that are valid for the
given resource type.
relationships(dict): Any relationshi... | def create(cls, session, attributes=None, relationships=None):
resource_type = cls._resource_type()
resource_path = cls._resource_path()
url = session._build_url(resource_path)
json = build_request_body(resource_type, None,
attributes=attributes... | 985,213 |
VCS init method.
Args:
callback: Callback function that will be called for each action.
Returns:
VCS Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._vcs = brocade_vcs(
callback=pynos.utilities.return_xml
) | 986,129 |
BGP object init.
Args:
callback: Callback function that will be called for each action.
Returns:
BGP Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._rbridge = brocade_rbridge(callback=pynos.utilities.return_xml) | 986,210 |
Add SNMP Community to NOS device.
Args:
community (str): Community string to be added to device.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
... | def add_snmp_community(self, **kwargs):
community = kwargs.pop('community')
callback = kwargs.pop('callback', self._callback)
config = ET.Element('config')
snmp_server = ET.SubElement(config, 'snmp-server',
xmlns=("urn:brocade.com:mgmt:"
... | 986,293 |
VCS init function
Args:
callback: Callback function that will be called for each action
Returns:
VCS Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._brocade_tunnels = brocade_tunnels(callback=pynos.utilities.return_xml) | 986,347 |
Set gateway type
Args:
name (str): gateway-name
type (str): gateway-type
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def hwvtep_set_overlaygw_type(self, **kwargs):
name = kwargs.pop('name')
type = kwargs.pop('type')
ip_args = dict(name=name, gw_type=type)
method_name = 'overlay_gateway_gw_type'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
... | 986,348 |
Add a range of rbridge-ids
Args:
name (str): gateway-name
vlan (str): rbridge-ids range
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def hwvtep_add_rbridgeid(self, **kwargs):
name = kwargs.pop('name')
id = kwargs.pop('rb_range')
ip_args = dict(name=name, rb_add=id)
method_name = 'overlay_gateway_attach_rbridge_id_rb_add'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, meth... | 986,349 |
Add loopback interface to the overlay-gateway
Args:
name (str): gateway-name
int_id (int): loopback inteface id
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:... | def hwvtep_add_loopback_interface(self, **kwargs):
name = kwargs.pop('name')
id = kwargs.pop('int_id')
ip_args = dict(name=name, loopback_id=id)
method_name = 'overlay_gateway_ip_interface_loopback_loopback_id'
method_class = self._brocade_tunnels
gw_attr = getat... | 986,350 |
Add virtual ethernet (ve) interface to the overlay-gateway
Args:
name (str): gateway-name
int_id (int): ve id
vrrp_id (int): VRPP-E group ID
callback (function): A function executed upon completion of the
... | def hwvtep_add_ve_interface(self, **kwargs):
name = kwargs.pop('name')
ve_id = kwargs.pop('ve_id')
vrrp_id = kwargs.pop('vrrp_id')
ve_args = dict(name=name, ve_id=ve_id)
method_name = 'overlay_gateway_ip_interface_ve_ve_id'
method_class = self._brocade_tunnels
... | 986,351 |
Activate the hwvtep
Args:
name (str): overlay_gateway name
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def hwvtep_activate_hwvtep(self, **kwargs):
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'overlay_gateway_activate'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**name_args)
outp... | 986,352 |
Identifies exported VLANs in VXLAN gateway configurations.
Args:
name (str): overlay_gateway name
vlan(str): vlan_id range
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
... | def hwvtep_attach_vlan_vid(self, **kwargs):
name = kwargs.pop('name')
mac = kwargs.pop('mac')
vlan = kwargs.pop('vlan')
name_args = dict(name=name, vid=vlan, mac=mac)
method_name = 'overlay_gateway_attach_vlan_mac'
method_class = self._brocade_tunnels
gw_... | 986,353 |
Get overlay-gateway name on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Dictionary containing details of VXLAN Overlay Gateway.
Raises:
None | def get_overlay_gateway(self):
urn = "urn:brocade.com:mgmt:brocade-tunnels"
config = ET.Element("config")
ET.SubElement(config, "overlay-gateway", xmlns=urn)
output = self._callback(config, handler='get_config')
result = {}
element = ET.fromstring(str(output))
... | 986,354 |
Return the `ip unnumbered` donor name XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
delete (bool): Remove the configuration if ``True... | def _ip_unnumbered_name(self, **kwargs):
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_name' % kwargs['int_type']
ip_unnumbered_name = getattr(self._interface, method_name)
config = ip_unnumbered_name(**kwargs)
if kwargs['delete']:
... | 986,447 |
Return the `ip unnumbered` donor type XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
delete (bool): Remove the configuration if ``True... | def _ip_unnumbered_type(self, **kwargs):
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_type' % kwargs['int_type']
ip_unnumbered_type = getattr(self._interface, method_name)
config = ip_unnumbered_type(**kwargs)
if kwargs['delete']:
... | 986,448 |
Get and merge the `ip unnumbered` config from an interface.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
unnumbered_type: XML document with the XML to get the donor type.
unnumbered_name: XML document with the XML to get the donor n... | def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name):
unnumbered_type = self._callback(unnumbered_type, handler='get_config')
unnumbered_name = self._callback(unnumbered_name, handler='get_config')
unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type))
unnu... | 986,449 |
Return the BFD minimum transmit interval XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
min_tx (str): BFD transmit interval in milliseconds (300, 500, etc)
delete (bool): Remove the configuration if ``True``.
Returns:
XML to... | def _bfd_tx(self, **kwargs):
int_type = kwargs['int_type']
method_name = 'interface_%s_bfd_interval_min_tx' % int_type
bfd_tx = getattr(self._interface, method_name)
config = bfd_tx(**kwargs)
if kwargs['delete']:
tag = 'min-tx'
config.find('.//*%s... | 986,452 |
Return the BFD minimum receive interval XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
min_rx (str): BFD receive interval in milliseconds (300, 500, etc)
delete (bool): Remove the configuration if ``True``.
Returns:
XML to b... | def _bfd_rx(self, **kwargs):
int_type = kwargs['int_type']
method_name = 'interface_%s_bfd_interval_min_rx' % int_type
bfd_rx = getattr(self._interface, method_name)
config = bfd_rx(**kwargs)
if kwargs['delete']:
tag = 'min-rx'
config.find('.//*%s... | 986,453 |
Return the BFD multiplier XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
min_tx (str): BFD transmit interval in milliseconds (300, 500, etc)
delete (bool): Remove the configuration if ``True``.
Returns:
XML to be passed to t... | def _bfd_multiplier(self, **kwargs):
int_type = kwargs['int_type']
method_name = 'interface_%s_bfd_interval_multiplier' % int_type
bfd_multiplier = getattr(self._interface, method_name)
config = bfd_multiplier(**kwargs)
if kwargs['delete']:
tag = 'multiplier'... | 986,454 |
Get/Set nsx controller name
Args:
name: (str) : Name of the nsx controller
get (bool) : Get nsx controller config(True,False)
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
... | def nsx_controller_name(self, **kwargs):
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'nsx_controller_name'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(method_class, method_name)
config = nsxcontroller_attr(**name_args... | 986,606 |
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def set_nsxcontroller_ip(self, **kwargs):
name = kwargs.pop('name')
ip_addr = str((kwargs.pop('ip_addr', None)))
nsxipaddress = ip_interface(unicode(ip_addr))
if nsxipaddress.version != 4:
raise ValueError('NSX Controller ip must be IPV4')
ip_args = dict(nam... | 986,607 |
Activate NSX Controller
Args:
name (str): nsxcontroller name
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def activate_nsxcontroller(self, **kwargs):
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'nsx_controller_activate'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(method_class, method_name)
config = nsxcontroller_attr(**na... | 986,608 |
Set Nsx Controller pot on the switch
Args:
port (int): 1 to 65535.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | def set_nsxcontroller_port(self, **kwargs):
name = kwargs.pop('name')
port = str(kwargs.pop('port'))
port_args = dict(name=name, port=port)
method_name = 'nsx_controller_connection_addr_port'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(metho... | 986,609 |
Get/Set nsx controller name
Args:
name: (str) : Name of the nsx-controller
callback (function): A function executed upon completion of the
method.
Returns: Return dictionary containing nsx-controller information.
Returns blank dict if no ns... | def get_nsx_controller(self):
urn = "urn:brocade.com:mgmt:brocade-tunnels"
config = ET.Element("config")
ET.SubElement(config, "nsx-controller", xmlns=urn)
output = self._callback(config, handler='get_config')
result = {}
element = ET.fromstring(str(output))
... | 986,610 |
LLDP init method.
Args:
callback (function): Callback function that will be called for each
action.
Returns:
LLDP Object
Raises:
None | def __init__(self, callback):
super(LLDP, self).__init__(callback)
self._lldp = brcd_lldp(callback=pynos.utilities.return_xml) | 986,841 |
Interface init function.
Args:
callback: Callback function that will be called for each action.
Returns:
Interface Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._interface = brocade_interface(
callback=pynos.utilities.return_xml
)
self._rbridge = brocade_rbridge(
callback=pynos.utilities.return_xml
)
self._mac_address_table = brocade_mac... | 986,885 |
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if command completes successfully or False if not.
... | def add_vlan_int(self, vlan_id):
config = ET.Element('config')
vlinterface = ET.SubElement(config, 'interface-vlan',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
interface = ET.SubElement(vlinterface,... | 986,886 |
Change an interface's operation to L3.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
Returns:
True if com... | def disable_switchport(self, inter_type, inter):
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
int_type = ET.SubElement(interfac... | 986,887 |
Add a L2 Interface to a specific VLAN.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
vlan_id: ID for the VLAN inte... | def access_vlan(self, inter_type, inter, vlan_id):
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
int_type = ET.SubElement(interf... | 986,888 |
Set IP address of a L3 interface.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
ip_addr: IP Address in <prefix>/<b... | def set_ip(self, inter_type, inter, ip_addr):
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
intert = ET.SubElement(interface, in... | 986,889 |
Returns firmware version.
Args:
None
Returns:
Dictionary
Raises:
None | def firmware_version(self):
namespace = "urn:brocade.com:mgmt:brocade-firmware-ext"
request_ver = ET.Element("show-firmware-version", xmlns=namespace)
ver = self._callback(request_ver, handler='get')
return ver.find('.//*{%s}os-version' % namespace).text | 987,133 |
Reconnect session with device.
Args:
None
Returns:
bool: True if reconnect succeeds, False if not.
Raises:
None | def reconnect(self):
if self._auth_method is "userpass":
self._mgr = manager.connect(host=self._conn[0],
port=self._conn[1],
username=self._auth[0],
password=self._auth[1]... | 987,135 |
Return the BFD minimum receive interval XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
min_rx (str): BFD receive interval in milliseconds (300, 500, etc)
delete (bool): Remove the configuration if ``True``.
Returns:
XML to b... | def _bfd_rx(self, **kwargs):
method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \
'bfd_interval_min_rx'
bfd_rx = getattr(self._rbridge, method_name)
config = bfd_rx(**kwargs)
if kwargs['delete']:
tag = 'min-rx'
confi... | 987,166 |
Return the BFD multiplier XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
min_tx (str): BFD transmit interval in milliseconds (300, 500, etc)
delete (bool): Remove the configuration if ``True``.
Returns:
XML to be passed to t... | def _bfd_multiplier(self, **kwargs):
method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \
'bfd_interval_multiplier'
bfd_multiplier = getattr(self._rbridge, method_name)
config = bfd_multiplier(**kwargs)
if kwargs['delete']:
tag ... | 987,167 |
Return the BFD minimum transmit interval XML.
You should not use this method.
You probably want `BGP.bfd`.
Args:
peer_ip (str): Peer IPv4 address for BFD setting.
min_tx (str): BFD transmit interval in milliseconds (300, 500, etc)
delete (bool): Remove the c... | def _peer_bfd_tx(self, **kwargs):
method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \
'neighbor_neighbor_ips_neighbor_addr_bfd_interval_min_tx'
bfd_tx = getattr(self._rbridge, method_name)
config = bfd_tx(**kwargs)
if kwargs['delete']:
... | 987,171 |
Get and merge the `bfd` config from global BGP.
You should not use this method.
You probably want `BGP.bfd`.
Args:
tx: XML document with the XML to get the transmit interval.
rx: XML document with the XML to get the receive interval.
multiplier: XML document... | def _peer_get_bfd(self, tx, rx, multiplier):
tx = self._callback(tx, handler='get_config')
rx = self._callback(rx, handler='get_config')
multiplier = self._callback(multiplier, handler='get_config')
tx = pynos.utilities.return_xml(str(tx))
rx = pynos.utilities.return_xml... | 987,172 |
RAS init method.
Args:
callback: Callback function that will be called for each action.
Returns:
RAS Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._ras = brocade_ras(callback=pynos.utilities.return_xml) | 987,230 |
Interface init function.
Args:
callback: Callback function that will be called for each action.
Returns:
Interface Object
Raises:
None | def __init__(self, callback):
super(Interface, self).__init__(callback)
self._mac_address_table = brocade_mac_address_table(
callback=pynos.utilities.return_xml
) | 987,552 |
Vcenter init function
Args:
callback: Callback function that will be called for each action
Returns:
Vcenter Object
Raises:
None | def __init__(self, callback):
self._callback = callback
self._brocade_vswitch = brocade_vswitch(callback=pynos.utilities.return_xml) | 987,619 |
Add vCenter on the switch
Args:
id(str) : Name of an established vCenter
url (bool) : vCenter URL
username (str): Username of the vCenter
password (str): Password of the vCenter
callback (function): A function executed upon completion of the
... | def add_vcenter(self, **kwargs):
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter",
xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id = ET.SubElement(vcenter, "id")
id.text = kwargs.pop('id')
credentials = ET.SubElemen... | 987,620 |
Activate vCenter on the switch
Args:
name: (str) : Name of an established vCenter
activate (bool) : Activates the vCenter if activate=True
else deactivates it
callback (function): A function executed upon completion of the
metho... | def activate_vcenter(self, **kwargs):
name = kwargs.pop('name')
activate = kwargs.pop('activate', True)
vcenter_args = dict(id=name)
method_class = self._brocade_vswitch
if activate:
method_name = 'vcenter_activate'
vcenter_attr = getattr(method_c... | 987,621 |
Get vCenter hosts on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Returns a list of vcenters
Raises:
None | def get_vcenter(self, **kwargs):
config = ET.Element("config")
urn = "urn:brocade.com:mgmt:brocade-vswitch"
ET.SubElement(config, "vcenter", xmlns=urn)
output = self._callback(config, handler='get_config')
result = []
element = ET.fromstring(str(output))
... | 987,622 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.