body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
53f0a098d72796b805f0b830a211c5b615a488d8ad66c3835bfe74e05cd538dc | def download_persec_data(job_header_df, api_key, base_path, raw_filename_function=default_raw_csv_filename, formatted_filename_function=default_formatted_csv_filename, units_filename_function=default_units_csv_filename, local_job_headers_updater=None, default_delay=70, max_attempts=3):
' Download jobs in job_header_df from PerSecData API\n\n Parameters\n ----------\n job_header_df: pd.DataFrame\n A DataFrame with the a column of job_ids to download from the\n PerSecData API\n\n api_key: str\n The WDL API key to use for request authentication\n\n base_path: pathlib.Path or str\n The base path to use for the target CSV files\n\n raw_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n raw CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n formatted_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n formatted CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n units_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n units CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n local_job_headers_updater: Callable[[str], None]\n A function that takes a job_id and updates a local JobHeaders\n database table.\n\n default_delay: int\n Default number of seconds to wait between requests. This\n number should be non-negative.\n\n max_attempts: int\n The maximum number of times to attempt the download the\n PerSecData for job_id. This number should be positive.\n '
def is_function(param):
return isinstance(param, (FunctionType, partial))
def prepend_base_path(filename):
return ((base_path / filename) if filename else None)
assert isinstance(job_header_df, pd.DataFrame)
assert ('job_id' in job_header_df.columns)
assert isinstance(api_key, str)
assert is_function(raw_filename_function)
assert is_function(formatted_filename_function)
assert is_function(units_filename_function)
assert (is_function(local_job_headers_updater) or (local_job_headers_updater is None))
assert (default_delay >= 0)
assert (max_attempts > 0)
base_path = Path(base_path)
delay_before_making_next_api_call = 0
for job_id in job_header_df.job_id.values:
raw_filename = prepend_base_path(raw_filename_function(job_id))
formatted_filename = prepend_base_path(formatted_filename_function(job_id))
units_filename = prepend_base_path(units_filename_function(job_id))
persec_filenames = PerSecFilenames(raw_filename=raw_filename, formatted_filename=formatted_filename, units_filename=units_filename)
sleep(delay_before_making_next_api_call)
download_success = download_job_persec(job_id=job_id, api_key=api_key, persec_filenames=persec_filenames, default_delay=default_delay, max_attempts=max_attempts)
if (download_success and (local_job_headers_updater is not None)):
local_job_headers_updater(job_id=job_id)
delay_before_making_next_api_call = default_delay | Download jobs in job_header_df from PerSecData API
Parameters
----------
job_header_df: pd.DataFrame
A DataFrame with the a column of job_ids to download from the
PerSecData API
api_key: str
The WDL API key to use for request authentication
base_path: pathlib.Path or str
The base path to use for the target CSV files
raw_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
raw CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
formatted_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
formatted CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
units_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
units CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
local_job_headers_updater: Callable[[str], None]
A function that takes a job_id and updates a local JobHeaders
database table.
default_delay: int
Default number of seconds to wait between requests. This
number should be non-negative.
max_attempts: int
The maximum number of times to attempt the download the
PerSecData for job_id. This number should be positive. | persec_data_api.py | download_persec_data | welldatalabs/wdl-python | 1 | python | def download_persec_data(job_header_df, api_key, base_path, raw_filename_function=default_raw_csv_filename, formatted_filename_function=default_formatted_csv_filename, units_filename_function=default_units_csv_filename, local_job_headers_updater=None, default_delay=70, max_attempts=3):
' Download jobs in job_header_df from PerSecData API\n\n Parameters\n ----------\n job_header_df: pd.DataFrame\n A DataFrame with the a column of job_ids to download from the\n PerSecData API\n\n api_key: str\n The WDL API key to use for request authentication\n\n base_path: pathlib.Path or str\n The base path to use for the target CSV files\n\n raw_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n raw CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n formatted_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n formatted CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n units_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n units CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n local_job_headers_updater: Callable[[str], None]\n A function that takes a job_id and updates a local JobHeaders\n database table.\n\n default_delay: int\n Default number of seconds to wait between requests. This\n number should be non-negative.\n\n max_attempts: int\n The maximum number of times to attempt the download the\n PerSecData for job_id. This number should be positive.\n '
def is_function(param):
return isinstance(param, (FunctionType, partial))
def prepend_base_path(filename):
return ((base_path / filename) if filename else None)
assert isinstance(job_header_df, pd.DataFrame)
assert ('job_id' in job_header_df.columns)
assert isinstance(api_key, str)
assert is_function(raw_filename_function)
assert is_function(formatted_filename_function)
assert is_function(units_filename_function)
assert (is_function(local_job_headers_updater) or (local_job_headers_updater is None))
assert (default_delay >= 0)
assert (max_attempts > 0)
base_path = Path(base_path)
delay_before_making_next_api_call = 0
for job_id in job_header_df.job_id.values:
raw_filename = prepend_base_path(raw_filename_function(job_id))
formatted_filename = prepend_base_path(formatted_filename_function(job_id))
units_filename = prepend_base_path(units_filename_function(job_id))
persec_filenames = PerSecFilenames(raw_filename=raw_filename, formatted_filename=formatted_filename, units_filename=units_filename)
sleep(delay_before_making_next_api_call)
download_success = download_job_persec(job_id=job_id, api_key=api_key, persec_filenames=persec_filenames, default_delay=default_delay, max_attempts=max_attempts)
if (download_success and (local_job_headers_updater is not None)):
local_job_headers_updater(job_id=job_id)
delay_before_making_next_api_call = default_delay | def download_persec_data(job_header_df, api_key, base_path, raw_filename_function=default_raw_csv_filename, formatted_filename_function=default_formatted_csv_filename, units_filename_function=default_units_csv_filename, local_job_headers_updater=None, default_delay=70, max_attempts=3):
' Download jobs in job_header_df from PerSecData API\n\n Parameters\n ----------\n job_header_df: pd.DataFrame\n A DataFrame with the a column of job_ids to download from the\n PerSecData API\n\n api_key: str\n The WDL API key to use for request authentication\n\n base_path: pathlib.Path or str\n The base path to use for the target CSV files\n\n raw_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n raw CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n formatted_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n formatted CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n units_filename_function: Callable[[str], pathlib.Path]\n A function that takes a job_id and produces a filename for the\n units CSV data that is appended to base_path. This can be\n set to persec_data_api.nosave_filename to not save the\n file.\n\n local_job_headers_updater: Callable[[str], None]\n A function that takes a job_id and updates a local JobHeaders\n database table.\n\n default_delay: int\n Default number of seconds to wait between requests. This\n number should be non-negative.\n\n max_attempts: int\n The maximum number of times to attempt the download the\n PerSecData for job_id. This number should be positive.\n '
def is_function(param):
return isinstance(param, (FunctionType, partial))
def prepend_base_path(filename):
return ((base_path / filename) if filename else None)
assert isinstance(job_header_df, pd.DataFrame)
assert ('job_id' in job_header_df.columns)
assert isinstance(api_key, str)
assert is_function(raw_filename_function)
assert is_function(formatted_filename_function)
assert is_function(units_filename_function)
assert (is_function(local_job_headers_updater) or (local_job_headers_updater is None))
assert (default_delay >= 0)
assert (max_attempts > 0)
base_path = Path(base_path)
delay_before_making_next_api_call = 0
for job_id in job_header_df.job_id.values:
raw_filename = prepend_base_path(raw_filename_function(job_id))
formatted_filename = prepend_base_path(formatted_filename_function(job_id))
units_filename = prepend_base_path(units_filename_function(job_id))
persec_filenames = PerSecFilenames(raw_filename=raw_filename, formatted_filename=formatted_filename, units_filename=units_filename)
sleep(delay_before_making_next_api_call)
download_success = download_job_persec(job_id=job_id, api_key=api_key, persec_filenames=persec_filenames, default_delay=default_delay, max_attempts=max_attempts)
if (download_success and (local_job_headers_updater is not None)):
local_job_headers_updater(job_id=job_id)
delay_before_making_next_api_call = default_delay<|docstring|>Download jobs in job_header_df from PerSecData API
Parameters
----------
job_header_df: pd.DataFrame
A DataFrame with the a column of job_ids to download from the
PerSecData API
api_key: str
The WDL API key to use for request authentication
base_path: pathlib.Path or str
The base path to use for the target CSV files
raw_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
raw CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
formatted_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
formatted CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
units_filename_function: Callable[[str], pathlib.Path]
A function that takes a job_id and produces a filename for the
units CSV data that is appended to base_path. This can be
set to persec_data_api.nosave_filename to not save the
file.
local_job_headers_updater: Callable[[str], None]
A function that takes a job_id and updates a local JobHeaders
database table.
default_delay: int
Default number of seconds to wait between requests. This
number should be non-negative.
max_attempts: int
The maximum number of times to attempt the download the
PerSecData for job_id. This number should be positive.<|endoftext|> |
55b3d4c47e3c44842e19d6650914d91d05bfbd213688e9ac049c4557fadcfd00 | def strip_parentheses(unit):
' Remove parentheses from unit str '
return unit.translate({ord(i): None for i in '()'}) | Remove parentheses from unit str | persec_data_api.py | strip_parentheses | welldatalabs/wdl-python | 1 | python | def strip_parentheses(unit):
' '
return unit.translate({ord(i): None for i in '()'}) | def strip_parentheses(unit):
' '
return unit.translate({ord(i): None for i in '()'})<|docstring|>Remove parentheses from unit str<|endoftext|> |
012fa3f8948d22214a77273c7992f9ffe83cb7ca6035bf64a197b7ee3ef77e3a | def load_nodes(filename):
'\n Load nodes.\n '
nodes = set()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.rstrip().split()
nodes |= set(arrs)
return nodes | Load nodes. | src/common.py | load_nodes | raphael-group/netmix | 10 | python | def load_nodes(filename):
'\n \n '
nodes = set()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.rstrip().split()
nodes |= set(arrs)
return nodes | def load_nodes(filename):
'\n \n '
nodes = set()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.rstrip().split()
nodes |= set(arrs)
return nodes<|docstring|>Load nodes.<|endoftext|> |
0af197d87cf0ad64d78915b9341f21851fc390f3fce271ee609e056a7026aa58 | def save_nodes(filename, nodes):
'\n Load nodes.\n '
with open(filename, 'w') as f:
f.write('\n'.join((str(node) for node in nodes))) | Load nodes. | src/common.py | save_nodes | raphael-group/netmix | 10 | python | def save_nodes(filename, nodes):
'\n \n '
with open(filename, 'w') as f:
f.write('\n'.join((str(node) for node in nodes))) | def save_nodes(filename, nodes):
'\n \n '
with open(filename, 'w') as f:
f.write('\n'.join((str(node) for node in nodes)))<|docstring|>Load nodes.<|endoftext|> |
a472b7e0e34fd0cc255c871b87988a6036a845d7b950688323098c964c360c54 | def load_node_score(filename):
'\n Load node scores.\n '
node_to_score = dict()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) == 2):
node = arrs[0]
if is_number(arrs[1]):
score = float(arrs[1])
if np.isfinite(score):
node_to_score[node] = score
else:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
elif arrs:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
if (not node_to_score):
raise Exception('No node scores; check {}.'.format(filename))
return node_to_score | Load node scores. | src/common.py | load_node_score | raphael-group/netmix | 10 | python | def load_node_score(filename):
'\n \n '
node_to_score = dict()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) == 2):
node = arrs[0]
if is_number(arrs[1]):
score = float(arrs[1])
if np.isfinite(score):
node_to_score[node] = score
else:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
elif arrs:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
if (not node_to_score):
raise Exception('No node scores; check {}.'.format(filename))
return node_to_score | def load_node_score(filename):
'\n \n '
node_to_score = dict()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) == 2):
node = arrs[0]
if is_number(arrs[1]):
score = float(arrs[1])
if np.isfinite(score):
node_to_score[node] = score
else:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
elif arrs:
raise Warning('{} is not a valid node score; input line omitted.'.format(l.strip()))
if (not node_to_score):
raise Exception('No node scores; check {}.'.format(filename))
return node_to_score<|docstring|>Load node scores.<|endoftext|> |
89c7f2cb6688626dd268d9e93f496bac816530fc08f16135e41fd044094f0581 | def save_node_score(filename, node_to_score, reverse=True):
'\n Save node scores.\n '
node_score_list = sorted(node_to_score.items(), key=(lambda node_score: (((- float(node_score[1])) if reverse else float(node_score[1])), node_score[0])))
with open(filename, 'w') as f:
f.write('\n'.join(('{}\t{}'.format(node, score) for (node, score) in node_score_list))) | Save node scores. | src/common.py | save_node_score | raphael-group/netmix | 10 | python | def save_node_score(filename, node_to_score, reverse=True):
'\n \n '
node_score_list = sorted(node_to_score.items(), key=(lambda node_score: (((- float(node_score[1])) if reverse else float(node_score[1])), node_score[0])))
with open(filename, 'w') as f:
f.write('\n'.join(('{}\t{}'.format(node, score) for (node, score) in node_score_list))) | def save_node_score(filename, node_to_score, reverse=True):
'\n \n '
node_score_list = sorted(node_to_score.items(), key=(lambda node_score: (((- float(node_score[1])) if reverse else float(node_score[1])), node_score[0])))
with open(filename, 'w') as f:
f.write('\n'.join(('{}\t{}'.format(node, score) for (node, score) in node_score_list)))<|docstring|>Save node scores.<|endoftext|> |
ea21777cea31398a7ed17f88442aa9768d208738f04e5aa2b16b06293c6a17f3 | def load_edge_list(filename):
'\n Load edge list.\n '
edge_list = list()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) >= 2):
(u, v) = arrs[:2]
edge_list.append((u, v))
elif arrs:
raise Warning('{} is not a valid edge; input line omitted.'.format(l.strip()))
if (not edge_list):
raise Exception('Edge list has no edges; check {}.'.format(filename))
return edge_list | Load edge list. | src/common.py | load_edge_list | raphael-group/netmix | 10 | python | def load_edge_list(filename):
'\n \n '
edge_list = list()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) >= 2):
(u, v) = arrs[:2]
edge_list.append((u, v))
elif arrs:
raise Warning('{} is not a valid edge; input line omitted.'.format(l.strip()))
if (not edge_list):
raise Exception('Edge list has no edges; check {}.'.format(filename))
return edge_list | def load_edge_list(filename):
'\n \n '
edge_list = list()
with open(filename, 'r') as f:
for l in f:
if (not l.startswith('#')):
arrs = l.strip().split()
if (len(arrs) >= 2):
(u, v) = arrs[:2]
edge_list.append((u, v))
elif arrs:
raise Warning('{} is not a valid edge; input line omitted.'.format(l.strip()))
if (not edge_list):
raise Exception('Edge list has no edges; check {}.'.format(filename))
return edge_list<|docstring|>Load edge list.<|endoftext|> |
d522e5ff38a9051df8952f03078c3bb39abf40688054df651ff8d69191195a10 | def save_edge_list(filename, edge_list):
'\n Save edge list.\n '
with open(filename, 'w') as f:
f.write('\n'.join(('\t'.join(map(str, edge)) for edge in edge_list))) | Save edge list. | src/common.py | save_edge_list | raphael-group/netmix | 10 | python | def save_edge_list(filename, edge_list):
'\n \n '
with open(filename, 'w') as f:
f.write('\n'.join(('\t'.join(map(str, edge)) for edge in edge_list))) | def save_edge_list(filename, edge_list):
'\n \n '
with open(filename, 'w') as f:
f.write('\n'.join(('\t'.join(map(str, edge)) for edge in edge_list)))<|docstring|>Save edge list.<|endoftext|> |
0c18d90708bfd309578625cd0480e57e4014f6c99874ed07195ce4a4cc8c624a | def load_matrix(filename, matrix_name='A', dtype=np.float32):
'\n Load matrix.\n '
import h5py
f = h5py.File(filename, 'r')
if (matrix_name in f):
A = np.asarray(f[matrix_name].value, dtype=dtype)
else:
raise KeyError('Matrix {} is not in {}.'.format(matrix_name, filename))
f.close()
return A | Load matrix. | src/common.py | load_matrix | raphael-group/netmix | 10 | python | def load_matrix(filename, matrix_name='A', dtype=np.float32):
'\n \n '
import h5py
f = h5py.File(filename, 'r')
if (matrix_name in f):
A = np.asarray(f[matrix_name].value, dtype=dtype)
else:
raise KeyError('Matrix {} is not in {}.'.format(matrix_name, filename))
f.close()
return A | def load_matrix(filename, matrix_name='A', dtype=np.float32):
'\n \n '
import h5py
f = h5py.File(filename, 'r')
if (matrix_name in f):
A = np.asarray(f[matrix_name].value, dtype=dtype)
else:
raise KeyError('Matrix {} is not in {}.'.format(matrix_name, filename))
f.close()
return A<|docstring|>Load matrix.<|endoftext|> |
a1f2b17d3845f4419484c4001caf1d463d5b43cbf668d432841485991760b88e | def save_matrix(filename, A, matrix_name='A', dtype=np.float32):
'\n Save matrix.\n '
import h5py
f = h5py.File(filename, 'a')
if (matrix_name in f):
del f[matrix_name]
f[matrix_name] = np.asarray(A, dtype=dtype)
f.close() | Save matrix. | src/common.py | save_matrix | raphael-group/netmix | 10 | python | def save_matrix(filename, A, matrix_name='A', dtype=np.float32):
'\n \n '
import h5py
f = h5py.File(filename, 'a')
if (matrix_name in f):
del f[matrix_name]
f[matrix_name] = np.asarray(A, dtype=dtype)
f.close() | def save_matrix(filename, A, matrix_name='A', dtype=np.float32):
'\n \n '
import h5py
f = h5py.File(filename, 'a')
if (matrix_name in f):
del f[matrix_name]
f[matrix_name] = np.asarray(A, dtype=dtype)
f.close()<|docstring|>Save matrix.<|endoftext|> |
adcb713b1a4631b1b738c0d7c07af9dd2d61fc5fa14888854725cc3ca6aa2788 | def save_subgraph_size(filename, num):
'\n Save number of nodes in altered subgraph\n '
with open(filename, 'w') as f:
f.write(str(num)) | Save number of nodes in altered subgraph | src/common.py | save_subgraph_size | raphael-group/netmix | 10 | python | def save_subgraph_size(filename, num):
'\n \n '
with open(filename, 'w') as f:
f.write(str(num)) | def save_subgraph_size(filename, num):
'\n \n '
with open(filename, 'w') as f:
f.write(str(num))<|docstring|>Save number of nodes in altered subgraph<|endoftext|> |
0f80734ce2f8d90ab75fe4eb36a31a61cbcc739ca24f23914277e3d6d03b0fe4 | def status(message=''):
'\n Write status message to screen; overwrite previous status message and do not\n advance line.\n '
import sys
try:
length = status.length
except AttributeError:
length = 0
sys.stdout.write(((('\r' + (' ' * length)) + '\r') + str(message)))
sys.stdout.flush()
status.length = max(len(str(message).expandtabs()), length) | Write status message to screen; overwrite previous status message and do not
advance line. | src/common.py | status | raphael-group/netmix | 10 | python | def status(message=):
'\n Write status message to screen; overwrite previous status message and do not\n advance line.\n '
import sys
try:
length = status.length
except AttributeError:
length = 0
sys.stdout.write(((('\r' + (' ' * length)) + '\r') + str(message)))
sys.stdout.flush()
status.length = max(len(str(message).expandtabs()), length) | def status(message=):
'\n Write status message to screen; overwrite previous status message and do not\n advance line.\n '
import sys
try:
length = status.length
except AttributeError:
length = 0
sys.stdout.write(((('\r' + (' ' * length)) + '\r') + str(message)))
sys.stdout.flush()
status.length = max(len(str(message).expandtabs()), length)<|docstring|>Write status message to screen; overwrite previous status message and do not
advance line.<|endoftext|> |
52e3eba10a7b5cbe7e3caf72a4aa8b7e3eb206a34b58a25e6e402a1b461c5cf6 | def read(*parts):
'\n Build an absolute path from *parts* and and return the contents of the\n resulting file. Assume UTF-8 encoding.\n '
with codecs.open(os.path.join(HERE, *parts), 'rb', 'utf-8') as f:
return f.read() | Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding. | setup.py | read | freelawproject/jsondate3-aware | 1 | python | def read(*parts):
'\n Build an absolute path from *parts* and and return the contents of the\n resulting file. Assume UTF-8 encoding.\n '
with codecs.open(os.path.join(HERE, *parts), 'rb', 'utf-8') as f:
return f.read() | def read(*parts):
'\n Build an absolute path from *parts* and and return the contents of the\n resulting file. Assume UTF-8 encoding.\n '
with codecs.open(os.path.join(HERE, *parts), 'rb', 'utf-8') as f:
return f.read()<|docstring|>Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.<|endoftext|> |
58f41682181d4d85d6f25272ec57f210aeae14abd100976675d9444b50fa4484 | def get_queryset(self):
'Return the last five published polls'
return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] | Return the last five published polls | polls/views.py | get_queryset | vicknick/django-polls-simple | 0 | python | def get_queryset(self):
return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] | def get_queryset(self):
return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]<|docstring|>Return the last five published polls<|endoftext|> |
d2be1207cce521473b911a0d8a24486172584cd998fa171eca57dc6163112d29 | def get_queryset(self):
'\n\t\tExclude any polls that are not published yet\n\t\t'
return Poll.objects.filter(pub_date__lte=timezone.now()) | Exclude any polls that are not published yet | polls/views.py | get_queryset | vicknick/django-polls-simple | 0 | python | def get_queryset(self):
'\n\t\t\n\t\t'
return Poll.objects.filter(pub_date__lte=timezone.now()) | def get_queryset(self):
'\n\t\t\n\t\t'
return Poll.objects.filter(pub_date__lte=timezone.now())<|docstring|>Exclude any polls that are not published yet<|endoftext|> |
190f13de5517e3e3207952301eeb91a629bbfad19986fd3c740c2948288ce4b9 | def new_query():
'\n Obtain a new GPUStatCollection instance by querying nvidia-smi\n to get the list of GPUs and running process information.\n '
return GPUStatCollection.new_query() | Obtain a new GPUStatCollection instance by querying nvidia-smi
to get the list of GPUs and running process information. | gpustat.py | new_query | jabalazs/gpustat_standalone | 0 | python | def new_query():
'\n Obtain a new GPUStatCollection instance by querying nvidia-smi\n to get the list of GPUs and running process information.\n '
return GPUStatCollection.new_query() | def new_query():
'\n Obtain a new GPUStatCollection instance by querying nvidia-smi\n to get the list of GPUs and running process information.\n '
return GPUStatCollection.new_query()<|docstring|>Obtain a new GPUStatCollection instance by querying nvidia-smi
to get the list of GPUs and running process information.<|endoftext|> |
b3f0ece16c01789697f5a431d8342ba08b3da672e84b52b5e335d5f85f3ad11a | def print_gpustat(**args):
'\n Display the GPU query results into standard output.\n '
try:
gpu_stats = GPUStatCollection.new_query()
except CalledProcessError as e:
sys.stderr.write('Error on calling nvidia-smi\n')
sys.exit(1)
gpu_stats.print_formatted(sys.stdout, **args) | Display the GPU query results into standard output. | gpustat.py | print_gpustat | jabalazs/gpustat_standalone | 0 | python | def print_gpustat(**args):
'\n \n '
try:
gpu_stats = GPUStatCollection.new_query()
except CalledProcessError as e:
sys.stderr.write('Error on calling nvidia-smi\n')
sys.exit(1)
gpu_stats.print_formatted(sys.stdout, **args) | def print_gpustat(**args):
'\n \n '
try:
gpu_stats = GPUStatCollection.new_query()
except CalledProcessError as e:
sys.stderr.write('Error on calling nvidia-smi\n')
sys.exit(1)
gpu_stats.print_formatted(sys.stdout, **args)<|docstring|>Display the GPU query results into standard output.<|endoftext|> |
bca07c761b8c1f6c15325fc34d2b3c0a1bd66e22e1dcb6b2dfab5f97a30fa0db | def list_locations(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets all available geo-locations.\n\n This operation provides all the locations that are available for\n resource providers; however, each resource provider may support a\n subset of this list.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Location\n :rtype:\n ~azure.mgmt.subscription.models.LocationPaged[~azure.mgmt.subscription.models.Location]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list_locations.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.LocationPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.LocationPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | Gets all available geo-locations.
This operation provides all the locations that are available for
resource providers; however, each resource provider may support a
subset of this list.
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Location
:rtype:
~azure.mgmt.subscription.models.LocationPaged[~azure.mgmt.subscription.models.Location]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` | src/subscription/azext_subscription/subscription/operations/subscriptions_operations.py | list_locations | v-chhbhoi/azure-cli-extensions | 207 | python | def list_locations(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets all available geo-locations.\n\n This operation provides all the locations that are available for\n resource providers; however, each resource provider may support a\n subset of this list.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Location\n :rtype:\n ~azure.mgmt.subscription.models.LocationPaged[~azure.mgmt.subscription.models.Location]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list_locations.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.LocationPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.LocationPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | def list_locations(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets all available geo-locations.\n\n This operation provides all the locations that are available for\n resource providers; however, each resource provider may support a\n subset of this list.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Location\n :rtype:\n ~azure.mgmt.subscription.models.LocationPaged[~azure.mgmt.subscription.models.Location]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list_locations.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.LocationPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.LocationPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized<|docstring|>Gets all available geo-locations.
This operation provides all the locations that are available for
resource providers; however, each resource provider may support a
subset of this list.
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Location
:rtype:
~azure.mgmt.subscription.models.LocationPaged[~azure.mgmt.subscription.models.Location]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`<|endoftext|> |
48084956ac6820940d617c8b79be3ca0876450f26f00995c20c34e51bb0470df | def get(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets details about a specified subscription.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: Subscription or ClientRawResponse if raw=true\n :rtype: ~azure.mgmt.subscription.models.Subscription or\n ~msrest.pipeline.ClientRawResponse\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
url = self.get.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if (response.status_code == 200):
deserialized = self._deserialize('Subscription', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | Gets details about a specified subscription.
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Subscription or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.subscription.models.Subscription or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` | src/subscription/azext_subscription/subscription/operations/subscriptions_operations.py | get | v-chhbhoi/azure-cli-extensions | 207 | python | def get(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets details about a specified subscription.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: Subscription or ClientRawResponse if raw=true\n :rtype: ~azure.mgmt.subscription.models.Subscription or\n ~msrest.pipeline.ClientRawResponse\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
url = self.get.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if (response.status_code == 200):
deserialized = self._deserialize('Subscription', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | def get(self, subscription_id, custom_headers=None, raw=False, **operation_config):
'Gets details about a specified subscription.\n\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: Subscription or ClientRawResponse if raw=true\n :rtype: ~azure.mgmt.subscription.models.Subscription or\n ~msrest.pipeline.ClientRawResponse\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
url = self.get.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('subscription_id', subscription_id, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if (response.status_code == 200):
deserialized = self._deserialize('Subscription', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized<|docstring|>Gets details about a specified subscription.
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Subscription or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.subscription.models.Subscription or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`<|endoftext|> |
722e65ff55a7bb2d4a32389d32e30c37a15dded68a9cceaa8c9df68ad617d7b4 | def list(self, custom_headers=None, raw=False, **operation_config):
'Gets all subscriptions for a tenant.\n\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Subscription\n :rtype:\n ~azure.mgmt.subscription.models.SubscriptionPaged[~azure.mgmt.subscription.models.Subscription]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list.metadata['url']
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | Gets all subscriptions for a tenant.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Subscription
:rtype:
~azure.mgmt.subscription.models.SubscriptionPaged[~azure.mgmt.subscription.models.Subscription]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` | src/subscription/azext_subscription/subscription/operations/subscriptions_operations.py | list | v-chhbhoi/azure-cli-extensions | 207 | python | def list(self, custom_headers=None, raw=False, **operation_config):
'Gets all subscriptions for a tenant.\n\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Subscription\n :rtype:\n ~azure.mgmt.subscription.models.SubscriptionPaged[~azure.mgmt.subscription.models.Subscription]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list.metadata['url']
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | def list(self, custom_headers=None, raw=False, **operation_config):
'Gets all subscriptions for a tenant.\n\n :param dict custom_headers: headers that will be added to the request\n :param bool raw: returns the direct response alongside the\n deserialized response\n :param operation_config: :ref:`Operation configuration\n overrides<msrest:optionsforoperations>`.\n :return: An iterator like instance of Subscription\n :rtype:\n ~azure.mgmt.subscription.models.SubscriptionPaged[~azure.mgmt.subscription.models.Subscription]\n :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`\n '
def internal_paging(next_link=None, raw=False):
if (not next_link):
url = self.list.metadata['url']
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('self.api_version', self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if (self.config.accept_language is not None):
header_parameters['accept-language'] = self._serialize.header('self.config.accept_language', self.config.accept_language, 'str')
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if (response.status_code not in [200]):
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.SubscriptionPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized<|docstring|>Gets all subscriptions for a tenant.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Subscription
:rtype:
~azure.mgmt.subscription.models.SubscriptionPaged[~azure.mgmt.subscription.models.Subscription]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`<|endoftext|> |
b88fc881e58c7e6e8459328cb1672cf0bd72a717c6de883932866254a12f0839 | def calculate_time(self, cache_type, cache_time):
'Convert time to required unit\n Returns:\n self\n '
cache_type = cache_type.lower()
calc = 0
if (cache_type in ('second', 'seconds')):
calc = 1
elif (cache_type in ('minute', 'minutes')):
calc = 60
elif (cache_type in ('hour', 'hours')):
calc = (60 ** 2)
elif (cache_type in ('day', 'days')):
calc = (60 ** 3)
elif (cache_type in ('month', 'months')):
calc = (60 ** 4)
elif (cache_type in ('year', 'years')):
calc = (60 ** 5)
else:
raise ValueError('{0} is not a valid caching type.'.format(cache_type))
return (cache_time * calc) | Convert time to required unit
Returns:
self | masonite/drivers/cache/BaseCacheDriver.py | calculate_time | lazyguru/masonite | 95 | python | def calculate_time(self, cache_type, cache_time):
'Convert time to required unit\n Returns:\n self\n '
cache_type = cache_type.lower()
calc = 0
if (cache_type in ('second', 'seconds')):
calc = 1
elif (cache_type in ('minute', 'minutes')):
calc = 60
elif (cache_type in ('hour', 'hours')):
calc = (60 ** 2)
elif (cache_type in ('day', 'days')):
calc = (60 ** 3)
elif (cache_type in ('month', 'months')):
calc = (60 ** 4)
elif (cache_type in ('year', 'years')):
calc = (60 ** 5)
else:
raise ValueError('{0} is not a valid caching type.'.format(cache_type))
return (cache_time * calc) | def calculate_time(self, cache_type, cache_time):
'Convert time to required unit\n Returns:\n self\n '
cache_type = cache_type.lower()
calc = 0
if (cache_type in ('second', 'seconds')):
calc = 1
elif (cache_type in ('minute', 'minutes')):
calc = 60
elif (cache_type in ('hour', 'hours')):
calc = (60 ** 2)
elif (cache_type in ('day', 'days')):
calc = (60 ** 3)
elif (cache_type in ('month', 'months')):
calc = (60 ** 4)
elif (cache_type in ('year', 'years')):
calc = (60 ** 5)
else:
raise ValueError('{0} is not a valid caching type.'.format(cache_type))
return (cache_time * calc)<|docstring|>Convert time to required unit
Returns:
self<|endoftext|> |
41e6d1bd7d3597804a20344f8cc623b90f073f26969afb6e0448d46df6399d67 | def discover_events_service(self, version):
"Delegates discovery to grpc's dns name resolution.\n\n "
name = constants.EVENTS_SERVICE_NAME
(_, services) = self.c.health.service(name, tag='v1')
addresses = []
if (len(services) == 0):
raise ValueError('No addresses found for events service')
for service in services:
addresses.append('{}:{}'.format(service['Node']['Address'], service['Service']['Port']))
return ('ipv4:' + ','.join(addresses)) | Delegates discovery to grpc's dns name resolution. | python/mtap/_discovery.py | discover_events_service | benknoll-umn/mtap | 3 | python | def discover_events_service(self, version):
"\n\n "
name = constants.EVENTS_SERVICE_NAME
(_, services) = self.c.health.service(name, tag='v1')
addresses = []
if (len(services) == 0):
raise ValueError('No addresses found for events service')
for service in services:
addresses.append('{}:{}'.format(service['Node']['Address'], service['Service']['Port']))
return ('ipv4:' + ','.join(addresses)) | def discover_events_service(self, version):
"\n\n "
name = constants.EVENTS_SERVICE_NAME
(_, services) = self.c.health.service(name, tag='v1')
addresses = []
if (len(services) == 0):
raise ValueError('No addresses found for events service')
for service in services:
addresses.append('{}:{}'.format(service['Node']['Address'], service['Service']['Port']))
return ('ipv4:' + ','.join(addresses))<|docstring|>Delegates discovery to grpc's dns name resolution.<|endoftext|> |
81ba891de494d42683f988244f510adf7bd198f27fe6be9d773aa86a9665550b | def _conf2json(conf):
'Convert Ganesha config to JSON.'
token_list = [io.StringIO()]
state = {'in_quote': False, 'in_comment': False, 'escape': False}
cbk = []
for char in conf:
if state['in_quote']:
if (not state['escape']):
if (char == '"'):
state['in_quote'] = False
cbk.append((lambda : token_list.append(io.StringIO())))
elif (char == '\\'):
cbk.append((lambda : state.update({'escape': True})))
else:
if (char == '#'):
state['in_comment'] = True
if state['in_comment']:
if (char == '\n'):
state['in_comment'] = False
elif (char == '"'):
token_list.append(io.StringIO())
state['in_quote'] = True
state['escape'] = False
if (not state['in_comment']):
token_list[(- 1)].write(char)
while cbk:
cbk.pop(0)()
if state['in_quote']:
raise RuntimeError('Unterminated quoted string')
js_token_list = ['{']
for tok in token_list:
tok = tok.getvalue()
if (tok[0] == '"'):
js_token_list.append(tok)
continue
for (pat, s) in [('([^=\\s])\\s*{', '\\1={'), (';\\s*}', '}'), ('}\\s*([^}\\s])', '};\\1'), ('([;{}=])', ' \\1 ')]:
tok = re.sub(pat, s, tok)
for word in tok.split():
if (word == '='):
word = ':'
elif (word == ';'):
word = ','
elif ((word in ['{', '}']) or re.search('\\A-?[1-9]\\d*(\\.\\d+)?\\Z', word)):
pass
else:
word = jsonutils.dumps(word)
js_token_list.append(word)
js_token_list.append('}')
token_grp_list = []
for tok in js_token_list:
if (tok[0] == '"'):
if (not (token_grp_list and isinstance(token_grp_list[(- 1)], list))):
token_grp_list.append([])
token_grp_list[(- 1)].append(tok)
else:
token_grp_list.append(tok)
js_token_list2 = []
for x in token_grp_list:
if isinstance(x, list):
x = ''.join(((['"'] + [tok[1:(- 1)] for tok in x]) + ['"']))
js_token_list2.append(x)
return ''.join(js_token_list2) | Convert Ganesha config to JSON. | manila/share/drivers/ganesha/manager.py | _conf2json | openstack/manila | 159 | python | def _conf2json(conf):
token_list = [io.StringIO()]
state = {'in_quote': False, 'in_comment': False, 'escape': False}
cbk = []
for char in conf:
if state['in_quote']:
if (not state['escape']):
if (char == '"'):
state['in_quote'] = False
cbk.append((lambda : token_list.append(io.StringIO())))
elif (char == '\\'):
cbk.append((lambda : state.update({'escape': True})))
else:
if (char == '#'):
state['in_comment'] = True
if state['in_comment']:
if (char == '\n'):
state['in_comment'] = False
elif (char == '"'):
token_list.append(io.StringIO())
state['in_quote'] = True
state['escape'] = False
if (not state['in_comment']):
token_list[(- 1)].write(char)
while cbk:
cbk.pop(0)()
if state['in_quote']:
raise RuntimeError('Unterminated quoted string')
js_token_list = ['{']
for tok in token_list:
tok = tok.getvalue()
if (tok[0] == '"'):
js_token_list.append(tok)
continue
for (pat, s) in [('([^=\\s])\\s*{', '\\1={'), (';\\s*}', '}'), ('}\\s*([^}\\s])', '};\\1'), ('([;{}=])', ' \\1 ')]:
tok = re.sub(pat, s, tok)
for word in tok.split():
if (word == '='):
word = ':'
elif (word == ';'):
word = ','
elif ((word in ['{', '}']) or re.search('\\A-?[1-9]\\d*(\\.\\d+)?\\Z', word)):
pass
else:
word = jsonutils.dumps(word)
js_token_list.append(word)
js_token_list.append('}')
token_grp_list = []
for tok in js_token_list:
if (tok[0] == '"'):
if (not (token_grp_list and isinstance(token_grp_list[(- 1)], list))):
token_grp_list.append([])
token_grp_list[(- 1)].append(tok)
else:
token_grp_list.append(tok)
js_token_list2 = []
for x in token_grp_list:
if isinstance(x, list):
x = .join(((['"'] + [tok[1:(- 1)] for tok in x]) + ['"']))
js_token_list2.append(x)
return .join(js_token_list2) | def _conf2json(conf):
token_list = [io.StringIO()]
state = {'in_quote': False, 'in_comment': False, 'escape': False}
cbk = []
for char in conf:
if state['in_quote']:
if (not state['escape']):
if (char == '"'):
state['in_quote'] = False
cbk.append((lambda : token_list.append(io.StringIO())))
elif (char == '\\'):
cbk.append((lambda : state.update({'escape': True})))
else:
if (char == '#'):
state['in_comment'] = True
if state['in_comment']:
if (char == '\n'):
state['in_comment'] = False
elif (char == '"'):
token_list.append(io.StringIO())
state['in_quote'] = True
state['escape'] = False
if (not state['in_comment']):
token_list[(- 1)].write(char)
while cbk:
cbk.pop(0)()
if state['in_quote']:
raise RuntimeError('Unterminated quoted string')
js_token_list = ['{']
for tok in token_list:
tok = tok.getvalue()
if (tok[0] == '"'):
js_token_list.append(tok)
continue
for (pat, s) in [('([^=\\s])\\s*{', '\\1={'), (';\\s*}', '}'), ('}\\s*([^}\\s])', '};\\1'), ('([;{}=])', ' \\1 ')]:
tok = re.sub(pat, s, tok)
for word in tok.split():
if (word == '='):
word = ':'
elif (word == ';'):
word = ','
elif ((word in ['{', '}']) or re.search('\\A-?[1-9]\\d*(\\.\\d+)?\\Z', word)):
pass
else:
word = jsonutils.dumps(word)
js_token_list.append(word)
js_token_list.append('}')
token_grp_list = []
for tok in js_token_list:
if (tok[0] == '"'):
if (not (token_grp_list and isinstance(token_grp_list[(- 1)], list))):
token_grp_list.append([])
token_grp_list[(- 1)].append(tok)
else:
token_grp_list.append(tok)
js_token_list2 = []
for x in token_grp_list:
if isinstance(x, list):
x = .join(((['"'] + [tok[1:(- 1)] for tok in x]) + ['"']))
js_token_list2.append(x)
return .join(js_token_list2)<|docstring|>Convert Ganesha config to JSON.<|endoftext|> |
b398880f3c66067feaaa05fa686562dfff71fb9d8a6cbdc3066f12f19dc3d957 | def _dump_to_conf(confdict, out=sys.stdout, indent=0):
'Output confdict in Ganesha config format.'
if isinstance(confdict, dict):
for (k, v) in confdict.items():
if (v is None):
continue
if isinstance(v, dict):
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(v, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}'))
elif isinstance(v, list):
for item in v:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(item, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}\n'))
elif (k.upper() == 'CLIENTS'):
out.write((((((' ' * (indent * IWIDTH)) + k) + ' = ') + v) + ';'))
else:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('= ')
_dump_to_conf(v, out, indent)
out.write(';')
out.write('\n')
else:
dj = jsonutils.dumps(confdict)
out.write(dj) | Output confdict in Ganesha config format. | manila/share/drivers/ganesha/manager.py | _dump_to_conf | openstack/manila | 159 | python | def _dump_to_conf(confdict, out=sys.stdout, indent=0):
if isinstance(confdict, dict):
for (k, v) in confdict.items():
if (v is None):
continue
if isinstance(v, dict):
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(v, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}'))
elif isinstance(v, list):
for item in v:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(item, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}\n'))
elif (k.upper() == 'CLIENTS'):
out.write((((((' ' * (indent * IWIDTH)) + k) + ' = ') + v) + ';'))
else:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('= ')
_dump_to_conf(v, out, indent)
out.write(';')
out.write('\n')
else:
dj = jsonutils.dumps(confdict)
out.write(dj) | def _dump_to_conf(confdict, out=sys.stdout, indent=0):
if isinstance(confdict, dict):
for (k, v) in confdict.items():
if (v is None):
continue
if isinstance(v, dict):
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(v, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}'))
elif isinstance(v, list):
for item in v:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('{\n')
_dump_to_conf(item, out, (indent + 1))
out.write(((' ' * (indent * IWIDTH)) + '}\n'))
elif (k.upper() == 'CLIENTS'):
out.write((((((' ' * (indent * IWIDTH)) + k) + ' = ') + v) + ';'))
else:
out.write((((' ' * (indent * IWIDTH)) + k) + ' '))
out.write('= ')
_dump_to_conf(v, out, indent)
out.write(';')
out.write('\n')
else:
dj = jsonutils.dumps(confdict)
out.write(dj)<|docstring|>Output confdict in Ganesha config format.<|endoftext|> |
64b71655e4ca776097a278fcdb08bf07ad9ccabc0469662defcbcee4cd4fb775 | def parseconf(conf):
'Parse Ganesha config.\n\n Both native format and JSON are supported.\n\n Convert config to a (nested) dictionary.\n '
def list_to_dict(src_list):
dst_dict = {}
for i in src_list:
if isinstance(i, tuple):
(k, v) = i
if isinstance(v, list):
v = list_to_dict(v)
if (k in dst_dict):
dst_dict[k] = [dst_dict[k]]
dst_dict[k].append(v)
else:
dst_dict[k] = v
return dst_dict
try:
d = jsonutils.loads(conf)
except ValueError:
li = jsonutils.loads(_conf2json(conf), object_pairs_hook=(lambda x: x))
d = list_to_dict(li)
return d | Parse Ganesha config.
Both native format and JSON are supported.
Convert config to a (nested) dictionary. | manila/share/drivers/ganesha/manager.py | parseconf | openstack/manila | 159 | python | def parseconf(conf):
'Parse Ganesha config.\n\n Both native format and JSON are supported.\n\n Convert config to a (nested) dictionary.\n '
def list_to_dict(src_list):
dst_dict = {}
for i in src_list:
if isinstance(i, tuple):
(k, v) = i
if isinstance(v, list):
v = list_to_dict(v)
if (k in dst_dict):
dst_dict[k] = [dst_dict[k]]
dst_dict[k].append(v)
else:
dst_dict[k] = v
return dst_dict
try:
d = jsonutils.loads(conf)
except ValueError:
li = jsonutils.loads(_conf2json(conf), object_pairs_hook=(lambda x: x))
d = list_to_dict(li)
return d | def parseconf(conf):
'Parse Ganesha config.\n\n Both native format and JSON are supported.\n\n Convert config to a (nested) dictionary.\n '
def list_to_dict(src_list):
dst_dict = {}
for i in src_list:
if isinstance(i, tuple):
(k, v) = i
if isinstance(v, list):
v = list_to_dict(v)
if (k in dst_dict):
dst_dict[k] = [dst_dict[k]]
dst_dict[k].append(v)
else:
dst_dict[k] = v
return dst_dict
try:
d = jsonutils.loads(conf)
except ValueError:
li = jsonutils.loads(_conf2json(conf), object_pairs_hook=(lambda x: x))
d = list_to_dict(li)
return d<|docstring|>Parse Ganesha config.
Both native format and JSON are supported.
Convert config to a (nested) dictionary.<|endoftext|> |
599355b4f55b0cd53749ff509927cf0152a9c76ca720555e3ce3e4f5d79ba567 | def mkconf(confdict):
'Create Ganesha config string from confdict.'
s = io.StringIO()
_dump_to_conf(confdict, s)
return s.getvalue() | Create Ganesha config string from confdict. | manila/share/drivers/ganesha/manager.py | mkconf | openstack/manila | 159 | python | def mkconf(confdict):
s = io.StringIO()
_dump_to_conf(confdict, s)
return s.getvalue() | def mkconf(confdict):
s = io.StringIO()
_dump_to_conf(confdict, s)
return s.getvalue()<|docstring|>Create Ganesha config string from confdict.<|endoftext|> |
3017ef6a633a382e4450cba2c79d33baf364e95caae1a59bf9db48950949e69d | def _getpath(self, name):
'Get the path of config file for name.'
return os.path.join(self.ganesha_export_dir, (name + '.conf')) | Get the path of config file for name. | manila/share/drivers/ganesha/manager.py | _getpath | openstack/manila | 159 | python | def _getpath(self, name):
return os.path.join(self.ganesha_export_dir, (name + '.conf')) | def _getpath(self, name):
return os.path.join(self.ganesha_export_dir, (name + '.conf'))<|docstring|>Get the path of config file for name.<|endoftext|> |
ccb5c60533be706ae1976f736698c988000068693947afe4b99e4d3f027420f9 | def _write_tmp_conf_file(self, path, data):
'Write data to tmp conf file.'
(dirpath, fname) = (getattr(os.path, (q + 'name'))(path) for q in ('dir', 'base'))
tmpf = self.execute('mktemp', '-p', dirpath, '-t', (fname + '.XXXXXX'))[0][:(- 1)]
self.execute('sh', '-c', ('echo %s > %s' % (pipes.quote(data), pipes.quote(tmpf))), message=('writing ' + tmpf))
return tmpf | Write data to tmp conf file. | manila/share/drivers/ganesha/manager.py | _write_tmp_conf_file | openstack/manila | 159 | python | def _write_tmp_conf_file(self, path, data):
(dirpath, fname) = (getattr(os.path, (q + 'name'))(path) for q in ('dir', 'base'))
tmpf = self.execute('mktemp', '-p', dirpath, '-t', (fname + '.XXXXXX'))[0][:(- 1)]
self.execute('sh', '-c', ('echo %s > %s' % (pipes.quote(data), pipes.quote(tmpf))), message=('writing ' + tmpf))
return tmpf | def _write_tmp_conf_file(self, path, data):
(dirpath, fname) = (getattr(os.path, (q + 'name'))(path) for q in ('dir', 'base'))
tmpf = self.execute('mktemp', '-p', dirpath, '-t', (fname + '.XXXXXX'))[0][:(- 1)]
self.execute('sh', '-c', ('echo %s > %s' % (pipes.quote(data), pipes.quote(tmpf))), message=('writing ' + tmpf))
return tmpf<|docstring|>Write data to tmp conf file.<|endoftext|> |
2634e87bdacc047e6d40c803bf925fb68377d8c42b1fcbd3bbdd4176ba3c0148 | def _write_conf_file(self, name, data):
'Write data to config file for name atomically.'
path = self._getpath(name)
tmpf = self._write_tmp_conf_file(path, data)
try:
self.execute('mv', tmpf, path)
except exception.ProcessExecutionError as e:
LOG.error('mv temp file ({0}) to {1} failed.'.format(tmpf, path))
self.execute('rm', tmpf)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
return path | Write data to config file for name atomically. | manila/share/drivers/ganesha/manager.py | _write_conf_file | openstack/manila | 159 | python | def _write_conf_file(self, name, data):
path = self._getpath(name)
tmpf = self._write_tmp_conf_file(path, data)
try:
self.execute('mv', tmpf, path)
except exception.ProcessExecutionError as e:
LOG.error('mv temp file ({0}) to {1} failed.'.format(tmpf, path))
self.execute('rm', tmpf)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
return path | def _write_conf_file(self, name, data):
path = self._getpath(name)
tmpf = self._write_tmp_conf_file(path, data)
try:
self.execute('mv', tmpf, path)
except exception.ProcessExecutionError as e:
LOG.error('mv temp file ({0}) to {1} failed.'.format(tmpf, path))
self.execute('rm', tmpf)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
return path<|docstring|>Write data to config file for name atomically.<|endoftext|> |
4da014a785476a7a93419179c63c369eec5671feddf1019fe1ad978af54c96ff | def _mkindex(self):
'Generate the index file for current exports.'
@utils.synchronized(('ganesha-index-' + self.tag), external=True)
def _mkindex():
files = filter((lambda f: (self.confrx.search(f) and (f != 'INDEX.conf'))), self.execute('ls', self.ganesha_export_dir, run_as_root=False)[0].split('\n'))
index = ''.join(map((lambda f: (('%include ' + os.path.join(self.ganesha_export_dir, f)) + '\n')), files))
self._write_conf_file('INDEX', index)
_mkindex() | Generate the index file for current exports. | manila/share/drivers/ganesha/manager.py | _mkindex | openstack/manila | 159 | python | def _mkindex(self):
@utils.synchronized(('ganesha-index-' + self.tag), external=True)
def _mkindex():
files = filter((lambda f: (self.confrx.search(f) and (f != 'INDEX.conf'))), self.execute('ls', self.ganesha_export_dir, run_as_root=False)[0].split('\n'))
index = .join(map((lambda f: (('%include ' + os.path.join(self.ganesha_export_dir, f)) + '\n')), files))
self._write_conf_file('INDEX', index)
_mkindex() | def _mkindex(self):
@utils.synchronized(('ganesha-index-' + self.tag), external=True)
def _mkindex():
files = filter((lambda f: (self.confrx.search(f) and (f != 'INDEX.conf'))), self.execute('ls', self.ganesha_export_dir, run_as_root=False)[0].split('\n'))
index = .join(map((lambda f: (('%include ' + os.path.join(self.ganesha_export_dir, f)) + '\n')), files))
self._write_conf_file('INDEX', index)
_mkindex()<|docstring|>Generate the index file for current exports.<|endoftext|> |
0b54689107a63dccf219847b076b82d8bf56dfe71e3a8e279a3bc0e6bafa679c | def _read_export(self, name):
'Return the dict of the export identified by name.'
if self.ganesha_rados_store_enable:
return self._read_export_rados_object(name)
else:
return self._read_export_file(name) | Return the dict of the export identified by name. | manila/share/drivers/ganesha/manager.py | _read_export | openstack/manila | 159 | python | def _read_export(self, name):
if self.ganesha_rados_store_enable:
return self._read_export_rados_object(name)
else:
return self._read_export_file(name) | def _read_export(self, name):
if self.ganesha_rados_store_enable:
return self._read_export_rados_object(name)
else:
return self._read_export_file(name)<|docstring|>Return the dict of the export identified by name.<|endoftext|> |
1132b61b717542ddf9e9c8dc321abea708219d32d0b56b8ee478bc08f1aff811 | def check_export_exists(self, name):
'Check whether export exists.'
if self.ganesha_rados_store_enable:
return self._check_export_rados_object_exists(name)
else:
return self._check_export_file_exists(name) | Check whether export exists. | manila/share/drivers/ganesha/manager.py | check_export_exists | openstack/manila | 159 | python | def check_export_exists(self, name):
if self.ganesha_rados_store_enable:
return self._check_export_rados_object_exists(name)
else:
return self._check_export_file_exists(name) | def check_export_exists(self, name):
if self.ganesha_rados_store_enable:
return self._check_export_rados_object_exists(name)
else:
return self._check_export_file_exists(name)<|docstring|>Check whether export exists.<|endoftext|> |
c476efd851d2e2dd67cf4fb1d7f94fa7250b5b5a00864d21918d608478cc3968 | def _write_export_rados_object(self, name, data):
'Write confdict to the export RADOS object of name.'
self._put_rados_object(self._get_export_rados_object_name(name), data)
return self._write_tmp_conf_file(self._getpath(name), data) | Write confdict to the export RADOS object of name. | manila/share/drivers/ganesha/manager.py | _write_export_rados_object | openstack/manila | 159 | python | def _write_export_rados_object(self, name, data):
self._put_rados_object(self._get_export_rados_object_name(name), data)
return self._write_tmp_conf_file(self._getpath(name), data) | def _write_export_rados_object(self, name, data):
self._put_rados_object(self._get_export_rados_object_name(name), data)
return self._write_tmp_conf_file(self._getpath(name), data)<|docstring|>Write confdict to the export RADOS object of name.<|endoftext|> |
9def4d8c81485b30d38fe97a6fb71fdf370812fc209212bfa96b02f574141e4d | def _write_export(self, name, confdict):
'Write confdict to the export file or RADOS object of name.'
for (k, v) in ganesha_utils.walk(confdict):
if (isinstance(v, str) and (v[0] == '@')):
msg = (_('Incomplete export block: value %(val)s of attribute %(key)s is a stub.') % {'key': k, 'val': v})
raise exception.InvalidParameterValue(err=msg)
if self.ganesha_rados_store_enable:
return self._write_export_rados_object(name, mkconf(confdict))
else:
return self._write_conf_file(name, mkconf(confdict)) | Write confdict to the export file or RADOS object of name. | manila/share/drivers/ganesha/manager.py | _write_export | openstack/manila | 159 | python | def _write_export(self, name, confdict):
for (k, v) in ganesha_utils.walk(confdict):
if (isinstance(v, str) and (v[0] == '@')):
msg = (_('Incomplete export block: value %(val)s of attribute %(key)s is a stub.') % {'key': k, 'val': v})
raise exception.InvalidParameterValue(err=msg)
if self.ganesha_rados_store_enable:
return self._write_export_rados_object(name, mkconf(confdict))
else:
return self._write_conf_file(name, mkconf(confdict)) | def _write_export(self, name, confdict):
for (k, v) in ganesha_utils.walk(confdict):
if (isinstance(v, str) and (v[0] == '@')):
msg = (_('Incomplete export block: value %(val)s of attribute %(key)s is a stub.') % {'key': k, 'val': v})
raise exception.InvalidParameterValue(err=msg)
if self.ganesha_rados_store_enable:
return self._write_export_rados_object(name, mkconf(confdict))
else:
return self._write_conf_file(name, mkconf(confdict))<|docstring|>Write confdict to the export file or RADOS object of name.<|endoftext|> |
adee10bb1424ae17b04bb60b90cc36a84e65908b826c38de73a19b8ebd853fbd | def _rm_export_file(self, name):
'Remove export file of name.'
self._rm_file(self._getpath(name)) | Remove export file of name. | manila/share/drivers/ganesha/manager.py | _rm_export_file | openstack/manila | 159 | python | def _rm_export_file(self, name):
self._rm_file(self._getpath(name)) | def _rm_export_file(self, name):
self._rm_file(self._getpath(name))<|docstring|>Remove export file of name.<|endoftext|> |
5ab76dac8e6c791c029d84b9db9afc7af1101edf1567cde3661ef344a01af35e | def _rm_export_rados_object(self, name):
'Remove export object of name.'
self._delete_rados_object(self._get_export_rados_object_name(name)) | Remove export object of name. | manila/share/drivers/ganesha/manager.py | _rm_export_rados_object | openstack/manila | 159 | python | def _rm_export_rados_object(self, name):
self._delete_rados_object(self._get_export_rados_object_name(name)) | def _rm_export_rados_object(self, name):
self._delete_rados_object(self._get_export_rados_object_name(name))<|docstring|>Remove export object of name.<|endoftext|> |
9019619eb27ecfe18019bb3bfc2fa91dcee11491c73d7e3f02baf3a701f7f797 | def _dbus_send_ganesha(self, method, *args, **kwargs):
'Send a message to Ganesha via dbus.'
service = kwargs.pop('service', 'exportmgr')
self.execute('dbus-send', '--print-reply', '--system', '--dest=org.ganesha.nfsd', '/org/ganesha/nfsd/ExportMgr', ('org.ganesha.nfsd.%s.%s' % (service, method)), *args, message=('dbus call %s.%s' % (service, method)), **kwargs) | Send a message to Ganesha via dbus. | manila/share/drivers/ganesha/manager.py | _dbus_send_ganesha | openstack/manila | 159 | python | def _dbus_send_ganesha(self, method, *args, **kwargs):
service = kwargs.pop('service', 'exportmgr')
self.execute('dbus-send', '--print-reply', '--system', '--dest=org.ganesha.nfsd', '/org/ganesha/nfsd/ExportMgr', ('org.ganesha.nfsd.%s.%s' % (service, method)), *args, message=('dbus call %s.%s' % (service, method)), **kwargs) | def _dbus_send_ganesha(self, method, *args, **kwargs):
service = kwargs.pop('service', 'exportmgr')
self.execute('dbus-send', '--print-reply', '--system', '--dest=org.ganesha.nfsd', '/org/ganesha/nfsd/ExportMgr', ('org.ganesha.nfsd.%s.%s' % (service, method)), *args, message=('dbus call %s.%s' % (service, method)), **kwargs)<|docstring|>Send a message to Ganesha via dbus.<|endoftext|> |
5f22351a9039a132216577a74d54bbacafb3bdf987461edf1c3709ca8e406a1e | def _remove_export_dbus(self, xid):
'Remove an export from Ganesha runtime with given export id.'
self._dbus_send_ganesha('RemoveExport', ('uint16:%d' % xid)) | Remove an export from Ganesha runtime with given export id. | manila/share/drivers/ganesha/manager.py | _remove_export_dbus | openstack/manila | 159 | python | def _remove_export_dbus(self, xid):
self._dbus_send_ganesha('RemoveExport', ('uint16:%d' % xid)) | def _remove_export_dbus(self, xid):
self._dbus_send_ganesha('RemoveExport', ('uint16:%d' % xid))<|docstring|>Remove an export from Ganesha runtime with given export id.<|endoftext|> |
d88f413e1e17caffa66862c08cae05dc2302f2b9c8aa4f8ecd18bcef1455e8d5 | def _add_rados_object_url_to_index(self, name):
"Add an export RADOS object's URL to the RADOS URL index."
index_data = self._get_rados_object(self.ganesha_rados_export_index)
want_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
if index_data:
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join([index_data, want_url]))
else:
self._put_rados_object(self.ganesha_rados_export_index, want_url) | Add an export RADOS object's URL to the RADOS URL index. | manila/share/drivers/ganesha/manager.py | _add_rados_object_url_to_index | openstack/manila | 159 | python | def _add_rados_object_url_to_index(self, name):
index_data = self._get_rados_object(self.ganesha_rados_export_index)
want_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
if index_data:
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join([index_data, want_url]))
else:
self._put_rados_object(self.ganesha_rados_export_index, want_url) | def _add_rados_object_url_to_index(self, name):
index_data = self._get_rados_object(self.ganesha_rados_export_index)
want_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
if index_data:
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join([index_data, want_url]))
else:
self._put_rados_object(self.ganesha_rados_export_index, want_url)<|docstring|>Add an export RADOS object's URL to the RADOS URL index.<|endoftext|> |
ea9fc084f48872b849dc52a7b90b7ed70076728bb8b1e025484370b0436ee586 | def _remove_rados_object_url_from_index(self, name):
"Remove an export RADOS object's URL from the RADOS URL index."
index_data = self._get_rados_object(self.ganesha_rados_export_index)
if (not index_data):
return
unwanted_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
rados_urls = index_data.split('\n')
new_rados_urls = [url for url in rados_urls if (url != unwanted_url)]
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join(new_rados_urls)) | Remove an export RADOS object's URL from the RADOS URL index. | manila/share/drivers/ganesha/manager.py | _remove_rados_object_url_from_index | openstack/manila | 159 | python | def _remove_rados_object_url_from_index(self, name):
index_data = self._get_rados_object(self.ganesha_rados_export_index)
if (not index_data):
return
unwanted_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
rados_urls = index_data.split('\n')
new_rados_urls = [url for url in rados_urls if (url != unwanted_url)]
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join(new_rados_urls)) | def _remove_rados_object_url_from_index(self, name):
index_data = self._get_rados_object(self.ganesha_rados_export_index)
if (not index_data):
return
unwanted_url = '%url rados://{0}/{1}'.format(self.ganesha_rados_store_pool_name, self._get_export_rados_object_name(name))
rados_urls = index_data.split('\n')
new_rados_urls = [url for url in rados_urls if (url != unwanted_url)]
self._put_rados_object(self.ganesha_rados_export_index, '\n'.join(new_rados_urls))<|docstring|>Remove an export RADOS object's URL from the RADOS URL index.<|endoftext|> |
e1d557f28dc5f2a3073548180f5002dc180190942c3a305e9cccf627928e1663 | def add_export(self, name, confdict):
'Add an export to Ganesha specified by confdict.'
xid = confdict['EXPORT']['Export_Id']
undos = []
_mkindex_called = False
try:
path = self._write_export(name, confdict)
if self.ganesha_rados_store_enable:
undos.append((lambda : self._rm_export_rados_object(name)))
undos.append((lambda : self._rm_file(path)))
else:
undos.append((lambda : self._rm_export_file(name)))
self._dbus_send_ganesha('AddExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
undos.append((lambda : self._remove_export_dbus(xid)))
if self.ganesha_rados_store_enable:
self._rm_file(path)
self._add_rados_object_url_to_index(name)
else:
_mkindex_called = True
self._mkindex()
except exception.ProcessExecutionError as e:
for u in undos:
u()
if ((not self.ganesha_rados_store_enable) and (not _mkindex_called)):
self._mkindex()
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd) | Add an export to Ganesha specified by confdict. | manila/share/drivers/ganesha/manager.py | add_export | openstack/manila | 159 | python | def add_export(self, name, confdict):
xid = confdict['EXPORT']['Export_Id']
undos = []
_mkindex_called = False
try:
path = self._write_export(name, confdict)
if self.ganesha_rados_store_enable:
undos.append((lambda : self._rm_export_rados_object(name)))
undos.append((lambda : self._rm_file(path)))
else:
undos.append((lambda : self._rm_export_file(name)))
self._dbus_send_ganesha('AddExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
undos.append((lambda : self._remove_export_dbus(xid)))
if self.ganesha_rados_store_enable:
self._rm_file(path)
self._add_rados_object_url_to_index(name)
else:
_mkindex_called = True
self._mkindex()
except exception.ProcessExecutionError as e:
for u in undos:
u()
if ((not self.ganesha_rados_store_enable) and (not _mkindex_called)):
self._mkindex()
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd) | def add_export(self, name, confdict):
xid = confdict['EXPORT']['Export_Id']
undos = []
_mkindex_called = False
try:
path = self._write_export(name, confdict)
if self.ganesha_rados_store_enable:
undos.append((lambda : self._rm_export_rados_object(name)))
undos.append((lambda : self._rm_file(path)))
else:
undos.append((lambda : self._rm_export_file(name)))
self._dbus_send_ganesha('AddExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
undos.append((lambda : self._remove_export_dbus(xid)))
if self.ganesha_rados_store_enable:
self._rm_file(path)
self._add_rados_object_url_to_index(name)
else:
_mkindex_called = True
self._mkindex()
except exception.ProcessExecutionError as e:
for u in undos:
u()
if ((not self.ganesha_rados_store_enable) and (not _mkindex_called)):
self._mkindex()
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)<|docstring|>Add an export to Ganesha specified by confdict.<|endoftext|> |
bf0648456837d563081c91000cbbdf5297656bb275dc52d72ccd8b48dc0875cc | def update_export(self, name, confdict):
'Update an export to Ganesha specified by confdict.'
xid = confdict['EXPORT']['Export_Id']
old_confdict = self._read_export(name)
path = self._write_export(name, confdict)
try:
self._dbus_send_ganesha('UpdateExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
except exception.ProcessExecutionError as e:
self._write_export(name, old_confdict)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
finally:
if self.ganesha_rados_store_enable:
self._rm_file(path) | Update an export to Ganesha specified by confdict. | manila/share/drivers/ganesha/manager.py | update_export | openstack/manila | 159 | python | def update_export(self, name, confdict):
xid = confdict['EXPORT']['Export_Id']
old_confdict = self._read_export(name)
path = self._write_export(name, confdict)
try:
self._dbus_send_ganesha('UpdateExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
except exception.ProcessExecutionError as e:
self._write_export(name, old_confdict)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
finally:
if self.ganesha_rados_store_enable:
self._rm_file(path) | def update_export(self, name, confdict):
xid = confdict['EXPORT']['Export_Id']
old_confdict = self._read_export(name)
path = self._write_export(name, confdict)
try:
self._dbus_send_ganesha('UpdateExport', ('string:' + path), ('string:EXPORT(Export_Id=%d)' % xid))
except exception.ProcessExecutionError as e:
self._write_export(name, old_confdict)
raise exception.GaneshaCommandFailure(stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
finally:
if self.ganesha_rados_store_enable:
self._rm_file(path)<|docstring|>Update an export to Ganesha specified by confdict.<|endoftext|> |
3d1fca3f67d555205040ddea2c57086fd145b83061f87c3e75206984ff051343 | def remove_export(self, name):
'Remove an export from Ganesha.'
try:
confdict = self._read_export(name)
self._remove_export_dbus(confdict['EXPORT']['Export_Id'])
finally:
if self.ganesha_rados_store_enable:
self._delete_rados_object(self._get_export_rados_object_name(name))
self._remove_rados_object_url_from_index(name)
else:
self._rm_export_file(name)
self._mkindex() | Remove an export from Ganesha. | manila/share/drivers/ganesha/manager.py | remove_export | openstack/manila | 159 | python | def remove_export(self, name):
try:
confdict = self._read_export(name)
self._remove_export_dbus(confdict['EXPORT']['Export_Id'])
finally:
if self.ganesha_rados_store_enable:
self._delete_rados_object(self._get_export_rados_object_name(name))
self._remove_rados_object_url_from_index(name)
else:
self._rm_export_file(name)
self._mkindex() | def remove_export(self, name):
try:
confdict = self._read_export(name)
self._remove_export_dbus(confdict['EXPORT']['Export_Id'])
finally:
if self.ganesha_rados_store_enable:
self._delete_rados_object(self._get_export_rados_object_name(name))
self._remove_rados_object_url_from_index(name)
else:
self._rm_export_file(name)
self._mkindex()<|docstring|>Remove an export from Ganesha.<|endoftext|> |
fcf4cf9cdfeb14bbe2553c79c7f4066a3f51d79275575dc041e88e2d75072d79 | def _get_rados_object(self, object_name):
'Synchronously read data from Ceph RADOS object as a text string.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :returns: tuple of object data and version\n '
pool_name = self.ganesha_rados_store_pool_name
ioctx = self.rados_client.open_ioctx(pool_name)
osd_max_write_size = self.rados_client.conf_get('osd_max_write_size')
max_size = ((int(osd_max_write_size) * 1024) * 1024)
try:
bytes_read = ioctx.read(object_name, max_size)
if ((len(bytes_read) == max_size) and ioctx.read(object_name, 1, offset=max_size)):
LOG.warning("Size of object {0} exceeds '{1}' bytes read".format(object_name, max_size))
finally:
ioctx.close()
bytes_read_decoded = bytes_read.decode('utf-8')
return bytes_read_decoded | Synchronously read data from Ceph RADOS object as a text string.
:param pool_name: name of the pool
:type pool_name: str
:param object_name: name of the object
:type object_name: str
:returns: tuple of object data and version | manila/share/drivers/ganesha/manager.py | _get_rados_object | openstack/manila | 159 | python | def _get_rados_object(self, object_name):
'Synchronously read data from Ceph RADOS object as a text string.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :returns: tuple of object data and version\n '
pool_name = self.ganesha_rados_store_pool_name
ioctx = self.rados_client.open_ioctx(pool_name)
osd_max_write_size = self.rados_client.conf_get('osd_max_write_size')
max_size = ((int(osd_max_write_size) * 1024) * 1024)
try:
bytes_read = ioctx.read(object_name, max_size)
if ((len(bytes_read) == max_size) and ioctx.read(object_name, 1, offset=max_size)):
LOG.warning("Size of object {0} exceeds '{1}' bytes read".format(object_name, max_size))
finally:
ioctx.close()
bytes_read_decoded = bytes_read.decode('utf-8')
return bytes_read_decoded | def _get_rados_object(self, object_name):
'Synchronously read data from Ceph RADOS object as a text string.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :returns: tuple of object data and version\n '
pool_name = self.ganesha_rados_store_pool_name
ioctx = self.rados_client.open_ioctx(pool_name)
osd_max_write_size = self.rados_client.conf_get('osd_max_write_size')
max_size = ((int(osd_max_write_size) * 1024) * 1024)
try:
bytes_read = ioctx.read(object_name, max_size)
if ((len(bytes_read) == max_size) and ioctx.read(object_name, 1, offset=max_size)):
LOG.warning("Size of object {0} exceeds '{1}' bytes read".format(object_name, max_size))
finally:
ioctx.close()
bytes_read_decoded = bytes_read.decode('utf-8')
return bytes_read_decoded<|docstring|>Synchronously read data from Ceph RADOS object as a text string.
:param pool_name: name of the pool
:type pool_name: str
:param object_name: name of the object
:type object_name: str
:returns: tuple of object data and version<|endoftext|> |
98336a4ae3dbda126cd74154d8594236340ff50b5d96ce6b4aa19d0e45bd7016 | def _put_rados_object(self, object_name, data):
'Synchronously write data as a byte string in a Ceph RADOS object.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :param data: data to write\n :type data: bytes\n '
pool_name = self.ganesha_rados_store_pool_name
encoded_data = data.encode('utf-8')
ioctx = self.rados_client.open_ioctx(pool_name)
max_size = ((int(self.rados_client.conf_get('osd_max_write_size')) * 1024) * 1024)
if (len(encoded_data) > max_size):
msg = "Data to be written to object '{0}' exceeds {1} bytes".format(object_name, max_size)
LOG.error(msg)
raise exception.ShareBackendException(msg)
try:
with rados.WriteOpCtx() as wop:
wop.write_full(encoded_data)
ioctx.operate_write_op(wop, object_name)
except rados.OSError as e:
LOG.error(e)
raise e
finally:
ioctx.close() | Synchronously write data as a byte string in a Ceph RADOS object.
:param pool_name: name of the pool
:type pool_name: str
:param object_name: name of the object
:type object_name: str
:param data: data to write
:type data: bytes | manila/share/drivers/ganesha/manager.py | _put_rados_object | openstack/manila | 159 | python | def _put_rados_object(self, object_name, data):
'Synchronously write data as a byte string in a Ceph RADOS object.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :param data: data to write\n :type data: bytes\n '
pool_name = self.ganesha_rados_store_pool_name
encoded_data = data.encode('utf-8')
ioctx = self.rados_client.open_ioctx(pool_name)
max_size = ((int(self.rados_client.conf_get('osd_max_write_size')) * 1024) * 1024)
if (len(encoded_data) > max_size):
msg = "Data to be written to object '{0}' exceeds {1} bytes".format(object_name, max_size)
LOG.error(msg)
raise exception.ShareBackendException(msg)
try:
with rados.WriteOpCtx() as wop:
wop.write_full(encoded_data)
ioctx.operate_write_op(wop, object_name)
except rados.OSError as e:
LOG.error(e)
raise e
finally:
ioctx.close() | def _put_rados_object(self, object_name, data):
'Synchronously write data as a byte string in a Ceph RADOS object.\n\n :param pool_name: name of the pool\n :type pool_name: str\n :param object_name: name of the object\n :type object_name: str\n :param data: data to write\n :type data: bytes\n '
pool_name = self.ganesha_rados_store_pool_name
encoded_data = data.encode('utf-8')
ioctx = self.rados_client.open_ioctx(pool_name)
max_size = ((int(self.rados_client.conf_get('osd_max_write_size')) * 1024) * 1024)
if (len(encoded_data) > max_size):
msg = "Data to be written to object '{0}' exceeds {1} bytes".format(object_name, max_size)
LOG.error(msg)
raise exception.ShareBackendException(msg)
try:
with rados.WriteOpCtx() as wop:
wop.write_full(encoded_data)
ioctx.operate_write_op(wop, object_name)
except rados.OSError as e:
LOG.error(e)
raise e
finally:
ioctx.close()<|docstring|>Synchronously write data as a byte string in a Ceph RADOS object.
:param pool_name: name of the pool
:type pool_name: str
:param object_name: name of the object
:type object_name: str
:param data: data to write
:type data: bytes<|endoftext|> |
c19c30a24fd379b0724d94e87dca94a6ef9d5ae873753856dbbe08c117a98139 | def get_export_id(self, bump=True):
'Get a new export id.'
if self.ganesha_rados_store_enable:
export_id = int(self._get_rados_object(self.ganesha_rados_export_counter))
if (not bump):
return export_id
export_id += 1
self._put_rados_object(self.ganesha_rados_export_counter, str(export_id))
return export_id
else:
if bump:
bumpcode = 'update ganesha set value = value + 1;'
else:
bumpcode = ''
out = self.execute('sqlite3', self.ganesha_db_path, (bumpcode + 'select * from ganesha where key = "exportid";'), run_as_root=False)[0]
match = re.search('\\Aexportid\\|(\\d+)$', out)
if (not match):
LOG.error('Invalid export database on Ganesha node %(tag)s: %(db)s.', {'tag': self.tag, 'db': self.ganesha_db_path})
raise exception.InvalidSqliteDB()
return int(match.groups()[0]) | Get a new export id. | manila/share/drivers/ganesha/manager.py | get_export_id | openstack/manila | 159 | python | def get_export_id(self, bump=True):
if self.ganesha_rados_store_enable:
export_id = int(self._get_rados_object(self.ganesha_rados_export_counter))
if (not bump):
return export_id
export_id += 1
self._put_rados_object(self.ganesha_rados_export_counter, str(export_id))
return export_id
else:
if bump:
bumpcode = 'update ganesha set value = value + 1;'
else:
bumpcode =
out = self.execute('sqlite3', self.ganesha_db_path, (bumpcode + 'select * from ganesha where key = "exportid";'), run_as_root=False)[0]
match = re.search('\\Aexportid\\|(\\d+)$', out)
if (not match):
LOG.error('Invalid export database on Ganesha node %(tag)s: %(db)s.', {'tag': self.tag, 'db': self.ganesha_db_path})
raise exception.InvalidSqliteDB()
return int(match.groups()[0]) | def get_export_id(self, bump=True):
if self.ganesha_rados_store_enable:
export_id = int(self._get_rados_object(self.ganesha_rados_export_counter))
if (not bump):
return export_id
export_id += 1
self._put_rados_object(self.ganesha_rados_export_counter, str(export_id))
return export_id
else:
if bump:
bumpcode = 'update ganesha set value = value + 1;'
else:
bumpcode =
out = self.execute('sqlite3', self.ganesha_db_path, (bumpcode + 'select * from ganesha where key = "exportid";'), run_as_root=False)[0]
match = re.search('\\Aexportid\\|(\\d+)$', out)
if (not match):
LOG.error('Invalid export database on Ganesha node %(tag)s: %(db)s.', {'tag': self.tag, 'db': self.ganesha_db_path})
raise exception.InvalidSqliteDB()
return int(match.groups()[0])<|docstring|>Get a new export id.<|endoftext|> |
088fe1179d6dd388a184787a2417465889afebbdf04d24dc6141e07b1422538d | def restart_service(self):
'Restart the Ganesha service.'
self.execute('service', self.ganesha_service, 'restart') | Restart the Ganesha service. | manila/share/drivers/ganesha/manager.py | restart_service | openstack/manila | 159 | python | def restart_service(self):
self.execute('service', self.ganesha_service, 'restart') | def restart_service(self):
self.execute('service', self.ganesha_service, 'restart')<|docstring|>Restart the Ganesha service.<|endoftext|> |
c78f20de43b90bdc0d8d809c2031ffb977c5bb92dd87e76cb96833d613ecd6ad | def reset_exports(self):
'Delete all export files.'
self.execute('sh', '-c', ('rm -f %s/*.conf' % pipes.quote(self.ganesha_export_dir)))
self._mkindex() | Delete all export files. | manila/share/drivers/ganesha/manager.py | reset_exports | openstack/manila | 159 | python | def reset_exports(self):
self.execute('sh', '-c', ('rm -f %s/*.conf' % pipes.quote(self.ganesha_export_dir)))
self._mkindex() | def reset_exports(self):
self.execute('sh', '-c', ('rm -f %s/*.conf' % pipes.quote(self.ganesha_export_dir)))
self._mkindex()<|docstring|>Delete all export files.<|endoftext|> |
8a5e93a596fbb4b771e2faacfd298462b114a3177a836a010347cb1cfb04b7ac | def create_estimator(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | create_estimator | mybirth0407/easyml | 37 | python | def create_estimator(self):
'\n \n '
raise NotImplementedError | def create_estimator(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
090960a20bc4ca8df0f9e40b071644858a480840cc5a7a35471b41c5296de65a | def extract_coefficients(self, estimator):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | extract_coefficients | mybirth0407/easyml | 37 | python | def extract_coefficients(self, estimator):
'\n \n '
raise NotImplementedError | def extract_coefficients(self, estimator):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
d96e124ba47b818e789310ca32fd7742d787487e1c633910924dd4436a98bc34 | def process_coefficients(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | process_coefficients | mybirth0407/easyml | 37 | python | def process_coefficients(self):
'\n \n '
raise NotImplementedError | def process_coefficients(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
9d708f2d429b9f250bd1319d92f830290bf483caa8b88f2217e6d8c9b11eb8d8 | def plot_coefficients_processed(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | plot_coefficients_processed | mybirth0407/easyml | 37 | python | def plot_coefficients_processed(self):
'\n \n '
raise NotImplementedError | def plot_coefficients_processed(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
3e37d8a0163ce30d0f27862721cae384c103b1cee9f6ba4f5fb928fe601f0bfa | def extract_variable_importances(self, estimator):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | extract_variable_importances | mybirth0407/easyml | 37 | python | def extract_variable_importances(self, estimator):
'\n \n '
raise NotImplementedError | def extract_variable_importances(self, estimator):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
a8fdf99b27f8c6097181bda04a1ea848edcaf7d21c3697022986a8b05599638d | def process_variable_importances(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | process_variable_importances | mybirth0407/easyml | 37 | python | def process_variable_importances(self):
'\n \n '
raise NotImplementedError | def process_variable_importances(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
ddca26bd0a970966947aa9ce9c9390a8479de48dde84139f354c26b80955b321 | def plot_variable_importances_processed(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | plot_variable_importances_processed | mybirth0407/easyml | 37 | python | def plot_variable_importances_processed(self):
'\n \n '
raise NotImplementedError | def plot_variable_importances_processed(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
b0250a33d701b70cd52735599f749e80176bffb03caa1213cec877cf841da8f8 | def predict_model(self):
'\n See the subclass documentation for more information on this method.\n '
raise NotImplementedError | See the subclass documentation for more information on this method. | Python/easymlpy/core.py | predict_model | mybirth0407/easyml | 37 | python | def predict_model(self):
'\n \n '
raise NotImplementedError | def predict_model(self):
'\n \n '
raise NotImplementedError<|docstring|>See the subclass documentation for more information on this method.<|endoftext|> |
977b183d163f5691a0bb07b23369ac877385566b2f479f9f74a4feb911140921 | def generate_coefficients_(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
coefficient = self.extract_coefficients(model)
return coefficient | Generate coefficients for a model (if applicable).
:return: An ndarray. | Python/easymlpy/core.py | generate_coefficients_ | mybirth0407/easyml | 37 | python | def generate_coefficients_(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
coefficient = self.extract_coefficients(model)
return coefficient | def generate_coefficients_(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
coefficient = self.extract_coefficients(model)
return coefficient<|docstring|>Generate coefficients for a model (if applicable).
:return: An ndarray.<|endoftext|> |
9c102f674f8eadfc74ecf59c51a1fc8ab6a072f0377bea9e086bed575e00b964 | def generate_coefficients(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
coefficients = []
print('Generating coefficients from multiple model builds:')
for _ in range(self.n_samples):
coefficient = self.generate_coefficients_()
coefficients.append(coefficient)
if self.progress_bar:
bar.update(i)
i += 1
coefficients = np.asarray(coefficients)
return coefficients | Generate coefficients for a model (if applicable).
:return: An ndarray. | Python/easymlpy/core.py | generate_coefficients | mybirth0407/easyml | 37 | python | def generate_coefficients(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
coefficients = []
print('Generating coefficients from multiple model builds:')
for _ in range(self.n_samples):
coefficient = self.generate_coefficients_()
coefficients.append(coefficient)
if self.progress_bar:
bar.update(i)
i += 1
coefficients = np.asarray(coefficients)
return coefficients | def generate_coefficients(self):
'\n Generate coefficients for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
coefficients = []
print('Generating coefficients from multiple model builds:')
for _ in range(self.n_samples):
coefficient = self.generate_coefficients_()
coefficients.append(coefficient)
if self.progress_bar:
bar.update(i)
i += 1
coefficients = np.asarray(coefficients)
return coefficients<|docstring|>Generate coefficients for a model (if applicable).
:return: An ndarray.<|endoftext|> |
071aedd3c4a89a6e288b0d1e93db4ff4fc2213811e99e8155b4bfbe627add817 | def generate_variable_importances_(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
variable_importance = self.extract_variable_importances(model)
return variable_importance | Generate variable importances for a model (if applicable).
:return: An ndarray. | Python/easymlpy/core.py | generate_variable_importances_ | mybirth0407/easyml | 37 | python | def generate_variable_importances_(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
variable_importance = self.extract_variable_importances(model)
return variable_importance | def generate_variable_importances_(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_preprocessed, self.y)
variable_importance = self.extract_variable_importances(model)
return variable_importance<|docstring|>Generate variable importances for a model (if applicable).
:return: An ndarray.<|endoftext|> |
1f04afe278d2d1d2784be2a2295446e88e9a4ce3cf9ee7845bda58e4fb4b98a3 | def generate_variable_importances(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
variable_importances = []
print('Generating variable importances from multiple model builds:')
for _ in range(self.n_samples):
variable_importance = self.generate_variable_importances_()
variable_importances.append(variable_importance)
if self.progress_bar:
bar.update(i)
i += 1
variable_importances = np.asarray(variable_importances)
return variable_importances | Generate variable importances for a model (if applicable).
:return: An ndarray. | Python/easymlpy/core.py | generate_variable_importances | mybirth0407/easyml | 37 | python | def generate_variable_importances(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
variable_importances = []
print('Generating variable importances from multiple model builds:')
for _ in range(self.n_samples):
variable_importance = self.generate_variable_importances_()
variable_importances.append(variable_importance)
if self.progress_bar:
bar.update(i)
i += 1
variable_importances = np.asarray(variable_importances)
return variable_importances | def generate_variable_importances(self):
'\n Generate variable importances for a model (if applicable).\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
variable_importances = []
print('Generating variable importances from multiple model builds:')
for _ in range(self.n_samples):
variable_importance = self.generate_variable_importances_()
variable_importances.append(variable_importance)
if self.progress_bar:
bar.update(i)
i += 1
variable_importances = np.asarray(variable_importances)
return variable_importances<|docstring|>Generate variable importances for a model (if applicable).
:return: An ndarray.<|endoftext|> |
fc47ceae7473d4d7f5cde3430d1ac897eb7aed4dcff0815c5b351e9930f3f891 | def generate_predictions_(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, self.X_train_preprocessed)
y_test_pred = self.predict_model(model, self.X_test_preprocessed)
return (y_train_pred, y_test_pred) | Generate predictions for a model.
:return: An ndarray. | Python/easymlpy/core.py | generate_predictions_ | mybirth0407/easyml | 37 | python | def generate_predictions_(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, self.X_train_preprocessed)
y_test_pred = self.predict_model(model, self.X_test_preprocessed)
return (y_train_pred, y_test_pred) | def generate_predictions_(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, self.X_train_preprocessed)
y_test_pred = self.predict_model(model, self.X_test_preprocessed)
return (y_train_pred, y_test_pred)<|docstring|>Generate predictions for a model.
:return: An ndarray.<|endoftext|> |
a662eea96e653a937432880ef4a0cce0ee61435349a8fa206251530e49c98131 | def generate_predictions(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
y_train_preds = []
y_test_preds = []
print('Generating predictions for a single train test split:')
for _ in range(self.n_samples):
(y_train_pred, y_test_pred) = self.generate_predictions_()
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
if self.progress_bar:
bar.update(i)
i += 1
y_train_preds = np.asarray(y_train_preds)
y_test_preds = np.asarray(y_test_preds)
return (y_train_preds, y_test_preds) | Generate predictions for a model.
:return: An ndarray. | Python/easymlpy/core.py | generate_predictions | mybirth0407/easyml | 37 | python | def generate_predictions(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
y_train_preds = []
y_test_preds = []
print('Generating predictions for a single train test split:')
for _ in range(self.n_samples):
(y_train_pred, y_test_pred) = self.generate_predictions_()
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
if self.progress_bar:
bar.update(i)
i += 1
y_train_preds = np.asarray(y_train_preds)
y_test_preds = np.asarray(y_test_preds)
return (y_train_preds, y_test_preds) | def generate_predictions(self):
'\n Generate predictions for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_samples)
i = 0
y_train_preds = []
y_test_preds = []
print('Generating predictions for a single train test split:')
for _ in range(self.n_samples):
(y_train_pred, y_test_pred) = self.generate_predictions_()
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
if self.progress_bar:
bar.update(i)
i += 1
y_train_preds = np.asarray(y_train_preds)
y_test_preds = np.asarray(y_test_preds)
return (y_train_preds, y_test_preds)<|docstring|>Generate predictions for a model.
:return: An ndarray.<|endoftext|> |
5764e78249e830d5b31faa2dba3c1a5f0c7779cd6ee2b22540c2b8fa4111888f | def generate_model_performance_(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
(X_train, X_test, y_train, y_test) = self.resample(self.X, self.y)
(X_train_preprocessed, X_test_preprocessed) = self.preprocess(X_train, X_test, categorical_variables=self.categorical_variables)
y_train_preds = []
y_test_preds = []
for _ in range(self.n_iterations):
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, X_train_preprocessed)
y_test_pred = self.predict_model(model, X_test_preprocessed)
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
predictions_train = np.mean(np.asarray(y_train_preds), axis=0)
predictions_test = np.mean(np.asarray(y_test_preds), axis=0)
model_performance_train = self.measure(y_train, predictions_train)
model_performance_test = self.measure(y_test, predictions_test)
return (model_performance_train, model_performance_test) | Generate measures of model performance for a model.
:return: An ndarray. | Python/easymlpy/core.py | generate_model_performance_ | mybirth0407/easyml | 37 | python | def generate_model_performance_(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
(X_train, X_test, y_train, y_test) = self.resample(self.X, self.y)
(X_train_preprocessed, X_test_preprocessed) = self.preprocess(X_train, X_test, categorical_variables=self.categorical_variables)
y_train_preds = []
y_test_preds = []
for _ in range(self.n_iterations):
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, X_train_preprocessed)
y_test_pred = self.predict_model(model, X_test_preprocessed)
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
predictions_train = np.mean(np.asarray(y_train_preds), axis=0)
predictions_test = np.mean(np.asarray(y_test_preds), axis=0)
model_performance_train = self.measure(y_train, predictions_train)
model_performance_test = self.measure(y_test, predictions_test)
return (model_performance_train, model_performance_test) | def generate_model_performance_(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
(X_train, X_test, y_train, y_test) = self.resample(self.X, self.y)
(X_train_preprocessed, X_test_preprocessed) = self.preprocess(X_train, X_test, categorical_variables=self.categorical_variables)
y_train_preds = []
y_test_preds = []
for _ in range(self.n_iterations):
estimator = self.create_estimator()
if self.model_args:
estimator = estimator.set_params(**self.model_args)
model = estimator.fit(self.X_train_preprocessed, self.y_train)
y_train_pred = self.predict_model(model, X_train_preprocessed)
y_test_pred = self.predict_model(model, X_test_preprocessed)
y_train_preds.append(y_train_pred)
y_test_preds.append(y_test_pred)
predictions_train = np.mean(np.asarray(y_train_preds), axis=0)
predictions_test = np.mean(np.asarray(y_test_preds), axis=0)
model_performance_train = self.measure(y_train, predictions_train)
model_performance_test = self.measure(y_test, predictions_test)
return (model_performance_train, model_performance_test)<|docstring|>Generate measures of model performance for a model.
:return: An ndarray.<|endoftext|> |
c53b16ac67fc17a8ae77966b13e23a63951cd1f620fa1195c680c88f927a3f03 | def generate_model_performance(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_divisions)
i = 0
model_performance_train_all = []
model_performance_test_all = []
print('Generating measures of model performance over multiple train test splits:')
for _ in range(self.n_divisions):
(model_performance_train, model_performance_test) = self.generate_model_performance_()
model_performance_train_all.append(model_performance_train)
model_performance_test_all.append(model_performance_test)
if self.progress_bar:
bar.update(i)
i += 1
model_performance_train = np.asarray(model_performance_train_all)
model_performance_test = np.asarray(model_performance_test_all)
return (model_performance_train, model_performance_test) | Generate measures of model performance for a model.
:return: An ndarray. | Python/easymlpy/core.py | generate_model_performance | mybirth0407/easyml | 37 | python | def generate_model_performance(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_divisions)
i = 0
model_performance_train_all = []
model_performance_test_all = []
print('Generating measures of model performance over multiple train test splits:')
for _ in range(self.n_divisions):
(model_performance_train, model_performance_test) = self.generate_model_performance_()
model_performance_train_all.append(model_performance_train)
model_performance_test_all.append(model_performance_test)
if self.progress_bar:
bar.update(i)
i += 1
model_performance_train = np.asarray(model_performance_train_all)
model_performance_test = np.asarray(model_performance_test_all)
return (model_performance_train, model_performance_test) | def generate_model_performance(self):
'\n Generate measures of model performance for a model.\n\n :return: An ndarray.\n '
if self.progress_bar:
bar = progressbar.ProgressBar(max_value=self.n_divisions)
i = 0
model_performance_train_all = []
model_performance_test_all = []
print('Generating measures of model performance over multiple train test splits:')
for _ in range(self.n_divisions):
(model_performance_train, model_performance_test) = self.generate_model_performance_()
model_performance_train_all.append(model_performance_train)
model_performance_test_all.append(model_performance_test)
if self.progress_bar:
bar.update(i)
i += 1
model_performance_train = np.asarray(model_performance_train_all)
model_performance_test = np.asarray(model_performance_test_all)
return (model_performance_train, model_performance_test)<|docstring|>Generate measures of model performance for a model.
:return: An ndarray.<|endoftext|> |
ede75f5ec2eb7c4caf3842c41dbb612bec782e6c90dc0026ed35a6d0c0929e7e | def plot_predictions_single_train_test_split_train(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_train, y_train_pred)
else:
(fig, ax) = plot.plot_predictions_binomial(y_train, y_train_pred)
return (fig, ax) | Plot predictions.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_predictions_single_train_test_split_train | mybirth0407/easyml | 37 | python | def plot_predictions_single_train_test_split_train(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_train, y_train_pred)
else:
(fig, ax) = plot.plot_predictions_binomial(y_train, y_train_pred)
return (fig, ax) | def plot_predictions_single_train_test_split_train(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_train, y_train_pred)
else:
(fig, ax) = plot.plot_predictions_binomial(y_train, y_train_pred)
return (fig, ax)<|docstring|>Plot predictions.
:return: Figure and axe objects.<|endoftext|> |
50288c73132fff6e7d7c94d90eec36f9e085d92d4424d3ddcbcd634bf43877a4 | def plot_predictions_single_train_test_split_test(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_test, y_test_pred, subtitle='Test')
else:
(fig, ax) = plot.plot_predictions_binomial(y_test, y_test_pred, subtitle='Test')
return (fig, ax) | Plot predictions.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_predictions_single_train_test_split_test | mybirth0407/easyml | 37 | python | def plot_predictions_single_train_test_split_test(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_test, y_test_pred, subtitle='Test')
else:
(fig, ax) = plot.plot_predictions_binomial(y_test, y_test_pred, subtitle='Test')
return (fig, ax) | def plot_predictions_single_train_test_split_test(self):
'\n Plot predictions.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
(fig, ax) = plot.plot_predictions_gaussian(y_test, y_test_pred, subtitle='Test')
else:
(fig, ax) = plot.plot_predictions_binomial(y_test, y_test_pred, subtitle='Test')
return (fig, ax)<|docstring|>Plot predictions.
:return: Figure and axe objects.<|endoftext|> |
39fb637b551a4e3b877f02bf56935cac219325218fb2c2d66821c5f53948ecc5 | def plot_roc_single_train_test_split_train(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_train, y_train_pred)
return (fig, ax) | Plot ROC Curve.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_roc_single_train_test_split_train | mybirth0407/easyml | 37 | python | def plot_roc_single_train_test_split_train(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_train, y_train_pred)
return (fig, ax) | def plot_roc_single_train_test_split_train(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_train = self.y_train
y_train_pred = np.mean(self.predictions_train, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_train, y_train_pred)
return (fig, ax)<|docstring|>Plot ROC Curve.
:return: Figure and axe objects.<|endoftext|> |
065dc4651e4d37679548974a90211cbff63c8ae02c414e89def55606b2e43a24 | def plot_roc_single_train_test_split_test(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_test, y_test_pred, subtitle='Test')
return (fig, ax) | Plot ROC Curve.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_roc_single_train_test_split_test | mybirth0407/easyml | 37 | python | def plot_roc_single_train_test_split_test(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_test, y_test_pred, subtitle='Test')
return (fig, ax) | def plot_roc_single_train_test_split_test(self):
'\n Plot ROC Curve.\n\n :return: Figure and axe objects.\n '
y_test = self.y_test
y_test_pred = np.mean(self.predictions_test, axis=0)
if (self.family == 'gaussian'):
raise NotImplementedError
else:
(fig, ax) = plot.plot_roc_single_train_test_split(y_test, y_test_pred, subtitle='Test')
return (fig, ax)<|docstring|>Plot ROC Curve.
:return: Figure and axe objects.<|endoftext|> |
2ccbd35f384b51587faac21e3712c74fba15a84ac4e699d18af722650bc7fdc9 | def plot_model_performance_train(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_train)
return (fig, ax) | Plot model performance.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_model_performance_train | mybirth0407/easyml | 37 | python | def plot_model_performance_train(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_train)
return (fig, ax) | def plot_model_performance_train(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_train)
return (fig, ax)<|docstring|>Plot model performance.
:return: Figure and axe objects.<|endoftext|> |
217b0fae8b7f25fd0efd3af053f4f2b1b86a353c404370be2b31e67b65c6fbfe | def plot_model_performance_test(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_test, subtitle='Test')
return (fig, ax) | Plot model performance.
:return: Figure and axe objects. | Python/easymlpy/core.py | plot_model_performance_test | mybirth0407/easyml | 37 | python | def plot_model_performance_test(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_test, subtitle='Test')
return (fig, ax) | def plot_model_performance_test(self):
'\n Plot model performance.\n\n :return: Figure and axe objects.\n '
(fig, ax) = self.plot_model_performance(self.model_performance_test, subtitle='Test')
return (fig, ax)<|docstring|>Plot model performance.
:return: Figure and axe objects.<|endoftext|> |
7b6e074c28f870d46ac9a45770e11fedb8309bfb9c258920314c260fd156b44a | def gather_mm(a, b, *, idx_b):
'Gather data according to the given indices and perform matrix multiplication.\n\n Let the result tensor be ``c``, the operator conducts the following computation:\n\n c[i] = a[i] @ b[idx_b[i]]\n , where len(c) == len(idx_b)\n\n\n Parameters\n ----------\n a : Tensor\n A 2-D tensor of shape ``(N, D1)``\n b : Tensor\n A 3-D tensor of shape ``(R, D1, D2)``\n idx_b : Tensor, optional\n An 1-D integer tensor of shape ``(N,)``.\n\n Returns\n -------\n Tensor\n The output dense matrix of shape ``(N, D2)``\n '
(N, D1) = F.shape(a)
(R, _, D2) = F.shape(b)
if ((N > 1000000) or (D1 > 8) or (D2 > 8)):
import torch
(sorted_idx_b, perm) = torch.sort(idx_b)
(_, rev_perm) = torch.sort(perm)
sorted_a = torch.index_select(a, 0, perm)
pos_l = torch.searchsorted(sorted_idx_b, torch.arange(R, device=a.device))
pos_r = torch.cat([pos_l[1:], torch.tensor([len(idx_b)], device=a.device)])
seglen = (pos_r - pos_l).cpu()
return torch.index_select(F.segment_mm(sorted_a, b, seglen), 0, rev_perm)
else:
return F.gather_mm(a, b, None, idx_b) | Gather data according to the given indices and perform matrix multiplication.
Let the result tensor be ``c``, the operator conducts the following computation:
c[i] = a[i] @ b[idx_b[i]]
, where len(c) == len(idx_b)
Parameters
----------
a : Tensor
A 2-D tensor of shape ``(N, D1)``
b : Tensor
A 3-D tensor of shape ``(R, D1, D2)``
idx_b : Tensor, optional
An 1-D integer tensor of shape ``(N,)``.
Returns
-------
Tensor
The output dense matrix of shape ``(N, D2)`` | python/dgl/ops/gather_mm.py | gather_mm | binfoo1993/dgl | 1 | python | def gather_mm(a, b, *, idx_b):
'Gather data according to the given indices and perform matrix multiplication.\n\n Let the result tensor be ``c``, the operator conducts the following computation:\n\n c[i] = a[i] @ b[idx_b[i]]\n , where len(c) == len(idx_b)\n\n\n Parameters\n ----------\n a : Tensor\n A 2-D tensor of shape ``(N, D1)``\n b : Tensor\n A 3-D tensor of shape ``(R, D1, D2)``\n idx_b : Tensor, optional\n An 1-D integer tensor of shape ``(N,)``.\n\n Returns\n -------\n Tensor\n The output dense matrix of shape ``(N, D2)``\n '
(N, D1) = F.shape(a)
(R, _, D2) = F.shape(b)
if ((N > 1000000) or (D1 > 8) or (D2 > 8)):
import torch
(sorted_idx_b, perm) = torch.sort(idx_b)
(_, rev_perm) = torch.sort(perm)
sorted_a = torch.index_select(a, 0, perm)
pos_l = torch.searchsorted(sorted_idx_b, torch.arange(R, device=a.device))
pos_r = torch.cat([pos_l[1:], torch.tensor([len(idx_b)], device=a.device)])
seglen = (pos_r - pos_l).cpu()
return torch.index_select(F.segment_mm(sorted_a, b, seglen), 0, rev_perm)
else:
return F.gather_mm(a, b, None, idx_b) | def gather_mm(a, b, *, idx_b):
'Gather data according to the given indices and perform matrix multiplication.\n\n Let the result tensor be ``c``, the operator conducts the following computation:\n\n c[i] = a[i] @ b[idx_b[i]]\n , where len(c) == len(idx_b)\n\n\n Parameters\n ----------\n a : Tensor\n A 2-D tensor of shape ``(N, D1)``\n b : Tensor\n A 3-D tensor of shape ``(R, D1, D2)``\n idx_b : Tensor, optional\n An 1-D integer tensor of shape ``(N,)``.\n\n Returns\n -------\n Tensor\n The output dense matrix of shape ``(N, D2)``\n '
(N, D1) = F.shape(a)
(R, _, D2) = F.shape(b)
if ((N > 1000000) or (D1 > 8) or (D2 > 8)):
import torch
(sorted_idx_b, perm) = torch.sort(idx_b)
(_, rev_perm) = torch.sort(perm)
sorted_a = torch.index_select(a, 0, perm)
pos_l = torch.searchsorted(sorted_idx_b, torch.arange(R, device=a.device))
pos_r = torch.cat([pos_l[1:], torch.tensor([len(idx_b)], device=a.device)])
seglen = (pos_r - pos_l).cpu()
return torch.index_select(F.segment_mm(sorted_a, b, seglen), 0, rev_perm)
else:
return F.gather_mm(a, b, None, idx_b)<|docstring|>Gather data according to the given indices and perform matrix multiplication.
Let the result tensor be ``c``, the operator conducts the following computation:
c[i] = a[i] @ b[idx_b[i]]
, where len(c) == len(idx_b)
Parameters
----------
a : Tensor
A 2-D tensor of shape ``(N, D1)``
b : Tensor
A 3-D tensor of shape ``(R, D1, D2)``
idx_b : Tensor, optional
An 1-D integer tensor of shape ``(N,)``.
Returns
-------
Tensor
The output dense matrix of shape ``(N, D2)``<|endoftext|> |
b0a2d85302c95bb214ec341f9b04225304384990ee74ff442b16e569d738aded | def __init__(self, my_uuid, ws_discovery, model, device, deviceMdibContainer, validate=True, roleProvider=None, sslContext=None, logLevel=None, max_subscription_duration=7200, log_prefix='', chunked_messages=False):
'\n @param uuid: a string that becomes part of the devices url (no spaces, no special characters please. This could cause an invalid url!).\n Parameter can be None, in this case a random uuid string is generated.\n @param ws_discovery: reference to the wsDiscovery instance\n @param model: a pysoap.soapenvelope.DPWSThisModel instance\n @param device: a pysoap.soapenvelope.DPWSThisDevice instance\n @param deviceMdibContainer: a DeviceMdibContainer instance\n @param roleProvider: handles the operation calls\n @param sslContext: if not None, this context is used and https url is used. Otherwise http\n @param logLevel: if not None, the "sdc.device" logger will use this level\n @param max_subscription_duration: max. possible duration of a subscription, default is 7200 seconds\n @param ident: names a device, used for logging\n '
self._my_uuid = (my_uuid or uuid.uuid4())
self._wsdiscovery = ws_discovery
self.model = model
self.device = device
self._mdib = deviceMdibContainer
self._log_prefix = log_prefix
self._mdib.log_prefix = log_prefix
self._validate = validate
self._sslContext = sslContext
self._compression_methods = compression.encodings[:]
self._httpServerThread = None
self._setupLogging(logLevel)
self._logger = loghelper.getLoggerAdapter('sdc.device', log_prefix)
self.chunked_messages = chunked_messages
self.contextstates_in_getmdib = self.DEFAULT_CONTEXTSTATES_IN_GETMDIB
self._hostDispatcher = self._mkHostDispatcher()
self._GetDispatcher = None
self._LocalizationDispatcher = None
self._GetServiceHosted = None
self._ContextDispatcher = None
self._DescriptionEventDispatcher = None
self._StateEventDispatcher = None
self._WaveformDispatcher = None
self._SdcServiceHosted = None
self.__SetDispatcher = None
self._SetServiceHosted = None
self._hostedServices = []
self._url_dispatcher = None
self._rtSampleSendThread = None
self._runRtSampleThread = False
self.collectRtSamplesPeriod = 0.1
if (self._sslContext is not None):
self._urlschema = 'https'
else:
self._urlschema = 'http'
self.dpwsHost = None
self._subscriptionsManager = self._mkSubscriptionManager(max_subscription_duration)
self._scoOperationsRegistry = self._mkScoOperationsRegistry(handle='_sco')
deviceMdibContainer.setSdcDevice(self)
self.product_roles = roleProvider
if (self.product_roles is None):
self.mkDefaultRoleHandlers()
self._location = None | @param uuid: a string that becomes part of the devices url (no spaces, no special characters please. This could cause an invalid url!).
Parameter can be None, in this case a random uuid string is generated.
@param ws_discovery: reference to the wsDiscovery instance
@param model: a pysoap.soapenvelope.DPWSThisModel instance
@param device: a pysoap.soapenvelope.DPWSThisDevice instance
@param deviceMdibContainer: a DeviceMdibContainer instance
@param roleProvider: handles the operation calls
@param sslContext: if not None, this context is used and https url is used. Otherwise http
@param logLevel: if not None, the "sdc.device" logger will use this level
@param max_subscription_duration: max. possible duration of a subscription, default is 7200 seconds
@param ident: names a device, used for logging | sdc11073/sdcdevice/sdc_handlers.py | __init__ | deichmab-draeger/sdc11073-1 | 0 | python | def __init__(self, my_uuid, ws_discovery, model, device, deviceMdibContainer, validate=True, roleProvider=None, sslContext=None, logLevel=None, max_subscription_duration=7200, log_prefix=, chunked_messages=False):
'\n @param uuid: a string that becomes part of the devices url (no spaces, no special characters please. This could cause an invalid url!).\n Parameter can be None, in this case a random uuid string is generated.\n @param ws_discovery: reference to the wsDiscovery instance\n @param model: a pysoap.soapenvelope.DPWSThisModel instance\n @param device: a pysoap.soapenvelope.DPWSThisDevice instance\n @param deviceMdibContainer: a DeviceMdibContainer instance\n @param roleProvider: handles the operation calls\n @param sslContext: if not None, this context is used and https url is used. Otherwise http\n @param logLevel: if not None, the "sdc.device" logger will use this level\n @param max_subscription_duration: max. possible duration of a subscription, default is 7200 seconds\n @param ident: names a device, used for logging\n '
self._my_uuid = (my_uuid or uuid.uuid4())
self._wsdiscovery = ws_discovery
self.model = model
self.device = device
self._mdib = deviceMdibContainer
self._log_prefix = log_prefix
self._mdib.log_prefix = log_prefix
self._validate = validate
self._sslContext = sslContext
self._compression_methods = compression.encodings[:]
self._httpServerThread = None
self._setupLogging(logLevel)
self._logger = loghelper.getLoggerAdapter('sdc.device', log_prefix)
self.chunked_messages = chunked_messages
self.contextstates_in_getmdib = self.DEFAULT_CONTEXTSTATES_IN_GETMDIB
self._hostDispatcher = self._mkHostDispatcher()
self._GetDispatcher = None
self._LocalizationDispatcher = None
self._GetServiceHosted = None
self._ContextDispatcher = None
self._DescriptionEventDispatcher = None
self._StateEventDispatcher = None
self._WaveformDispatcher = None
self._SdcServiceHosted = None
self.__SetDispatcher = None
self._SetServiceHosted = None
self._hostedServices = []
self._url_dispatcher = None
self._rtSampleSendThread = None
self._runRtSampleThread = False
self.collectRtSamplesPeriod = 0.1
if (self._sslContext is not None):
self._urlschema = 'https'
else:
self._urlschema = 'http'
self.dpwsHost = None
self._subscriptionsManager = self._mkSubscriptionManager(max_subscription_duration)
self._scoOperationsRegistry = self._mkScoOperationsRegistry(handle='_sco')
deviceMdibContainer.setSdcDevice(self)
self.product_roles = roleProvider
if (self.product_roles is None):
self.mkDefaultRoleHandlers()
self._location = None | def __init__(self, my_uuid, ws_discovery, model, device, deviceMdibContainer, validate=True, roleProvider=None, sslContext=None, logLevel=None, max_subscription_duration=7200, log_prefix=, chunked_messages=False):
'\n @param uuid: a string that becomes part of the devices url (no spaces, no special characters please. This could cause an invalid url!).\n Parameter can be None, in this case a random uuid string is generated.\n @param ws_discovery: reference to the wsDiscovery instance\n @param model: a pysoap.soapenvelope.DPWSThisModel instance\n @param device: a pysoap.soapenvelope.DPWSThisDevice instance\n @param deviceMdibContainer: a DeviceMdibContainer instance\n @param roleProvider: handles the operation calls\n @param sslContext: if not None, this context is used and https url is used. Otherwise http\n @param logLevel: if not None, the "sdc.device" logger will use this level\n @param max_subscription_duration: max. possible duration of a subscription, default is 7200 seconds\n @param ident: names a device, used for logging\n '
self._my_uuid = (my_uuid or uuid.uuid4())
self._wsdiscovery = ws_discovery
self.model = model
self.device = device
self._mdib = deviceMdibContainer
self._log_prefix = log_prefix
self._mdib.log_prefix = log_prefix
self._validate = validate
self._sslContext = sslContext
self._compression_methods = compression.encodings[:]
self._httpServerThread = None
self._setupLogging(logLevel)
self._logger = loghelper.getLoggerAdapter('sdc.device', log_prefix)
self.chunked_messages = chunked_messages
self.contextstates_in_getmdib = self.DEFAULT_CONTEXTSTATES_IN_GETMDIB
self._hostDispatcher = self._mkHostDispatcher()
self._GetDispatcher = None
self._LocalizationDispatcher = None
self._GetServiceHosted = None
self._ContextDispatcher = None
self._DescriptionEventDispatcher = None
self._StateEventDispatcher = None
self._WaveformDispatcher = None
self._SdcServiceHosted = None
self.__SetDispatcher = None
self._SetServiceHosted = None
self._hostedServices = []
self._url_dispatcher = None
self._rtSampleSendThread = None
self._runRtSampleThread = False
self.collectRtSamplesPeriod = 0.1
if (self._sslContext is not None):
self._urlschema = 'https'
else:
self._urlschema = 'http'
self.dpwsHost = None
self._subscriptionsManager = self._mkSubscriptionManager(max_subscription_duration)
self._scoOperationsRegistry = self._mkScoOperationsRegistry(handle='_sco')
deviceMdibContainer.setSdcDevice(self)
self.product_roles = roleProvider
if (self.product_roles is None):
self.mkDefaultRoleHandlers()
self._location = None<|docstring|>@param uuid: a string that becomes part of the devices url (no spaces, no special characters please. This could cause an invalid url!).
Parameter can be None, in this case a random uuid string is generated.
@param ws_discovery: reference to the wsDiscovery instance
@param model: a pysoap.soapenvelope.DPWSThisModel instance
@param device: a pysoap.soapenvelope.DPWSThisDevice instance
@param deviceMdibContainer: a DeviceMdibContainer instance
@param roleProvider: handles the operation calls
@param sslContext: if not None, this context is used and https url is used. Otherwise http
@param logLevel: if not None, the "sdc.device" logger will use this level
@param max_subscription_duration: max. possible duration of a subscription, default is 7200 seconds
@param ident: names a device, used for logging<|endoftext|> |
a8ebbc039aff301e3f708ccd3310941a5759afc4daafbe726cefc85b473e671a | def _getDeviceComponentBasedScopes(self):
'\n SDC: For every instance derived from pm:AbstractComplexDeviceComponentDescriptor in the MDIB an\n SDC SERVICE PROVIDER SHOULD include a URIencoded pm:AbstractComplexDeviceComponentDescriptor/pm:Type\n as dpws:Scope of the MDPWS discovery messages. The URI encoding conforms to the given Extended Backus-Naur Form.\n E.G. sdc.cdc.type:///69650, sdc.cdc.type:/urn:oid:1.3.6.1.4.1.3592.2.1.1.0//DN_VMD\n After discussion with David: use only MDSDescriptor, VmdDescriptor makes no sense.\n :return: a set of scopes\n '
scopes = set()
for t in (namespaces.domTag('MdsDescriptor'),):
descriptors = self._mdib.descriptions.NODETYPE.get(t)
for d in descriptors:
if (d.Type is not None):
cs = ('' if (d.Type.CodingSystem == pmtypes.DefaultCodingSystem) else d.Type.CodingSystem)
csv = (d.Type.CodingSystemVersion or '')
sc = wsdiscovery.Scope('sdc.cdc.type:/{}/{}/{}'.format(cs, csv, d.Type.Code))
scopes.add(sc)
return scopes | SDC: For every instance derived from pm:AbstractComplexDeviceComponentDescriptor in the MDIB an
SDC SERVICE PROVIDER SHOULD include a URIencoded pm:AbstractComplexDeviceComponentDescriptor/pm:Type
as dpws:Scope of the MDPWS discovery messages. The URI encoding conforms to the given Extended Backus-Naur Form.
E.G. sdc.cdc.type:///69650, sdc.cdc.type:/urn:oid:1.3.6.1.4.1.3592.2.1.1.0//DN_VMD
After discussion with David: use only MDSDescriptor, VmdDescriptor makes no sense.
:return: a set of scopes | sdc11073/sdcdevice/sdc_handlers.py | _getDeviceComponentBasedScopes | deichmab-draeger/sdc11073-1 | 0 | python | def _getDeviceComponentBasedScopes(self):
'\n SDC: For every instance derived from pm:AbstractComplexDeviceComponentDescriptor in the MDIB an\n SDC SERVICE PROVIDER SHOULD include a URIencoded pm:AbstractComplexDeviceComponentDescriptor/pm:Type\n as dpws:Scope of the MDPWS discovery messages. The URI encoding conforms to the given Extended Backus-Naur Form.\n E.G. sdc.cdc.type:///69650, sdc.cdc.type:/urn:oid:1.3.6.1.4.1.3592.2.1.1.0//DN_VMD\n After discussion with David: use only MDSDescriptor, VmdDescriptor makes no sense.\n :return: a set of scopes\n '
scopes = set()
for t in (namespaces.domTag('MdsDescriptor'),):
descriptors = self._mdib.descriptions.NODETYPE.get(t)
for d in descriptors:
if (d.Type is not None):
cs = ( if (d.Type.CodingSystem == pmtypes.DefaultCodingSystem) else d.Type.CodingSystem)
csv = (d.Type.CodingSystemVersion or )
sc = wsdiscovery.Scope('sdc.cdc.type:/{}/{}/{}'.format(cs, csv, d.Type.Code))
scopes.add(sc)
return scopes | def _getDeviceComponentBasedScopes(self):
'\n SDC: For every instance derived from pm:AbstractComplexDeviceComponentDescriptor in the MDIB an\n SDC SERVICE PROVIDER SHOULD include a URIencoded pm:AbstractComplexDeviceComponentDescriptor/pm:Type\n as dpws:Scope of the MDPWS discovery messages. The URI encoding conforms to the given Extended Backus-Naur Form.\n E.G. sdc.cdc.type:///69650, sdc.cdc.type:/urn:oid:1.3.6.1.4.1.3592.2.1.1.0//DN_VMD\n After discussion with David: use only MDSDescriptor, VmdDescriptor makes no sense.\n :return: a set of scopes\n '
scopes = set()
for t in (namespaces.domTag('MdsDescriptor'),):
descriptors = self._mdib.descriptions.NODETYPE.get(t)
for d in descriptors:
if (d.Type is not None):
cs = ( if (d.Type.CodingSystem == pmtypes.DefaultCodingSystem) else d.Type.CodingSystem)
csv = (d.Type.CodingSystemVersion or )
sc = wsdiscovery.Scope('sdc.cdc.type:/{}/{}/{}'.format(cs, csv, d.Type.Code))
scopes.add(sc)
return scopes<|docstring|>SDC: For every instance derived from pm:AbstractComplexDeviceComponentDescriptor in the MDIB an
SDC SERVICE PROVIDER SHOULD include a URIencoded pm:AbstractComplexDeviceComponentDescriptor/pm:Type
as dpws:Scope of the MDPWS discovery messages. The URI encoding conforms to the given Extended Backus-Naur Form.
E.G. sdc.cdc.type:///69650, sdc.cdc.type:/urn:oid:1.3.6.1.4.1.3592.2.1.1.0//DN_VMD
After discussion with David: use only MDSDescriptor, VmdDescriptor makes no sense.
:return: a set of scopes<|endoftext|> |
59d5e649eba40fd1930dc5015c81ebc1613b1c861de527a16e4e9e35dbb3e271 | def dispatchGetRequest(self, parseResult, headers):
' device itself can also handle GET requests. This is the handler'
return self._hostDispatcher.dispatchGetRequest(parseResult, headers) | device itself can also handle GET requests. This is the handler | sdc11073/sdcdevice/sdc_handlers.py | dispatchGetRequest | deichmab-draeger/sdc11073-1 | 0 | python | def dispatchGetRequest(self, parseResult, headers):
' '
return self._hostDispatcher.dispatchGetRequest(parseResult, headers) | def dispatchGetRequest(self, parseResult, headers):
' '
return self._hostDispatcher.dispatchGetRequest(parseResult, headers)<|docstring|>device itself can also handle GET requests. This is the handler<|endoftext|> |
99405eaa3b980f7d04cda353e7bb918a46791e2e4afd6e4a27cbbf90812d134a | def _startServices(self, shared_http_server=None):
' start the services'
self._logger.info('starting services, addr = {}', self._wsdiscovery.getActiveAddresses())
self._scoOperationsRegistry.startWorker()
if shared_http_server:
self._httpServerThread = shared_http_server
else:
self._httpServerThread = httpserver.HttpServerThread(my_ipaddress='0.0.0.0', sslContext=self._sslContext, supportedEncodings=self._compression_methods, log_prefix=self._log_prefix, chunked_responses=self.chunked_messages)
self._httpServerThread.start()
event_is_set = self._httpServerThread.started_evt.wait(timeout=15.0)
if (not event_is_set):
self._logger.error('Cannot start device, start event of http server not set.')
raise RuntimeError('Cannot start device, start event of http server not set.')
host_ips = self._wsdiscovery.getActiveAddresses()
self._url_dispatcher = httpserver.HostedServiceDispatcher(self._mdib.sdc_definitions, self._logger)
self._httpServerThread.devices_dispatcher.register_device_dispatcher(self.path_prefix, self._url_dispatcher)
if (len(host_ips) == 0):
self._logger.error('Cannot start device, there is no IP address to bind it to.')
raise RuntimeError('Cannot start device, there is no IP address to bind it to.')
port = self._httpServerThread.my_port
if (port is None):
self._logger.error('Cannot start device, could not bind HTTP server to a port.')
raise RuntimeError('Cannot start device, could not bind HTTP server to a port.')
base_urls = []
for addr in host_ips:
base_urls.append(urllib.parse.SplitResult(self._urlschema, '{}:{}'.format(addr, port), self.path_prefix, query=None, fragment=None))
self.dpwsHost = pysoap.soapenvelope.DPWSHost(endpointReferencesList=[pysoap.soapenvelope.WsaEndpointReferenceType(self.epr)], typesList=self._mdib.sdc_definitions.MedicalDeviceTypesFilter)
self._url_dispatcher.register_hosted_service(self._hostDispatcher)
self._register_hosted_services(base_urls)
for host_ip in host_ips:
self._logger.info('serving Services on {}:{}', host_ip, port)
self._subscriptionsManager.setBaseUrls(base_urls) | start the services | sdc11073/sdcdevice/sdc_handlers.py | _startServices | deichmab-draeger/sdc11073-1 | 0 | python | def _startServices(self, shared_http_server=None):
' '
self._logger.info('starting services, addr = {}', self._wsdiscovery.getActiveAddresses())
self._scoOperationsRegistry.startWorker()
if shared_http_server:
self._httpServerThread = shared_http_server
else:
self._httpServerThread = httpserver.HttpServerThread(my_ipaddress='0.0.0.0', sslContext=self._sslContext, supportedEncodings=self._compression_methods, log_prefix=self._log_prefix, chunked_responses=self.chunked_messages)
self._httpServerThread.start()
event_is_set = self._httpServerThread.started_evt.wait(timeout=15.0)
if (not event_is_set):
self._logger.error('Cannot start device, start event of http server not set.')
raise RuntimeError('Cannot start device, start event of http server not set.')
host_ips = self._wsdiscovery.getActiveAddresses()
self._url_dispatcher = httpserver.HostedServiceDispatcher(self._mdib.sdc_definitions, self._logger)
self._httpServerThread.devices_dispatcher.register_device_dispatcher(self.path_prefix, self._url_dispatcher)
if (len(host_ips) == 0):
self._logger.error('Cannot start device, there is no IP address to bind it to.')
raise RuntimeError('Cannot start device, there is no IP address to bind it to.')
port = self._httpServerThread.my_port
if (port is None):
self._logger.error('Cannot start device, could not bind HTTP server to a port.')
raise RuntimeError('Cannot start device, could not bind HTTP server to a port.')
base_urls = []
for addr in host_ips:
base_urls.append(urllib.parse.SplitResult(self._urlschema, '{}:{}'.format(addr, port), self.path_prefix, query=None, fragment=None))
self.dpwsHost = pysoap.soapenvelope.DPWSHost(endpointReferencesList=[pysoap.soapenvelope.WsaEndpointReferenceType(self.epr)], typesList=self._mdib.sdc_definitions.MedicalDeviceTypesFilter)
self._url_dispatcher.register_hosted_service(self._hostDispatcher)
self._register_hosted_services(base_urls)
for host_ip in host_ips:
self._logger.info('serving Services on {}:{}', host_ip, port)
self._subscriptionsManager.setBaseUrls(base_urls) | def _startServices(self, shared_http_server=None):
' '
self._logger.info('starting services, addr = {}', self._wsdiscovery.getActiveAddresses())
self._scoOperationsRegistry.startWorker()
if shared_http_server:
self._httpServerThread = shared_http_server
else:
self._httpServerThread = httpserver.HttpServerThread(my_ipaddress='0.0.0.0', sslContext=self._sslContext, supportedEncodings=self._compression_methods, log_prefix=self._log_prefix, chunked_responses=self.chunked_messages)
self._httpServerThread.start()
event_is_set = self._httpServerThread.started_evt.wait(timeout=15.0)
if (not event_is_set):
self._logger.error('Cannot start device, start event of http server not set.')
raise RuntimeError('Cannot start device, start event of http server not set.')
host_ips = self._wsdiscovery.getActiveAddresses()
self._url_dispatcher = httpserver.HostedServiceDispatcher(self._mdib.sdc_definitions, self._logger)
self._httpServerThread.devices_dispatcher.register_device_dispatcher(self.path_prefix, self._url_dispatcher)
if (len(host_ips) == 0):
self._logger.error('Cannot start device, there is no IP address to bind it to.')
raise RuntimeError('Cannot start device, there is no IP address to bind it to.')
port = self._httpServerThread.my_port
if (port is None):
self._logger.error('Cannot start device, could not bind HTTP server to a port.')
raise RuntimeError('Cannot start device, could not bind HTTP server to a port.')
base_urls = []
for addr in host_ips:
base_urls.append(urllib.parse.SplitResult(self._urlschema, '{}:{}'.format(addr, port), self.path_prefix, query=None, fragment=None))
self.dpwsHost = pysoap.soapenvelope.DPWSHost(endpointReferencesList=[pysoap.soapenvelope.WsaEndpointReferenceType(self.epr)], typesList=self._mdib.sdc_definitions.MedicalDeviceTypesFilter)
self._url_dispatcher.register_hosted_service(self._hostDispatcher)
self._register_hosted_services(base_urls)
for host_ip in host_ips:
self._logger.info('serving Services on {}:{}', host_ip, port)
self._subscriptionsManager.setBaseUrls(base_urls)<|docstring|>start the services<|endoftext|> |
31b5ba6840a870fb01de2ead63278aab2bf23ac2a40e8e6647d4927b9e34b7ae | def sendWaveformUpdates(self, changedSamples):
'\n @param changedSamples: a dictionary with key = handle, value= devicemdib.RtSampleArray instance\n '
with self._mdib.mdibUpdateTransaction() as tr:
for (descriptorHandle, changedSample) in changedSamples.items():
determinationTime = changedSample.determinationTime
samples = [s[0] for s in changedSample.samples]
activationState = changedSample.activationState
st = tr.getRealTimeSampleArrayMetricState(descriptorHandle)
if (st.metricValue is None):
st.mkMetricValue()
st.metricValue.Samples = samples
st.metricValue.DeterminationTime = determinationTime
st.metricValue.Annotations = changedSample.annotations
st.metricValue.ApplyAnnotations = changedSample.applyAnnotations
st.ActivationState = activationState | @param changedSamples: a dictionary with key = handle, value= devicemdib.RtSampleArray instance | sdc11073/sdcdevice/sdc_handlers.py | sendWaveformUpdates | deichmab-draeger/sdc11073-1 | 0 | python | def sendWaveformUpdates(self, changedSamples):
'\n \n '
with self._mdib.mdibUpdateTransaction() as tr:
for (descriptorHandle, changedSample) in changedSamples.items():
determinationTime = changedSample.determinationTime
samples = [s[0] for s in changedSample.samples]
activationState = changedSample.activationState
st = tr.getRealTimeSampleArrayMetricState(descriptorHandle)
if (st.metricValue is None):
st.mkMetricValue()
st.metricValue.Samples = samples
st.metricValue.DeterminationTime = determinationTime
st.metricValue.Annotations = changedSample.annotations
st.metricValue.ApplyAnnotations = changedSample.applyAnnotations
st.ActivationState = activationState | def sendWaveformUpdates(self, changedSamples):
'\n \n '
with self._mdib.mdibUpdateTransaction() as tr:
for (descriptorHandle, changedSample) in changedSamples.items():
determinationTime = changedSample.determinationTime
samples = [s[0] for s in changedSample.samples]
activationState = changedSample.activationState
st = tr.getRealTimeSampleArrayMetricState(descriptorHandle)
if (st.metricValue is None):
st.mkMetricValue()
st.metricValue.Samples = samples
st.metricValue.DeterminationTime = determinationTime
st.metricValue.Annotations = changedSample.annotations
st.metricValue.ApplyAnnotations = changedSample.applyAnnotations
st.ActivationState = activationState<|docstring|>@param changedSamples: a dictionary with key = handle, value= devicemdib.RtSampleArray instance<|endoftext|> |
4c1fe770e5d5fc28e19dbff6a4c21fd8df9eff311129c5b35966179f97ce1753 | def __init__(self, *, configuration_attrs=None, read_attrs=None, **kwargs):
"\n if configuration_attrs is None:\n\n configuration_attrs = ['external_trig', 'total_points',\n\n 'spectra_per_point', 'settings',\n\n 'rewindable']\n\n if read_attrs is None:\n\n read_attrs = ['channel1', 'channel2', 'channel3', 'hdf5']\n "
super().__init__(configuration_attrs=configuration_attrs, read_attrs=read_attrs, **kwargs) | if configuration_attrs is None:
configuration_attrs = ['external_trig', 'total_points',
'spectra_per_point', 'settings',
'rewindable']
if read_attrs is None:
read_attrs = ['channel1', 'channel2', 'channel3', 'hdf5'] | srxgui/.ipython/profile_srx/startup/80-areadetectors.py | __init__ | whishei/srxgui | 0 | python | def __init__(self, *, configuration_attrs=None, read_attrs=None, **kwargs):
"\n if configuration_attrs is None:\n\n configuration_attrs = ['external_trig', 'total_points',\n\n 'spectra_per_point', 'settings',\n\n 'rewindable']\n\n if read_attrs is None:\n\n read_attrs = ['channel1', 'channel2', 'channel3', 'hdf5']\n "
super().__init__(configuration_attrs=configuration_attrs, read_attrs=read_attrs, **kwargs) | def __init__(self, *, configuration_attrs=None, read_attrs=None, **kwargs):
"\n if configuration_attrs is None:\n\n configuration_attrs = ['external_trig', 'total_points',\n\n 'spectra_per_point', 'settings',\n\n 'rewindable']\n\n if read_attrs is None:\n\n read_attrs = ['channel1', 'channel2', 'channel3', 'hdf5']\n "
super().__init__(configuration_attrs=configuration_attrs, read_attrs=read_attrs, **kwargs)<|docstring|>if configuration_attrs is None:
configuration_attrs = ['external_trig', 'total_points',
'spectra_per_point', 'settings',
'rewindable']
if read_attrs is None:
read_attrs = ['channel1', 'channel2', 'channel3', 'hdf5']<|endoftext|> |
17e1f432d80e16fc9ac7170eb5853cd8b85113f32ae32f2bcedbbe50451d3b95 | @pseudo_position_argument
def forward(self, pseudo_pos):
'Run a forward (pseudo -> real) calculation'
pseudo_pos = self.PseudoPosition(*pseudo_pos)
return self.RealPosition(harmonic=self.harmonic.position, fundamental=(pseudo_pos.energy / self.harmonic.position)) | Run a forward (pseudo -> real) calculation | srxgui/.ipython/profile_srx/startup/80-areadetectors.py | forward | whishei/srxgui | 0 | python | @pseudo_position_argument
def forward(self, pseudo_pos):
pseudo_pos = self.PseudoPosition(*pseudo_pos)
return self.RealPosition(harmonic=self.harmonic.position, fundamental=(pseudo_pos.energy / self.harmonic.position)) | @pseudo_position_argument
def forward(self, pseudo_pos):
pseudo_pos = self.PseudoPosition(*pseudo_pos)
return self.RealPosition(harmonic=self.harmonic.position, fundamental=(pseudo_pos.energy / self.harmonic.position))<|docstring|>Run a forward (pseudo -> real) calculation<|endoftext|> |
443e66acc5fe8526e91b966a0585334baff6509f010b8eb10051dee8ea6bb628 | @real_position_argument
def inverse(self, real_pos):
'Run an inverse (real -> pseudo) calculation'
real_pos = self.RealPosition(*real_pos)
return self.PseudoPosition(energy=(real_pos.fundamental * real_pos.harmonic)) | Run an inverse (real -> pseudo) calculation | srxgui/.ipython/profile_srx/startup/80-areadetectors.py | inverse | whishei/srxgui | 0 | python | @real_position_argument
def inverse(self, real_pos):
real_pos = self.RealPosition(*real_pos)
return self.PseudoPosition(energy=(real_pos.fundamental * real_pos.harmonic)) | @real_position_argument
def inverse(self, real_pos):
real_pos = self.RealPosition(*real_pos)
return self.PseudoPosition(energy=(real_pos.fundamental * real_pos.harmonic))<|docstring|>Run an inverse (real -> pseudo) calculation<|endoftext|> |
bb9b1eab22eb33435707a24fc0fd90f7722c64c61b3ca081d938347c09763a22 | def assertGood(self, expect_value, pred, context=None):
'Assert that got_result is expect_value returned by pred as valid.'
path_value = PathValue('', expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path='', path_value=path_value, valid=True)
self.assertEqual(expect, got_result) | Assert that got_result is expect_value returned by pred as valid. | tests/json_predicate/simple_binary_prediate_test.py | assertGood | plumpy/citest | 69 | python | def assertGood(self, expect_value, pred, context=None):
path_value = PathValue(, expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path=, path_value=path_value, valid=True)
self.assertEqual(expect, got_result) | def assertGood(self, expect_value, pred, context=None):
path_value = PathValue(, expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path=, path_value=path_value, valid=True)
self.assertEqual(expect, got_result)<|docstring|>Assert that got_result is expect_value returned by pred as valid.<|endoftext|> |
45364b7c7d384a4898f61f47fd1e6cf202a3f9dae7ec439b892e87cd458052d9 | def assertBad(self, expect_value, pred, context=None):
'Assert that got_result is expect_value returned by pred as invalid.'
path_value = PathValue('', expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path='', path_value=path_value, valid=False)
self.assertEqual(expect, got_result) | Assert that got_result is expect_value returned by pred as invalid. | tests/json_predicate/simple_binary_prediate_test.py | assertBad | plumpy/citest | 69 | python | def assertBad(self, expect_value, pred, context=None):
path_value = PathValue(, expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path=, path_value=path_value, valid=False)
self.assertEqual(expect, got_result) | def assertBad(self, expect_value, pred, context=None):
path_value = PathValue(, expect_value)
got_result = pred((context or ExecutionContext()), expect_value)
expect = jp.PathValueResult(pred=pred, source=expect_value, target_path=, path_value=path_value, valid=False)
self.assertEqual(expect, got_result)<|docstring|>Assert that got_result is expect_value returned by pred as invalid.<|endoftext|> |
6ac8f75caaff3b7025a80fcd8e475b66a9c84e5903adf7d1812ac46845f8690f | def simple_operand_type_mismatch_helper(self, context, expected_type, factory, good_operand, bad_operand):
'Helper method used to generate operand type mismatch errors.\n\n Args:\n factory: The factory to test.\n good_operand: A good operand value.\n bad_operand: A bad operand value.\n '
self.assertRaises(TypeError, factory, bad_operand)
pred = factory(good_operand)
try:
self.assertEqual(jp.TypeMismatchError(expected_type, bad_operand.__class__, bad_operand), pred(context, bad_operand))
except:
print('\nFAILED value={0} pred={1}'.format(good_operand, pred.name))
raise | Helper method used to generate operand type mismatch errors.
Args:
factory: The factory to test.
good_operand: A good operand value.
bad_operand: A bad operand value. | tests/json_predicate/simple_binary_prediate_test.py | simple_operand_type_mismatch_helper | plumpy/citest | 69 | python | def simple_operand_type_mismatch_helper(self, context, expected_type, factory, good_operand, bad_operand):
'Helper method used to generate operand type mismatch errors.\n\n Args:\n factory: The factory to test.\n good_operand: A good operand value.\n bad_operand: A bad operand value.\n '
self.assertRaises(TypeError, factory, bad_operand)
pred = factory(good_operand)
try:
self.assertEqual(jp.TypeMismatchError(expected_type, bad_operand.__class__, bad_operand), pred(context, bad_operand))
except:
print('\nFAILED value={0} pred={1}'.format(good_operand, pred.name))
raise | def simple_operand_type_mismatch_helper(self, context, expected_type, factory, good_operand, bad_operand):
'Helper method used to generate operand type mismatch errors.\n\n Args:\n factory: The factory to test.\n good_operand: A good operand value.\n bad_operand: A bad operand value.\n '
self.assertRaises(TypeError, factory, bad_operand)
pred = factory(good_operand)
try:
self.assertEqual(jp.TypeMismatchError(expected_type, bad_operand.__class__, bad_operand), pred(context, bad_operand))
except:
print('\nFAILED value={0} pred={1}'.format(good_operand, pred.name))
raise<|docstring|>Helper method used to generate operand type mismatch errors.
Args:
factory: The factory to test.
good_operand: A good operand value.
bad_operand: A bad operand value.<|endoftext|> |
89680b2bd689726b9464291f95205a00e65ad453c0bdc1a68a4ca17394ad0a2d | def create_tables(engine):
'\n Creates all tables defined with the base class.\n '
BASE.metadata.create_all(engine) | Creates all tables defined with the base class. | test/flask_restful_app/models.py | create_tables | MichaelWashburnJr/Flask-SQLAlchemy-Paging | 1 | python | def create_tables(engine):
'\n \n '
BASE.metadata.create_all(engine) | def create_tables(engine):
'\n \n '
BASE.metadata.create_all(engine)<|docstring|>Creates all tables defined with the base class.<|endoftext|> |
b20107f2cd9e8f4c13eaeda4db658c84454e3861efc3890b891d39a20adb6dda | def test_com_allsamples(self):
'\n Iterate over all of the sample/whois/*.com files, read the data,\n parse it, and compare to the expected values in sample/expected/.\n Only keys defined in keys_to_test will be tested.\n\n To generate fresh expected value dumps, see NOTE below.\n '
keys_to_test = ['domain_name', 'expiration_date', 'updated_date', 'creation_date', 'status']
fail = 0
total = 0
whois_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'whois', '*')
expect_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'expected')
for path in glob(whois_path):
domain = os.path.basename(path)
with open(path) as whois_fp:
data = whois_fp.read()
w = WhoisEntry.load(domain, data)
results = {key: w.get(key) for key in keys_to_test}
if False:
def date2str4json(obj):
if isinstance(obj, datetime.datetime):
return str(obj)
raise TypeError('{} is not JSON serializable'.format(repr(obj)))
outfile_name = os.path.join(expect_path, domain)
with open(outfile_name, 'w') as outfil:
expected_results = json.dump(results, outfil, default=date2str4json)
continue
with open(os.path.join(expect_path, domain)) as infil:
expected_results = json.load(infil)
compare_keys = set.union(set(results), set(expected_results))
if (keys_to_test is not None):
compare_keys = compare_keys.intersection(set(keys_to_test))
for key in compare_keys:
total += 1
if (key not in results):
print(('%s \t(%s):\t Missing in results' % (domain, key)))
fail += 1
continue
result = results.get(key)
if isinstance(result, list):
result = [str(element) for element in result]
if isinstance(result, datetime.datetime):
result = str(result)
expected = expected_results.get(key)
if (expected != result):
print(('%s \t(%s):\t %s != %s' % (domain, key, result, expected)))
fail += 1
if fail:
self.fail(('%d/%d sample whois attributes were not parsed properly!' % (fail, total))) | Iterate over all of the sample/whois/*.com files, read the data,
parse it, and compare to the expected values in sample/expected/.
Only keys defined in keys_to_test will be tested.
To generate fresh expected value dumps, see NOTE below. | test/test_parser.py | test_com_allsamples | mienkofax/openwhois | 1 | python | def test_com_allsamples(self):
'\n Iterate over all of the sample/whois/*.com files, read the data,\n parse it, and compare to the expected values in sample/expected/.\n Only keys defined in keys_to_test will be tested.\n\n To generate fresh expected value dumps, see NOTE below.\n '
keys_to_test = ['domain_name', 'expiration_date', 'updated_date', 'creation_date', 'status']
fail = 0
total = 0
whois_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'whois', '*')
expect_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'expected')
for path in glob(whois_path):
domain = os.path.basename(path)
with open(path) as whois_fp:
data = whois_fp.read()
w = WhoisEntry.load(domain, data)
results = {key: w.get(key) for key in keys_to_test}
if False:
def date2str4json(obj):
if isinstance(obj, datetime.datetime):
return str(obj)
raise TypeError('{} is not JSON serializable'.format(repr(obj)))
outfile_name = os.path.join(expect_path, domain)
with open(outfile_name, 'w') as outfil:
expected_results = json.dump(results, outfil, default=date2str4json)
continue
with open(os.path.join(expect_path, domain)) as infil:
expected_results = json.load(infil)
compare_keys = set.union(set(results), set(expected_results))
if (keys_to_test is not None):
compare_keys = compare_keys.intersection(set(keys_to_test))
for key in compare_keys:
total += 1
if (key not in results):
print(('%s \t(%s):\t Missing in results' % (domain, key)))
fail += 1
continue
result = results.get(key)
if isinstance(result, list):
result = [str(element) for element in result]
if isinstance(result, datetime.datetime):
result = str(result)
expected = expected_results.get(key)
if (expected != result):
print(('%s \t(%s):\t %s != %s' % (domain, key, result, expected)))
fail += 1
if fail:
self.fail(('%d/%d sample whois attributes were not parsed properly!' % (fail, total))) | def test_com_allsamples(self):
'\n Iterate over all of the sample/whois/*.com files, read the data,\n parse it, and compare to the expected values in sample/expected/.\n Only keys defined in keys_to_test will be tested.\n\n To generate fresh expected value dumps, see NOTE below.\n '
keys_to_test = ['domain_name', 'expiration_date', 'updated_date', 'creation_date', 'status']
fail = 0
total = 0
whois_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'whois', '*')
expect_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'samples', 'expected')
for path in glob(whois_path):
domain = os.path.basename(path)
with open(path) as whois_fp:
data = whois_fp.read()
w = WhoisEntry.load(domain, data)
results = {key: w.get(key) for key in keys_to_test}
if False:
def date2str4json(obj):
if isinstance(obj, datetime.datetime):
return str(obj)
raise TypeError('{} is not JSON serializable'.format(repr(obj)))
outfile_name = os.path.join(expect_path, domain)
with open(outfile_name, 'w') as outfil:
expected_results = json.dump(results, outfil, default=date2str4json)
continue
with open(os.path.join(expect_path, domain)) as infil:
expected_results = json.load(infil)
compare_keys = set.union(set(results), set(expected_results))
if (keys_to_test is not None):
compare_keys = compare_keys.intersection(set(keys_to_test))
for key in compare_keys:
total += 1
if (key not in results):
print(('%s \t(%s):\t Missing in results' % (domain, key)))
fail += 1
continue
result = results.get(key)
if isinstance(result, list):
result = [str(element) for element in result]
if isinstance(result, datetime.datetime):
result = str(result)
expected = expected_results.get(key)
if (expected != result):
print(('%s \t(%s):\t %s != %s' % (domain, key, result, expected)))
fail += 1
if fail:
self.fail(('%d/%d sample whois attributes were not parsed properly!' % (fail, total)))<|docstring|>Iterate over all of the sample/whois/*.com files, read the data,
parse it, and compare to the expected values in sample/expected/.
Only keys defined in keys_to_test will be tested.
To generate fresh expected value dumps, see NOTE below.<|endoftext|> |
e927efa1cf283b1bc403d6582526d31b94081c6d6342769ea7c1ba3708a03c74 | def get_random_contest_from(self, description: ContestDescription, random: Random, suppress_validity_check=False, with_trues=False) -> PlaintextBallotContest:
'\n Get a randomly filled contest for the given description that \n may be undervoted and may include explicitly false votes.\n Since this is only used for testing, the random number generator\n (`random`) must be provided to make this function deterministic.\n '
if (not suppress_validity_check):
assert description.is_valid(), 'the contest description must be valid'
selections: List[PlaintextBallotSelection] = list()
voted = 0
for selection_description in description.ballot_selections:
selection = self.get_random_selection_from(selection_description, random)
voted += selection.to_int()
if ((voted <= 1) and selection.to_int() and with_trues):
selections.append(selection)
continue
if ((voted <= description.number_elected) and (bool(random.randint(0, 1)) == 1)):
selections.append(selection)
elif (bool(random.randint(0, 1)) == 1):
selections.append(selection_from(selection_description))
return PlaintextBallotContest(description.object_id, selections) | Get a randomly filled contest for the given description that
may be undervoted and may include explicitly false votes.
Since this is only used for testing, the random number generator
(`random`) must be provided to make this function deterministic. | src/electionguardtest/ballot_factory.py | get_random_contest_from | Fredilein/electionguard-python | 1 | python | def get_random_contest_from(self, description: ContestDescription, random: Random, suppress_validity_check=False, with_trues=False) -> PlaintextBallotContest:
'\n Get a randomly filled contest for the given description that \n may be undervoted and may include explicitly false votes.\n Since this is only used for testing, the random number generator\n (`random`) must be provided to make this function deterministic.\n '
if (not suppress_validity_check):
assert description.is_valid(), 'the contest description must be valid'
selections: List[PlaintextBallotSelection] = list()
voted = 0
for selection_description in description.ballot_selections:
selection = self.get_random_selection_from(selection_description, random)
voted += selection.to_int()
if ((voted <= 1) and selection.to_int() and with_trues):
selections.append(selection)
continue
if ((voted <= description.number_elected) and (bool(random.randint(0, 1)) == 1)):
selections.append(selection)
elif (bool(random.randint(0, 1)) == 1):
selections.append(selection_from(selection_description))
return PlaintextBallotContest(description.object_id, selections) | def get_random_contest_from(self, description: ContestDescription, random: Random, suppress_validity_check=False, with_trues=False) -> PlaintextBallotContest:
'\n Get a randomly filled contest for the given description that \n may be undervoted and may include explicitly false votes.\n Since this is only used for testing, the random number generator\n (`random`) must be provided to make this function deterministic.\n '
if (not suppress_validity_check):
assert description.is_valid(), 'the contest description must be valid'
selections: List[PlaintextBallotSelection] = list()
voted = 0
for selection_description in description.ballot_selections:
selection = self.get_random_selection_from(selection_description, random)
voted += selection.to_int()
if ((voted <= 1) and selection.to_int() and with_trues):
selections.append(selection)
continue
if ((voted <= description.number_elected) and (bool(random.randint(0, 1)) == 1)):
selections.append(selection)
elif (bool(random.randint(0, 1)) == 1):
selections.append(selection_from(selection_description))
return PlaintextBallotContest(description.object_id, selections)<|docstring|>Get a randomly filled contest for the given description that
may be undervoted and may include explicitly false votes.
Since this is only used for testing, the random number generator
(`random`) must be provided to make this function deterministic.<|endoftext|> |
1e677f3aec776f749855855e0414fe13ccbb771c53ac08e55418331ae5efd4b8 | def get_fake_ballot(self, election: InternalElectionDescription, ballot_id: str=None, with_trues=True) -> PlaintextBallot:
'\n Get a single Fake Ballot object that is manually constructed with default vaules\n '
if (ballot_id is None):
ballot_id = 'some-unique-ballot-id-123'
contests: List[PlaintextBallotContest] = []
for contest in election.get_contests_for(election.ballot_styles[0].object_id):
contests.append(self.get_random_contest_from(contest, Random(), with_trues=with_trues))
fake_ballot = PlaintextBallot(ballot_id, election.ballot_styles[0].object_id, contests)
return fake_ballot | Get a single Fake Ballot object that is manually constructed with default vaules | src/electionguardtest/ballot_factory.py | get_fake_ballot | Fredilein/electionguard-python | 1 | python | def get_fake_ballot(self, election: InternalElectionDescription, ballot_id: str=None, with_trues=True) -> PlaintextBallot:
'\n \n '
if (ballot_id is None):
ballot_id = 'some-unique-ballot-id-123'
contests: List[PlaintextBallotContest] = []
for contest in election.get_contests_for(election.ballot_styles[0].object_id):
contests.append(self.get_random_contest_from(contest, Random(), with_trues=with_trues))
fake_ballot = PlaintextBallot(ballot_id, election.ballot_styles[0].object_id, contests)
return fake_ballot | def get_fake_ballot(self, election: InternalElectionDescription, ballot_id: str=None, with_trues=True) -> PlaintextBallot:
'\n \n '
if (ballot_id is None):
ballot_id = 'some-unique-ballot-id-123'
contests: List[PlaintextBallotContest] = []
for contest in election.get_contests_for(election.ballot_styles[0].object_id):
contests.append(self.get_random_contest_from(contest, Random(), with_trues=with_trues))
fake_ballot = PlaintextBallot(ballot_id, election.ballot_styles[0].object_id, contests)
return fake_ballot<|docstring|>Get a single Fake Ballot object that is manually constructed with default vaules<|endoftext|> |
b229ff0feb356e3219620a460be5a8ff14e15a296945a8c8bc93e9d22ed54508 | def test_status_code(self):
'\n A topic should be edited only by the owner.\n Unauthorized users should get a 404 response (Page Not Found)\n '
self.assertEquals(self.response.status_code, 404) | A topic should be edited only by the owner.
Unauthorized users should get a 404 response (Page Not Found) | boards/tests/test_view_edit_post.py | test_status_code | krishnakaushik25/django_boards_project | 0 | python | def test_status_code(self):
'\n A topic should be edited only by the owner.\n Unauthorized users should get a 404 response (Page Not Found)\n '
self.assertEquals(self.response.status_code, 404) | def test_status_code(self):
'\n A topic should be edited only by the owner.\n Unauthorized users should get a 404 response (Page Not Found)\n '
self.assertEquals(self.response.status_code, 404)<|docstring|>A topic should be edited only by the owner.
Unauthorized users should get a 404 response (Page Not Found)<|endoftext|> |
1050f728135be3668dfc84114cbb869f6a25307637394d8204b4043726cf2566 | @pytest.fixture
def vqe_parametric(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'HF'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
return _vqe | Initialize a VQE experiment with a custom hamiltonian
given as constant input | tests/conftest.py | vqe_parametric | yaoyongxin/qucochemistry | 0 | python | @pytest.fixture
def vqe_parametric(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'HF'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
return _vqe | @pytest.fixture
def vqe_parametric(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'HF'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=True, tomography=vqe_tomography, shotN=NSHOTS_FLOAT)
return _vqe<|docstring|>Initialize a VQE experiment with a custom hamiltonian
given as constant input<|endoftext|> |
968a4d6710163dfb756c0d2b7525f51333ade81d3c388c9c5d13dfad6983b6c2 | @pytest.fixture
def vqe_fixed(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
return _vqe | Initialize a VQE experiment with a custom hamiltonian
given as constant input | tests/conftest.py | vqe_fixed | yaoyongxin/qucochemistry | 0 | python | @pytest.fixture
def vqe_fixed(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
return _vqe | @pytest.fixture
def vqe_fixed(vqe_strategy, vqe_tomography, vqe_method):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input\n '
_vqe = None
if (vqe_strategy == 'custom_program'):
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
elif (vqe_strategy == 'UCCSD'):
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H2.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, method=vqe_method, strategy=vqe_strategy, parametric=False, tomography=vqe_tomography, shotN=NSHOTS_INT)
return _vqe<|docstring|>Initialize a VQE experiment with a custom hamiltonian
given as constant input<|endoftext|> |
ff96c8a3c42a84ba7f24d5b249caf0661d16a5574e41b9331696e1584365468b | @pytest.fixture
def vqe_qc(vqe_strategy, vqe_qc_backend, vqe_parametricflag, sample_molecule):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input, given a QC-type backend (tomography is always set to True then)\n '
_vqe = None
qc = None
vqe_cq = None
if (vqe_strategy == 'custom_program'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=True, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'HF'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'UCCSD'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-4Q-A-qvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-4Q-A-pyqvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('4q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('4q-pyqvm')
_vqe = VQEexperiment(molecule=sample_molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
return _vqe | Initialize a VQE experiment with a custom hamiltonian
given as constant input, given a QC-type backend (tomography is always set to True then) | tests/conftest.py | vqe_qc | yaoyongxin/qucochemistry | 0 | python | @pytest.fixture
def vqe_qc(vqe_strategy, vqe_qc_backend, vqe_parametricflag, sample_molecule):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input, given a QC-type backend (tomography is always set to True then)\n '
_vqe = None
qc = None
vqe_cq = None
if (vqe_strategy == 'custom_program'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=True, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'HF'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'UCCSD'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-4Q-A-qvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-4Q-A-pyqvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('4q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('4q-pyqvm')
_vqe = VQEexperiment(molecule=sample_molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
return _vqe | @pytest.fixture
def vqe_qc(vqe_strategy, vqe_qc_backend, vqe_parametricflag, sample_molecule):
'\n Initialize a VQE experiment with a custom hamiltonian\n given as constant input, given a QC-type backend (tomography is always set to True then)\n '
_vqe = None
qc = None
vqe_cq = None
if (vqe_strategy == 'custom_program'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
custom_ham = PauliSum([PauliTerm(*x) for x in HAMILTONIAN])
_vqe = VQEexperiment(hamiltonian=custom_ham, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=True, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'HF'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-2Q-A-qvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-2Q-A-pyqvm')
vqe_cq = [1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('2q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('2q-pyqvm')
cwd = os.path.abspath(os.path.dirname(__file__))
fname = os.path.join(cwd, 'resources', 'H.hdf5')
molecule = MolecularData(filename=fname)
_vqe = VQEexperiment(molecule=molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
elif (vqe_strategy == 'UCCSD'):
if (vqe_qc_backend == 'Aspen-qvm'):
qc = get_qc('Aspen-4-4Q-A-qvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Aspen-pyqvm'):
qc = get_qc('Aspen-4-4Q-A-pyqvm')
vqe_cq = [7, 0, 1, 2]
elif (vqe_qc_backend == 'Nq-qvm'):
qc = get_qc('4q-qvm')
elif (vqe_qc_backend == 'Nq-pyqvm'):
qc = get_qc('4q-pyqvm')
_vqe = VQEexperiment(molecule=sample_molecule, qc=qc, custom_qubits=vqe_cq, method='QC', strategy=vqe_strategy, parametric=vqe_parametricflag, tomography=True, shotN=NSHOTS_SMALL)
return _vqe<|docstring|>Initialize a VQE experiment with a custom hamiltonian
given as constant input, given a QC-type backend (tomography is always set to True then)<|endoftext|> |
247d9b589180c4bd7e59057f961c3fee05eb0f048b947c54358a398df5a9fa6a | def update_transform(self):
'\n Calculate a new estimate of the rigid transformation.\n\n '
muX = np.divide(np.sum(self.PX, axis=0), self.Np)
muY = np.divide(np.sum(np.dot(np.transpose(self.P), self.Y), axis=0), self.Np)
self.X_hat = (self.X - np.tile(muX, (self.N, 1)))
Y_hat = (self.Y - np.tile(muY, (self.M, 1)))
self.A = np.dot(np.transpose(self.X_hat), np.transpose(self.P))
self.A = np.dot(self.A, Y_hat)
self.YPY = np.dot(np.transpose(Y_hat), np.diag(self.P1))
self.YPY = np.dot(self.YPY, Y_hat)
self.B = np.linalg.solve(np.transpose(self.YPY), np.transpose(self.A))
self.t = (np.transpose(muX) - np.dot(np.transpose(self.B), np.transpose(muY))) | Calculate a new estimate of the rigid transformation. | pycpd/affine_registration.py | update_transform | Yang-L1/pycpd | 345 | python | def update_transform(self):
'\n \n\n '
muX = np.divide(np.sum(self.PX, axis=0), self.Np)
muY = np.divide(np.sum(np.dot(np.transpose(self.P), self.Y), axis=0), self.Np)
self.X_hat = (self.X - np.tile(muX, (self.N, 1)))
Y_hat = (self.Y - np.tile(muY, (self.M, 1)))
self.A = np.dot(np.transpose(self.X_hat), np.transpose(self.P))
self.A = np.dot(self.A, Y_hat)
self.YPY = np.dot(np.transpose(Y_hat), np.diag(self.P1))
self.YPY = np.dot(self.YPY, Y_hat)
self.B = np.linalg.solve(np.transpose(self.YPY), np.transpose(self.A))
self.t = (np.transpose(muX) - np.dot(np.transpose(self.B), np.transpose(muY))) | def update_transform(self):
'\n \n\n '
muX = np.divide(np.sum(self.PX, axis=0), self.Np)
muY = np.divide(np.sum(np.dot(np.transpose(self.P), self.Y), axis=0), self.Np)
self.X_hat = (self.X - np.tile(muX, (self.N, 1)))
Y_hat = (self.Y - np.tile(muY, (self.M, 1)))
self.A = np.dot(np.transpose(self.X_hat), np.transpose(self.P))
self.A = np.dot(self.A, Y_hat)
self.YPY = np.dot(np.transpose(Y_hat), np.diag(self.P1))
self.YPY = np.dot(self.YPY, Y_hat)
self.B = np.linalg.solve(np.transpose(self.YPY), np.transpose(self.A))
self.t = (np.transpose(muX) - np.dot(np.transpose(self.B), np.transpose(muY)))<|docstring|>Calculate a new estimate of the rigid transformation.<|endoftext|> |
87fcd5373b1262d19c220026f1e4599b4f83d8ee58c98a746c4c081569317a58 | def transform_point_cloud(self, Y=None):
'\n Update a point cloud using the new estimate of the affine transformation.\n\n '
if (Y is None):
self.TY = (np.dot(self.Y, self.B) + np.tile(self.t, (self.M, 1)))
return
else:
return (np.dot(Y, self.B) + np.tile(self.t, (Y.shape[0], 1))) | Update a point cloud using the new estimate of the affine transformation. | pycpd/affine_registration.py | transform_point_cloud | Yang-L1/pycpd | 345 | python | def transform_point_cloud(self, Y=None):
'\n \n\n '
if (Y is None):
self.TY = (np.dot(self.Y, self.B) + np.tile(self.t, (self.M, 1)))
return
else:
return (np.dot(Y, self.B) + np.tile(self.t, (Y.shape[0], 1))) | def transform_point_cloud(self, Y=None):
'\n \n\n '
if (Y is None):
self.TY = (np.dot(self.Y, self.B) + np.tile(self.t, (self.M, 1)))
return
else:
return (np.dot(Y, self.B) + np.tile(self.t, (Y.shape[0], 1)))<|docstring|>Update a point cloud using the new estimate of the affine transformation.<|endoftext|> |
0fe0ee386c00d32fdf27efb5f9f158b7e979caa233aaf35ba53959ff73263191 | def update_variance(self):
'\n Update the variance of the mixture model using the new estimate of the affine transformation.\n See the update rule for sigma2 in Fig. 3 of of https://arxiv.org/pdf/0905.2635.pdf.\n\n '
qprev = self.q
trAB = np.trace(np.dot(self.A, self.B))
xPx = np.dot(np.transpose(self.Pt1), np.sum(np.multiply(self.X_hat, self.X_hat), axis=1))
trBYPYP = np.trace(np.dot(np.dot(self.B, self.YPY), self.B))
self.q = ((((xPx - (2 * trAB)) + trBYPYP) / (2 * self.sigma2)) + (((self.D * self.Np) / 2) * np.log(self.sigma2)))
self.diff = np.abs((self.q - qprev))
self.sigma2 = ((xPx - trAB) / (self.Np * self.D))
if (self.sigma2 <= 0):
self.sigma2 = (self.tolerance / 10) | Update the variance of the mixture model using the new estimate of the affine transformation.
See the update rule for sigma2 in Fig. 3 of of https://arxiv.org/pdf/0905.2635.pdf. | pycpd/affine_registration.py | update_variance | Yang-L1/pycpd | 345 | python | def update_variance(self):
'\n Update the variance of the mixture model using the new estimate of the affine transformation.\n See the update rule for sigma2 in Fig. 3 of of https://arxiv.org/pdf/0905.2635.pdf.\n\n '
qprev = self.q
trAB = np.trace(np.dot(self.A, self.B))
xPx = np.dot(np.transpose(self.Pt1), np.sum(np.multiply(self.X_hat, self.X_hat), axis=1))
trBYPYP = np.trace(np.dot(np.dot(self.B, self.YPY), self.B))
self.q = ((((xPx - (2 * trAB)) + trBYPYP) / (2 * self.sigma2)) + (((self.D * self.Np) / 2) * np.log(self.sigma2)))
self.diff = np.abs((self.q - qprev))
self.sigma2 = ((xPx - trAB) / (self.Np * self.D))
if (self.sigma2 <= 0):
self.sigma2 = (self.tolerance / 10) | def update_variance(self):
'\n Update the variance of the mixture model using the new estimate of the affine transformation.\n See the update rule for sigma2 in Fig. 3 of of https://arxiv.org/pdf/0905.2635.pdf.\n\n '
qprev = self.q
trAB = np.trace(np.dot(self.A, self.B))
xPx = np.dot(np.transpose(self.Pt1), np.sum(np.multiply(self.X_hat, self.X_hat), axis=1))
trBYPYP = np.trace(np.dot(np.dot(self.B, self.YPY), self.B))
self.q = ((((xPx - (2 * trAB)) + trBYPYP) / (2 * self.sigma2)) + (((self.D * self.Np) / 2) * np.log(self.sigma2)))
self.diff = np.abs((self.q - qprev))
self.sigma2 = ((xPx - trAB) / (self.Np * self.D))
if (self.sigma2 <= 0):
self.sigma2 = (self.tolerance / 10)<|docstring|>Update the variance of the mixture model using the new estimate of the affine transformation.
See the update rule for sigma2 in Fig. 3 of of https://arxiv.org/pdf/0905.2635.pdf.<|endoftext|> |
87e81e205db57da3865fbb23a91c3cf0b2a27305755ffc96161aefa12dab14e0 | def get_registration_parameters(self):
'\n Return the current estimate of the affine transformation parameters.\n\n '
return (self.B, self.t) | Return the current estimate of the affine transformation parameters. | pycpd/affine_registration.py | get_registration_parameters | Yang-L1/pycpd | 345 | python | def get_registration_parameters(self):
'\n \n\n '
return (self.B, self.t) | def get_registration_parameters(self):
'\n \n\n '
return (self.B, self.t)<|docstring|>Return the current estimate of the affine transformation parameters.<|endoftext|> |
598d9594b0554e27f0a069303df65c4b4ce690caed46ed36b237eafe5de49451 | @sap.Script
def shell():
'\n Start an embedded (i)python instance with a global object "o"\n '
o = OpenQuake()
try:
import IPython
IPython.embed(banner1='IPython shell with a global object "o"')
except ImportError:
import code
code.interact(banner='Python shell with a global object "o"', local=dict(o=o)) | Start an embedded (i)python instance with a global object "o" | openquake/commands/shell.py | shell | gfzriesgos/shakyground-lfs | 1 | python | @sap.Script
def shell():
'\n \n '
o = OpenQuake()
try:
import IPython
IPython.embed(banner1='IPython shell with a global object "o"')
except ImportError:
import code
code.interact(banner='Python shell with a global object "o"', local=dict(o=o)) | @sap.Script
def shell():
'\n \n '
o = OpenQuake()
try:
import IPython
IPython.embed(banner1='IPython shell with a global object "o"')
except ImportError:
import code
code.interact(banner='Python shell with a global object "o"', local=dict(o=o))<|docstring|>Start an embedded (i)python instance with a global object "o"<|endoftext|> |
668bcb01fc5a3fdd896dfd351f57203500d49cb83e37b31070c4956385b56917 | def __init__(self, data_cfg, rung_i=2):
'\n Parameters\n ----------\n dataset_dir : str or os.path object\n path to the directory containing the images and metadata\n data_cfg : dict or Dict\n copy of the `data` field of `BNNConfig`\n\n '
self.__dict__ = data_cfg
self.img_dir = os.path.join(h0rton.tdlmc_data.__path__[0], 'rung{:d}'.format(rung_i))
self.img_paths = np.sort(list(Path(self.img_dir).rglob('*drizzled_image/lens-image.fits')))
rescale = transforms.Lambda(whiten_pixels)
log = transforms.Lambda(plus_1_log)
transforms_list = []
if self.log_pixels:
transforms_list.append(log)
if self.rescale_pixels:
transforms_list.append(rescale)
if (len(transforms_list) == 0):
self.X_transform = None
else:
self.X_transform = transforms.Compose(transforms_list)
self.cosmo_df = h0rton.tdlmc_utils.convert_to_dataframe(rung=rung_i, save_csv_path=None)
self.cosmo_df.sort_values('seed', axis=0, inplace=True)
self.n_data = self.cosmo_df.shape[0]
self.Y_dim = len(self.Y_cols)
self.exposure_time_factor = (self.noise_kwargs.exposure_time / 9600.0)
if self.add_noise:
self.noise_model = NoiseModelTorch(**self.noise_kwargs) | Parameters
----------
dataset_dir : str or os.path object
path to the directory containing the images and metadata
data_cfg : dict or Dict
copy of the `data` field of `BNNConfig` | h0rton/trainval_data/tdlmc_data.py | __init__ | jiwoncpark/h0rton | 4 | python | def __init__(self, data_cfg, rung_i=2):
'\n Parameters\n ----------\n dataset_dir : str or os.path object\n path to the directory containing the images and metadata\n data_cfg : dict or Dict\n copy of the `data` field of `BNNConfig`\n\n '
self.__dict__ = data_cfg
self.img_dir = os.path.join(h0rton.tdlmc_data.__path__[0], 'rung{:d}'.format(rung_i))
self.img_paths = np.sort(list(Path(self.img_dir).rglob('*drizzled_image/lens-image.fits')))
rescale = transforms.Lambda(whiten_pixels)
log = transforms.Lambda(plus_1_log)
transforms_list = []
if self.log_pixels:
transforms_list.append(log)
if self.rescale_pixels:
transforms_list.append(rescale)
if (len(transforms_list) == 0):
self.X_transform = None
else:
self.X_transform = transforms.Compose(transforms_list)
self.cosmo_df = h0rton.tdlmc_utils.convert_to_dataframe(rung=rung_i, save_csv_path=None)
self.cosmo_df.sort_values('seed', axis=0, inplace=True)
self.n_data = self.cosmo_df.shape[0]
self.Y_dim = len(self.Y_cols)
self.exposure_time_factor = (self.noise_kwargs.exposure_time / 9600.0)
if self.add_noise:
self.noise_model = NoiseModelTorch(**self.noise_kwargs) | def __init__(self, data_cfg, rung_i=2):
'\n Parameters\n ----------\n dataset_dir : str or os.path object\n path to the directory containing the images and metadata\n data_cfg : dict or Dict\n copy of the `data` field of `BNNConfig`\n\n '
self.__dict__ = data_cfg
self.img_dir = os.path.join(h0rton.tdlmc_data.__path__[0], 'rung{:d}'.format(rung_i))
self.img_paths = np.sort(list(Path(self.img_dir).rglob('*drizzled_image/lens-image.fits')))
rescale = transforms.Lambda(whiten_pixels)
log = transforms.Lambda(plus_1_log)
transforms_list = []
if self.log_pixels:
transforms_list.append(log)
if self.rescale_pixels:
transforms_list.append(rescale)
if (len(transforms_list) == 0):
self.X_transform = None
else:
self.X_transform = transforms.Compose(transforms_list)
self.cosmo_df = h0rton.tdlmc_utils.convert_to_dataframe(rung=rung_i, save_csv_path=None)
self.cosmo_df.sort_values('seed', axis=0, inplace=True)
self.n_data = self.cosmo_df.shape[0]
self.Y_dim = len(self.Y_cols)
self.exposure_time_factor = (self.noise_kwargs.exposure_time / 9600.0)
if self.add_noise:
self.noise_model = NoiseModelTorch(**self.noise_kwargs)<|docstring|>Parameters
----------
dataset_dir : str or os.path object
path to the directory containing the images and metadata
data_cfg : dict or Dict
copy of the `data` field of `BNNConfig`<|endoftext|> |
2f60db13d0d9cd0ac17a04b8897565c4f5a4a39c1a194cc8d893a0fc82632516 | @classmethod
def serialize_operator(cls, op: BaseOperator) -> dict:
'Serializes operator into a JSON object.\n '
serialize_op = {}
for k in op._serialized_fields:
v = getattr(op, k, None)
if cls._is_excluded(v, k, op):
continue
if (k in cls._decorated_fields):
serialize_op[k] = cls._serialize(v)
else:
v = cls._serialize(v)
if (isinstance(v, dict) and ('__type' in v)):
v = v['__var']
serialize_op[k] = v
serialize_op['_task_type'] = op.__class__.__name__
serialize_op['_task_module'] = op.__class__.__module__
return serialize_op | Serializes operator into a JSON object. | airflow/serialization/serialized_baseoperator.py | serialize_operator | jmathis-jc/airflow | 1 | python | @classmethod
def serialize_operator(cls, op: BaseOperator) -> dict:
'\n '
serialize_op = {}
for k in op._serialized_fields:
v = getattr(op, k, None)
if cls._is_excluded(v, k, op):
continue
if (k in cls._decorated_fields):
serialize_op[k] = cls._serialize(v)
else:
v = cls._serialize(v)
if (isinstance(v, dict) and ('__type' in v)):
v = v['__var']
serialize_op[k] = v
serialize_op['_task_type'] = op.__class__.__name__
serialize_op['_task_module'] = op.__class__.__module__
return serialize_op | @classmethod
def serialize_operator(cls, op: BaseOperator) -> dict:
'\n '
serialize_op = {}
for k in op._serialized_fields:
v = getattr(op, k, None)
if cls._is_excluded(v, k, op):
continue
if (k in cls._decorated_fields):
serialize_op[k] = cls._serialize(v)
else:
v = cls._serialize(v)
if (isinstance(v, dict) and ('__type' in v)):
v = v['__var']
serialize_op[k] = v
serialize_op['_task_type'] = op.__class__.__name__
serialize_op['_task_module'] = op.__class__.__module__
return serialize_op<|docstring|>Serializes operator into a JSON object.<|endoftext|> |
81dff160dacaefeaa0c5f97b247584ddd2ab5d33c569d42a09b04ce9d3b8d6e2 | @classmethod
def deserialize_operator(cls, encoded_op: dict) -> BaseOperator:
'Deserializes an operator from a JSON object.\n '
from airflow.serialization import SerializedDAG
from airflow.plugins_manager import operator_extra_links
op = SerializedBaseOperator(task_id=encoded_op['task_id'])
op_extra_links_from_plugin = {}
for ope in operator_extra_links:
for operator in ope.operators:
if ((operator.__name__ == encoded_op['_task_type']) and (operator.__module__ == encoded_op['_task_module'])):
op_extra_links_from_plugin.update({ope.name: ope})
setattr(op, 'operator_extra_links', list(op_extra_links_from_plugin.values()))
for (k, v) in encoded_op.items():
if (k == '_downstream_task_ids'):
v = set(v)
elif (k == 'subdag'):
v = SerializedDAG.deserialize_dag(v)
elif (k in {'retry_delay', 'execution_timeout'}):
v = cls._deserialize_timedelta(v)
elif k.endswith('_date'):
v = cls._deserialize_datetime(v)
elif ((k in cls._decorated_fields) or (k not in op._serialized_fields)):
v = cls._deserialize(v)
setattr(op, k, v)
for k in ((op._serialized_fields - encoded_op.keys()) - cls._CONSTRUCTOR_PARAMS.keys()):
setattr(op, k, None)
return op | Deserializes an operator from a JSON object. | airflow/serialization/serialized_baseoperator.py | deserialize_operator | jmathis-jc/airflow | 1 | python | @classmethod
def deserialize_operator(cls, encoded_op: dict) -> BaseOperator:
'\n '
from airflow.serialization import SerializedDAG
from airflow.plugins_manager import operator_extra_links
op = SerializedBaseOperator(task_id=encoded_op['task_id'])
op_extra_links_from_plugin = {}
for ope in operator_extra_links:
for operator in ope.operators:
if ((operator.__name__ == encoded_op['_task_type']) and (operator.__module__ == encoded_op['_task_module'])):
op_extra_links_from_plugin.update({ope.name: ope})
setattr(op, 'operator_extra_links', list(op_extra_links_from_plugin.values()))
for (k, v) in encoded_op.items():
if (k == '_downstream_task_ids'):
v = set(v)
elif (k == 'subdag'):
v = SerializedDAG.deserialize_dag(v)
elif (k in {'retry_delay', 'execution_timeout'}):
v = cls._deserialize_timedelta(v)
elif k.endswith('_date'):
v = cls._deserialize_datetime(v)
elif ((k in cls._decorated_fields) or (k not in op._serialized_fields)):
v = cls._deserialize(v)
setattr(op, k, v)
for k in ((op._serialized_fields - encoded_op.keys()) - cls._CONSTRUCTOR_PARAMS.keys()):
setattr(op, k, None)
return op | @classmethod
def deserialize_operator(cls, encoded_op: dict) -> BaseOperator:
'\n '
from airflow.serialization import SerializedDAG
from airflow.plugins_manager import operator_extra_links
op = SerializedBaseOperator(task_id=encoded_op['task_id'])
op_extra_links_from_plugin = {}
for ope in operator_extra_links:
for operator in ope.operators:
if ((operator.__name__ == encoded_op['_task_type']) and (operator.__module__ == encoded_op['_task_module'])):
op_extra_links_from_plugin.update({ope.name: ope})
setattr(op, 'operator_extra_links', list(op_extra_links_from_plugin.values()))
for (k, v) in encoded_op.items():
if (k == '_downstream_task_ids'):
v = set(v)
elif (k == 'subdag'):
v = SerializedDAG.deserialize_dag(v)
elif (k in {'retry_delay', 'execution_timeout'}):
v = cls._deserialize_timedelta(v)
elif k.endswith('_date'):
v = cls._deserialize_datetime(v)
elif ((k in cls._decorated_fields) or (k not in op._serialized_fields)):
v = cls._deserialize(v)
setattr(op, k, v)
for k in ((op._serialized_fields - encoded_op.keys()) - cls._CONSTRUCTOR_PARAMS.keys()):
setattr(op, k, None)
return op<|docstring|>Deserializes an operator from a JSON object.<|endoftext|> |
4a14d78241be01d8a6ab72a8a95e325c2914d2a78d33b18b35bf32365c413ff3 | def get_args(parser_args=False):
"Get 'pup' command arguments"
parser = ArgumentParser(description=PROJECT, epilog=EPILOG, formatter_class=RawTextHelpFormatter, prog='pup')
subparsers = parser.add_subparsers()
common_parser = ArgumentParser(add_help=False)
common_parser.add_argument('-f', '--log-level-file', nargs=1, default=LOG_LEVEL_FILE, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to file\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_FILE[0]))
common_parser.add_argument('-p', '--log-level-print', nargs=1, default=LOG_LEVEL_PRINT, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to stdout/stderr\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_PRINT[0]))
common_parser.add_argument('--extra-vars', nargs=1, metavar='EXTRA-VARS', help='Provide extra variables to PowerUp')
parser_setup = subparsers.add_parser(SETUP_CMD, description=('%s - %s' % (PROJECT, SETUP_DESC)), help=SETUP_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_config = subparsers.add_parser(CONFIG_CMD, description=('%s - %s' % (PROJECT, CONFIG_DESC)), help=CONFIG_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_validate = subparsers.add_parser(VALIDATE_CMD, description=('%s - %s' % (PROJECT, VALIDATE_DESC)), help=VALIDATE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_deploy = subparsers.add_parser(DEPLOY_CMD, description=('%s - %s' % (PROJECT, DEPLOY_DESC)), help=DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_post_deploy = subparsers.add_parser(POST_DEPLOY_CMD, description=('%s - %s' % (PROJECT, POST_DEPLOY_DESC)), help=POST_DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_software = subparsers.add_parser(SOFTWARE_CMD, description=('%s - %s' % (PROJECT, SOFTWARE_DESC)), help=SOFTWARE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_osinstall = subparsers.add_parser(OSINSTALL_CMD, description=('%s - %s' % (PROJECT, OSINSTALL_DESC)), help=OSINSTALL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_utils = subparsers.add_parser(UTIL_CMD, description=('%s - %s' % (PROJECT, UTIL_DESC)), help=UTIL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_setup.set_defaults(setup=True)
parser_setup.add_argument('--networks', action='store_true', help='Create deployer interfaces, vlans and bridges')
parser_setup.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_setup.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_setup.add_argument('-a', '--all', action='store_true', help='Run all cluster setup steps')
parser_config.set_defaults(config=True)
parser_config.add_argument('--mgmt-switches', action='store_true', help='Configure the cluster management switches')
parser_config.add_argument('--data-switches', action='store_true', help='Configure the cluster data switches')
parser_config.add_argument('--create-container', action='store_true', help='Create deployer container')
parser_config.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.set_defaults(validate=True)
parser_validate.add_argument('--config-file', action='store_true', help='Schema and logic config file validation')
parser_validate.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.add_argument('--cluster-hardware', action='store_true', help='Cluster hardware discovery and validation')
parser_deploy.set_defaults(deploy=True)
parser_deploy.add_argument('--create-inventory', action='store_true', help='Create inventory')
parser_deploy.add_argument('--install-cobbler', action='store_true', help='Install Cobbler')
parser_deploy.add_argument('--download-os-images', action='store_true', help='Download OS images')
parser_deploy.add_argument('--inv-add-ports-ipmi', action='store_true', help='Discover and add IPMI ports to inventory')
parser_deploy.add_argument('--inv-add-ports-pxe', action='store_true', help='Discover and add PXE ports to inventory')
parser_deploy.add_argument('--reserve-ipmi-pxe-ips', action='store_true', help='Configure DHCP IP reservations for IPMI and PXE interfaces')
parser_deploy.add_argument('--add-cobbler-distros', action='store_true', help='Add Cobbler distros and profiles')
parser_deploy.add_argument('--add-cobbler-systems', action='store_true', help='Add Cobbler systems')
parser_deploy.add_argument('--install-client-os', action='store_true', help='Initiate client OS installation(s)')
parser_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster deployment steps')
parser_post_deploy.set_defaults(post_deploy=True)
parser_post_deploy.add_argument('--ssh-keyscan', action='store_true', help='Scan SSH keys')
parser_post_deploy.add_argument('--gather-mac-addr', action='store_true', help='Gather MAC addresses from switches and update inventory')
parser_post_deploy.add_argument('--lookup-interface-names', action='store_true', help="Lookup OS assigned name of all interfaces configured with 'rename: false' and update inventory")
parser_post_deploy.add_argument('--config-client-os', action='store_true', help='Configure cluster nodes client OS')
parser_post_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Config files need to reside in the power-up directory.')
parser_post_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster post deployment steps')
parser_osinstall.set_defaults(osinstall=True)
parser_osinstall.add_argument('--setup-interfaces', action='store_true', help='Create deployer interfaces.')
parser_osinstall.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_osinstall.add_argument('config_file_name', nargs='?', default='profile.yml', metavar='CONFIG-FILE-NAME', help='OS installation profile file name. Specify relative to the power-up directory.')
parser_software.set_defaults(software=True)
parser_software.add_argument('name', nargs='?', help='Software module name')
parser_software.add_argument('--prep', default=ABSENT, action='store_true', help='Download software packages and pre-requisite repositories and sets\nup this node as the server for the software')
parser_software.add_argument('--init-clients', default=ABSENT, action='store_true', help='Initialize the cluster clients to access the POWER-Up software server')
parser_software.add_argument('--install', default=ABSENT, action='store_true', help='Install the specified software to cluster nodes')
parser_software.add_argument('--README', default=ABSENT, action='store_true', help='Display software install module help')
parser_software.add_argument('--status', default=ABSENT, action='store_true', help='Display software install module preparation status')
parser_software.add_argument('--eval', default=False, action='store_true', help='Install the evaluation version of software if available')
parser_software.add_argument('--non-interactive', default=False, action='store_true', help='Runs the software phase with minimal user interaction')
parser_software.add_argument('-a', '--all', action='store_true', help='Run all software prep and install steps')
parser_software.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
parser_software.add_argument('--extract-from', nargs=1, help='Extract bundled repos and software directory')
parser_software.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_software.add_argument('--arch', default='ppc64le', choices=['ppc64le', 'x86_64'], help='Runs the software phase with specified architecture')
parser_software.add_argument('--base-dir', default=None, help='Set the base directory for storing server content. This directory will reside under the web server root directory.')
parser_software.add_argument('--step', default=None, nargs='+', choices=['ibmai_repo', 'cuda_drv_repo', 'wmla_license', 'spectrum_dli', 'spectrum_conductor', 'dependency_repo', 'conda_content_repo', 'conda_free_repo', 'conda_main_repo', 'pypi_repo', 'epel_repo'], help='Runs the software phase with specified step')
parser_software.add_argument('--proc-family', default='p8', nargs='+', choices=['p8', 'p9', 'x86_64'], help='Set the target processor family')
parser_software.add_argument('--engr-mode', default=False, action='store_true', help='Runs engineering mode function')
parser_software.add_argument('--public', default=None, action='store_true', help='Use public access, default is to use --prep to install private repos')
parser_software.add_argument('--run_ansible_task', default=None, nargs='+', help='Runs ansbile task from specified software directory')
parser_utils.set_defaults(utils=True)
parser_utils.add_argument('--scan-pxe-network', action='store_true', help='Ping all addresses in PXE subnet')
parser_utils.add_argument('--scan-ipmi-network', action='store_true', help='Ping all addresses in IPMI subnet')
parser_utils.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_utils.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_utils.add_argument('--bundle-from', nargs=1, help='Extract bundled repos and software directory')
parser_utils.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
if parser_args:
return (parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_software, parser_osinstall, parser_utils)
return parser | Get 'pup' command arguments | scripts/python/lib/argparse_gen.py | get_args | Bhaskers-Blu-Org1/power-up | 8 | python | def get_args(parser_args=False):
parser = ArgumentParser(description=PROJECT, epilog=EPILOG, formatter_class=RawTextHelpFormatter, prog='pup')
subparsers = parser.add_subparsers()
common_parser = ArgumentParser(add_help=False)
common_parser.add_argument('-f', '--log-level-file', nargs=1, default=LOG_LEVEL_FILE, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to file\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_FILE[0]))
common_parser.add_argument('-p', '--log-level-print', nargs=1, default=LOG_LEVEL_PRINT, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to stdout/stderr\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_PRINT[0]))
common_parser.add_argument('--extra-vars', nargs=1, metavar='EXTRA-VARS', help='Provide extra variables to PowerUp')
parser_setup = subparsers.add_parser(SETUP_CMD, description=('%s - %s' % (PROJECT, SETUP_DESC)), help=SETUP_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_config = subparsers.add_parser(CONFIG_CMD, description=('%s - %s' % (PROJECT, CONFIG_DESC)), help=CONFIG_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_validate = subparsers.add_parser(VALIDATE_CMD, description=('%s - %s' % (PROJECT, VALIDATE_DESC)), help=VALIDATE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_deploy = subparsers.add_parser(DEPLOY_CMD, description=('%s - %s' % (PROJECT, DEPLOY_DESC)), help=DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_post_deploy = subparsers.add_parser(POST_DEPLOY_CMD, description=('%s - %s' % (PROJECT, POST_DEPLOY_DESC)), help=POST_DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_software = subparsers.add_parser(SOFTWARE_CMD, description=('%s - %s' % (PROJECT, SOFTWARE_DESC)), help=SOFTWARE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_osinstall = subparsers.add_parser(OSINSTALL_CMD, description=('%s - %s' % (PROJECT, OSINSTALL_DESC)), help=OSINSTALL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_utils = subparsers.add_parser(UTIL_CMD, description=('%s - %s' % (PROJECT, UTIL_DESC)), help=UTIL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_setup.set_defaults(setup=True)
parser_setup.add_argument('--networks', action='store_true', help='Create deployer interfaces, vlans and bridges')
parser_setup.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_setup.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_setup.add_argument('-a', '--all', action='store_true', help='Run all cluster setup steps')
parser_config.set_defaults(config=True)
parser_config.add_argument('--mgmt-switches', action='store_true', help='Configure the cluster management switches')
parser_config.add_argument('--data-switches', action='store_true', help='Configure the cluster data switches')
parser_config.add_argument('--create-container', action='store_true', help='Create deployer container')
parser_config.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.set_defaults(validate=True)
parser_validate.add_argument('--config-file', action='store_true', help='Schema and logic config file validation')
parser_validate.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.add_argument('--cluster-hardware', action='store_true', help='Cluster hardware discovery and validation')
parser_deploy.set_defaults(deploy=True)
parser_deploy.add_argument('--create-inventory', action='store_true', help='Create inventory')
parser_deploy.add_argument('--install-cobbler', action='store_true', help='Install Cobbler')
parser_deploy.add_argument('--download-os-images', action='store_true', help='Download OS images')
parser_deploy.add_argument('--inv-add-ports-ipmi', action='store_true', help='Discover and add IPMI ports to inventory')
parser_deploy.add_argument('--inv-add-ports-pxe', action='store_true', help='Discover and add PXE ports to inventory')
parser_deploy.add_argument('--reserve-ipmi-pxe-ips', action='store_true', help='Configure DHCP IP reservations for IPMI and PXE interfaces')
parser_deploy.add_argument('--add-cobbler-distros', action='store_true', help='Add Cobbler distros and profiles')
parser_deploy.add_argument('--add-cobbler-systems', action='store_true', help='Add Cobbler systems')
parser_deploy.add_argument('--install-client-os', action='store_true', help='Initiate client OS installation(s)')
parser_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster deployment steps')
parser_post_deploy.set_defaults(post_deploy=True)
parser_post_deploy.add_argument('--ssh-keyscan', action='store_true', help='Scan SSH keys')
parser_post_deploy.add_argument('--gather-mac-addr', action='store_true', help='Gather MAC addresses from switches and update inventory')
parser_post_deploy.add_argument('--lookup-interface-names', action='store_true', help="Lookup OS assigned name of all interfaces configured with 'rename: false' and update inventory")
parser_post_deploy.add_argument('--config-client-os', action='store_true', help='Configure cluster nodes client OS')
parser_post_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Config files need to reside in the power-up directory.')
parser_post_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster post deployment steps')
parser_osinstall.set_defaults(osinstall=True)
parser_osinstall.add_argument('--setup-interfaces', action='store_true', help='Create deployer interfaces.')
parser_osinstall.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_osinstall.add_argument('config_file_name', nargs='?', default='profile.yml', metavar='CONFIG-FILE-NAME', help='OS installation profile file name. Specify relative to the power-up directory.')
parser_software.set_defaults(software=True)
parser_software.add_argument('name', nargs='?', help='Software module name')
parser_software.add_argument('--prep', default=ABSENT, action='store_true', help='Download software packages and pre-requisite repositories and sets\nup this node as the server for the software')
parser_software.add_argument('--init-clients', default=ABSENT, action='store_true', help='Initialize the cluster clients to access the POWER-Up software server')
parser_software.add_argument('--install', default=ABSENT, action='store_true', help='Install the specified software to cluster nodes')
parser_software.add_argument('--README', default=ABSENT, action='store_true', help='Display software install module help')
parser_software.add_argument('--status', default=ABSENT, action='store_true', help='Display software install module preparation status')
parser_software.add_argument('--eval', default=False, action='store_true', help='Install the evaluation version of software if available')
parser_software.add_argument('--non-interactive', default=False, action='store_true', help='Runs the software phase with minimal user interaction')
parser_software.add_argument('-a', '--all', action='store_true', help='Run all software prep and install steps')
parser_software.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
parser_software.add_argument('--extract-from', nargs=1, help='Extract bundled repos and software directory')
parser_software.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_software.add_argument('--arch', default='ppc64le', choices=['ppc64le', 'x86_64'], help='Runs the software phase with specified architecture')
parser_software.add_argument('--base-dir', default=None, help='Set the base directory for storing server content. This directory will reside under the web server root directory.')
parser_software.add_argument('--step', default=None, nargs='+', choices=['ibmai_repo', 'cuda_drv_repo', 'wmla_license', 'spectrum_dli', 'spectrum_conductor', 'dependency_repo', 'conda_content_repo', 'conda_free_repo', 'conda_main_repo', 'pypi_repo', 'epel_repo'], help='Runs the software phase with specified step')
parser_software.add_argument('--proc-family', default='p8', nargs='+', choices=['p8', 'p9', 'x86_64'], help='Set the target processor family')
parser_software.add_argument('--engr-mode', default=False, action='store_true', help='Runs engineering mode function')
parser_software.add_argument('--public', default=None, action='store_true', help='Use public access, default is to use --prep to install private repos')
parser_software.add_argument('--run_ansible_task', default=None, nargs='+', help='Runs ansbile task from specified software directory')
parser_utils.set_defaults(utils=True)
parser_utils.add_argument('--scan-pxe-network', action='store_true', help='Ping all addresses in PXE subnet')
parser_utils.add_argument('--scan-ipmi-network', action='store_true', help='Ping all addresses in IPMI subnet')
parser_utils.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_utils.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_utils.add_argument('--bundle-from', nargs=1, help='Extract bundled repos and software directory')
parser_utils.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
if parser_args:
return (parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_software, parser_osinstall, parser_utils)
return parser | def get_args(parser_args=False):
parser = ArgumentParser(description=PROJECT, epilog=EPILOG, formatter_class=RawTextHelpFormatter, prog='pup')
subparsers = parser.add_subparsers()
common_parser = ArgumentParser(add_help=False)
common_parser.add_argument('-f', '--log-level-file', nargs=1, default=LOG_LEVEL_FILE, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to file\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_FILE[0]))
common_parser.add_argument('-p', '--log-level-print', nargs=1, default=LOG_LEVEL_PRINT, choices=LOG_LEVEL_CHOICES, metavar='LOG-LEVEL', help='Add log to stdout/stderr\nChoices: {}\nDefault: {}'.format(','.join(LOG_LEVEL_CHOICES), LOG_LEVEL_PRINT[0]))
common_parser.add_argument('--extra-vars', nargs=1, metavar='EXTRA-VARS', help='Provide extra variables to PowerUp')
parser_setup = subparsers.add_parser(SETUP_CMD, description=('%s - %s' % (PROJECT, SETUP_DESC)), help=SETUP_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_config = subparsers.add_parser(CONFIG_CMD, description=('%s - %s' % (PROJECT, CONFIG_DESC)), help=CONFIG_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_validate = subparsers.add_parser(VALIDATE_CMD, description=('%s - %s' % (PROJECT, VALIDATE_DESC)), help=VALIDATE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_deploy = subparsers.add_parser(DEPLOY_CMD, description=('%s - %s' % (PROJECT, DEPLOY_DESC)), help=DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_post_deploy = subparsers.add_parser(POST_DEPLOY_CMD, description=('%s - %s' % (PROJECT, POST_DEPLOY_DESC)), help=POST_DEPLOY_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_software = subparsers.add_parser(SOFTWARE_CMD, description=('%s - %s' % (PROJECT, SOFTWARE_DESC)), help=SOFTWARE_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_osinstall = subparsers.add_parser(OSINSTALL_CMD, description=('%s - %s' % (PROJECT, OSINSTALL_DESC)), help=OSINSTALL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_utils = subparsers.add_parser(UTIL_CMD, description=('%s - %s' % (PROJECT, UTIL_DESC)), help=UTIL_DESC, epilog=EPILOG, parents=[common_parser], formatter_class=RawTextHelpFormatter)
parser_setup.set_defaults(setup=True)
parser_setup.add_argument('--networks', action='store_true', help='Create deployer interfaces, vlans and bridges')
parser_setup.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_setup.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_setup.add_argument('-a', '--all', action='store_true', help='Run all cluster setup steps')
parser_config.set_defaults(config=True)
parser_config.add_argument('--mgmt-switches', action='store_true', help='Configure the cluster management switches')
parser_config.add_argument('--data-switches', action='store_true', help='Configure the cluster data switches')
parser_config.add_argument('--create-container', action='store_true', help='Create deployer container')
parser_config.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.set_defaults(validate=True)
parser_validate.add_argument('--config-file', action='store_true', help='Schema and logic config file validation')
parser_validate.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_validate.add_argument('--cluster-hardware', action='store_true', help='Cluster hardware discovery and validation')
parser_deploy.set_defaults(deploy=True)
parser_deploy.add_argument('--create-inventory', action='store_true', help='Create inventory')
parser_deploy.add_argument('--install-cobbler', action='store_true', help='Install Cobbler')
parser_deploy.add_argument('--download-os-images', action='store_true', help='Download OS images')
parser_deploy.add_argument('--inv-add-ports-ipmi', action='store_true', help='Discover and add IPMI ports to inventory')
parser_deploy.add_argument('--inv-add-ports-pxe', action='store_true', help='Discover and add PXE ports to inventory')
parser_deploy.add_argument('--reserve-ipmi-pxe-ips', action='store_true', help='Configure DHCP IP reservations for IPMI and PXE interfaces')
parser_deploy.add_argument('--add-cobbler-distros', action='store_true', help='Add Cobbler distros and profiles')
parser_deploy.add_argument('--add-cobbler-systems', action='store_true', help='Add Cobbler systems')
parser_deploy.add_argument('--install-client-os', action='store_true', help='Initiate client OS installation(s)')
parser_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster deployment steps')
parser_post_deploy.set_defaults(post_deploy=True)
parser_post_deploy.add_argument('--ssh-keyscan', action='store_true', help='Scan SSH keys')
parser_post_deploy.add_argument('--gather-mac-addr', action='store_true', help='Gather MAC addresses from switches and update inventory')
parser_post_deploy.add_argument('--lookup-interface-names', action='store_true', help="Lookup OS assigned name of all interfaces configured with 'rename: false' and update inventory")
parser_post_deploy.add_argument('--config-client-os', action='store_true', help='Configure cluster nodes client OS')
parser_post_deploy.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Config files need to reside in the power-up directory.')
parser_post_deploy.add_argument('-a', '--all', action='store_true', help='Run all cluster post deployment steps')
parser_osinstall.set_defaults(osinstall=True)
parser_osinstall.add_argument('--setup-interfaces', action='store_true', help='Create deployer interfaces.')
parser_osinstall.add_argument('--gateway', action='store_true', help='Configure PXE network gateway and NAT record')
parser_osinstall.add_argument('config_file_name', nargs='?', default='profile.yml', metavar='CONFIG-FILE-NAME', help='OS installation profile file name. Specify relative to the power-up directory.')
parser_software.set_defaults(software=True)
parser_software.add_argument('name', nargs='?', help='Software module name')
parser_software.add_argument('--prep', default=ABSENT, action='store_true', help='Download software packages and pre-requisite repositories and sets\nup this node as the server for the software')
parser_software.add_argument('--init-clients', default=ABSENT, action='store_true', help='Initialize the cluster clients to access the POWER-Up software server')
parser_software.add_argument('--install', default=ABSENT, action='store_true', help='Install the specified software to cluster nodes')
parser_software.add_argument('--README', default=ABSENT, action='store_true', help='Display software install module help')
parser_software.add_argument('--status', default=ABSENT, action='store_true', help='Display software install module preparation status')
parser_software.add_argument('--eval', default=False, action='store_true', help='Install the evaluation version of software if available')
parser_software.add_argument('--non-interactive', default=False, action='store_true', help='Runs the software phase with minimal user interaction')
parser_software.add_argument('-a', '--all', action='store_true', help='Run all software prep and install steps')
parser_software.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
parser_software.add_argument('--extract-from', nargs=1, help='Extract bundled repos and software directory')
parser_software.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_software.add_argument('--arch', default='ppc64le', choices=['ppc64le', 'x86_64'], help='Runs the software phase with specified architecture')
parser_software.add_argument('--base-dir', default=None, help='Set the base directory for storing server content. This directory will reside under the web server root directory.')
parser_software.add_argument('--step', default=None, nargs='+', choices=['ibmai_repo', 'cuda_drv_repo', 'wmla_license', 'spectrum_dli', 'spectrum_conductor', 'dependency_repo', 'conda_content_repo', 'conda_free_repo', 'conda_main_repo', 'pypi_repo', 'epel_repo'], help='Runs the software phase with specified step')
parser_software.add_argument('--proc-family', default='p8', nargs='+', choices=['p8', 'p9', 'x86_64'], help='Set the target processor family')
parser_software.add_argument('--engr-mode', default=False, action='store_true', help='Runs engineering mode function')
parser_software.add_argument('--public', default=None, action='store_true', help='Use public access, default is to use --prep to install private repos')
parser_software.add_argument('--run_ansible_task', default=None, nargs='+', help='Runs ansbile task from specified software directory')
parser_utils.set_defaults(utils=True)
parser_utils.add_argument('--scan-pxe-network', action='store_true', help='Ping all addresses in PXE subnet')
parser_utils.add_argument('--scan-ipmi-network', action='store_true', help='Ping all addresses in IPMI subnet')
parser_utils.add_argument('config_file_name', nargs='?', default='config.yml', metavar='CONFIG-FILE-NAME', help='Config file name. Specify relative to the power-up directory.')
parser_utils.add_argument('--download-install-deps', action='store_true', help='Download install dependencies into local repo')
parser_utils.add_argument('--bundle-from', nargs=1, help='Extract bundled repos and software directory')
parser_utils.add_argument('--bundle-to', nargs=1, help='Bundle repos and software directory')
if parser_args:
return (parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_software, parser_osinstall, parser_utils)
return parser<|docstring|>Get 'pup' command arguments<|endoftext|> |
c45c62f90ef4da3c027d2272d535bc76de5ec4ed922ed22cad174b275f09606d | def get_parsed_args():
"Get parsed 'pup' command arguments"
(parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_osinstall, parser_software, parser_utils) = get_args(parser_args=True)
args = parser.parse_args()
if (hasattr(args, 'osinstall') and (args.log_level_print[0] != 'debug')):
args.log_level_print = ['nolog']
try:
if args.setup:
_check_setup(args, parser_setup)
except AttributeError:
pass
try:
if args.config:
_check_config(args, parser_config)
except AttributeError:
pass
try:
if args.validate:
_check_validate(args, parser_validate)
except AttributeError:
pass
try:
if args.deploy:
_check_deploy(args, parser_deploy)
except AttributeError:
pass
try:
if args.post_deploy:
_check_post_deploy(args, parser_post_deploy)
except AttributeError:
pass
try:
if args.software:
_check_software(args, parser_software)
except AttributeError:
pass
try:
if args.osinstall:
_check_osinstall(args, parser_osinstall)
except AttributeError:
pass
try:
if args.utils:
_check_utils(args, parser_utils)
except AttributeError:
pass
return args | Get parsed 'pup' command arguments | scripts/python/lib/argparse_gen.py | get_parsed_args | Bhaskers-Blu-Org1/power-up | 8 | python | def get_parsed_args():
(parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_osinstall, parser_software, parser_utils) = get_args(parser_args=True)
args = parser.parse_args()
if (hasattr(args, 'osinstall') and (args.log_level_print[0] != 'debug')):
args.log_level_print = ['nolog']
try:
if args.setup:
_check_setup(args, parser_setup)
except AttributeError:
pass
try:
if args.config:
_check_config(args, parser_config)
except AttributeError:
pass
try:
if args.validate:
_check_validate(args, parser_validate)
except AttributeError:
pass
try:
if args.deploy:
_check_deploy(args, parser_deploy)
except AttributeError:
pass
try:
if args.post_deploy:
_check_post_deploy(args, parser_post_deploy)
except AttributeError:
pass
try:
if args.software:
_check_software(args, parser_software)
except AttributeError:
pass
try:
if args.osinstall:
_check_osinstall(args, parser_osinstall)
except AttributeError:
pass
try:
if args.utils:
_check_utils(args, parser_utils)
except AttributeError:
pass
return args | def get_parsed_args():
(parser, parser_setup, parser_config, parser_validate, parser_deploy, parser_post_deploy, parser_osinstall, parser_software, parser_utils) = get_args(parser_args=True)
args = parser.parse_args()
if (hasattr(args, 'osinstall') and (args.log_level_print[0] != 'debug')):
args.log_level_print = ['nolog']
try:
if args.setup:
_check_setup(args, parser_setup)
except AttributeError:
pass
try:
if args.config:
_check_config(args, parser_config)
except AttributeError:
pass
try:
if args.validate:
_check_validate(args, parser_validate)
except AttributeError:
pass
try:
if args.deploy:
_check_deploy(args, parser_deploy)
except AttributeError:
pass
try:
if args.post_deploy:
_check_post_deploy(args, parser_post_deploy)
except AttributeError:
pass
try:
if args.software:
_check_software(args, parser_software)
except AttributeError:
pass
try:
if args.osinstall:
_check_osinstall(args, parser_osinstall)
except AttributeError:
pass
try:
if args.utils:
_check_utils(args, parser_utils)
except AttributeError:
pass
return args<|docstring|>Get parsed 'pup' command arguments<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.