function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def updateb(event=None):
global position
position -= nperscreen
position = max(0,position)
position = min(nplots-nperscreen, position)
plotparslider.set_val(position) | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def updaten(event=None):
global position
position += nperscreen
position = max(0,position)
position = min(nplots-nperscreen, position)
plotparslider.set_val(position) | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def update(tmp=0):
global position, plotparslider
position = tmp
position = max(0,position)
position = min(nplots-nperscreen, position)
t = tic()
for i,ax in enumerate(plotparsaxs):
ax.cla()
for item in ax.get_xticklabels() + ax.get_yticklabels(): ... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def showplots(plots=None, figsize=None):
'''
This function can be used to show plots (in separate figure windows, independently
of generating them. | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def loadplot(filename=None):
'''
Load a plot from a file and reanimate it. | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def makenewfigure(**figargs):
''' PyQt-specific function for maximizing the current figure '''
global scrwid, scrhei | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def closegui(event=None):
''' Close all GUI windows '''
global panelfig, plotfig
try: close(plotfig)
except: pass
try: close(panelfig)
except: pass
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def clearselections(event=None):
global check
for box in range(len(check.lines)):
for i in [0,1]: check.lines[box][i].set_visible(False)
updateplots()
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def advancedselections(event=None):
''' Toggle advance doptions '''
global check, checkboxes, updatebutton, clearbutton, defaultsbutton, advancedbutton, closebutton, plotfig, panelfig, results, plotargs, globaladvanced
globaladvanced = not(globaladvanced) # Toggle
try: close(plotfig) # These work bet... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def zoomplots(event=None, ratio=1.0):
''' Zoom in or out '''
global plotfig
for ax in plotfig.axes:
axpos = ax.get_position()
x0 = axpos.x0
x1 = axpos.x1
y0 = axpos.y0
y1 = axpos.y1
xdiff = x1-x0
ydiff = y1-y0
xchange = xdiff*(1-ratio)/2.0
... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def zoomout(event=None):
''' Zoom out of plots '''
zoomplots(event=event, ratio=0.9)
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def updateplots(event=None, tmpresults=None, **kwargs):
''' Close current window if it exists and open a new one based on user selections '''
global plotfig, check, checkboxes, results, plotargs
if tmpresults is not None: results = tmpresults | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def resetbudget():
''' Replace current displayed budget with default from portfolio '''
global globalportfolio, objectiveinputs
totalbudget = 0
for project in globalportfolio.projects.values():
totalbudget += sum(project.progsets[0].getdefaultbudget().values())
objectiveinputs['budget'].setT... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_loadproj():
''' Helper function to load a project, since used more than once '''
filepath = pyqt.QFileDialog.getOpenFileName(caption='Choose project file', filter='*'+prjext)
project = None
if filepath:
try: project = loadproj(filepath, verbose=0)
except Exception as E: print('Co... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_makesheet():
''' Create a geospatial spreadsheet template based on a project file ''' | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_makeproj():
''' Create a series of project files based on a seed file and a geospatial spreadsheet '''
project = gui_loadproj()
spreadsheetpath = pyqt.QFileDialog.getOpenFileName(caption='Choose geospatial spreadsheet', filter='*.xlsx')
destination = pyqt.QFileDialog.getExistingDirectory(caption... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_addproj():
''' Add a project -- same as creating a portfolio except don't overwrite '''
gui_create(doadd=True)
resetbudget() # And reset the budget
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_rungeo():
''' Actually run geospatial analysis!!! '''
global globalportfolio, globalobjectives, objectiveinputs
starttime = time()
if globalobjectives is None:
globalobjectives = defaultobjectives()
globalobjectives['budget'] = 0.0 # Reset
for key in objectiveinputs.keys():
... | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_plotgeo():
''' Actually plot geospatial analysis!!! '''
global globalportfolio
if globalportfolio is None:
warning('Please load a portfolio first')
return None
globalportfolio.plotBOCs(deriv=False)
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def gui_saveport():
''' Save the current portfolio '''
global globalportfolio
filepath = pyqt.QFileDialog.getSaveFileName(caption='Save portfolio file', filter='*'+prtext)
saveobj(filepath, globalportfolio)
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def geogui():
'''
Open the GUI for doing geospatial analysis. | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def updateprojectinfo():
global globalportfolio, projectslistbox, projectinfobox
ind = projectslistbox.currentRow()
project = globalportfolio.projects[ind]
projectinfobox.setText(repr(project))
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def removeproject():
global projectslistbox, projectinfobox, globalportfolio
ind = projectslistbox.currentRow()
globalportfolio.projects.pop(globalportfolio.projects.keys()[ind]) # Remove from portfolio
projectslistbox.takeItem(ind) # Remove from list
return None | optimamodel/Optima | [
7,
1,
7,
8,
1406655820
] |
def __init__(self, file, **settings):
self.file = file
self.settings = {"profile_set": None, "material": None}
for key, value in settings.items():
self.settings[key] = value | IfcOpenShell/IfcOpenShell | [
1191,
546,
1191,
377,
1439197394
] |
def test_recent_filtering(self):
def _get_recent(data):
recent = set()
for link in data['recent_links']:
recent.add(link['url'])
return recent
username = 'none'
req = get_request_with_user(username)
user = get_user_model(req)
... | uw-it-aca/myuw | [
13,
6,
13,
3,
1417029795
] |
def test_hidden_link(self):
req = get_request_with_user('none')
url = "http://s.ss.edu"
link = add_hidden_link(req, url)
self.assertEquals(link.url, url)
# second time
link1 = add_hidden_link(req, url)
self.assertEquals(link.pk, link1.pk)
self.assertIsNot... | uw-it-aca/myuw | [
13,
6,
13,
3,
1417029795
] |
def test_delete_custom_link(self):
username = 'none'
req = get_request_with_user(username)
url = "http://s.ss.edu"
link = add_custom_link(req, url)
self.assertIsNotNone(delete_custom_link(req, link.pk))
# second time
self.assertIsNone(delete_custom_link(req, link.... | uw-it-aca/myuw | [
13,
6,
13,
3,
1417029795
] |
def test_get_quicklink_data(self):
data = {
"affiliation": "student",
"url": "http://iss1.washington.edu/",
"label": "ISS1",
"campus": "seattle",
"pce": False,
"affiliation": "{intl_stud: True}",
}
plink = PopularLink.ob... | uw-it-aca/myuw | [
13,
6,
13,
3,
1417029795
] |
def test_tac_quicklinks(self):
username = "tacgrad"
req = get_request_with_user(username)
tac_qls = get_quicklink_data(req)
self.assertEqual(tac_qls['default_links'][0]['label'],
"International Student and Scholar Services (ISSS)") | uw-it-aca/myuw | [
13,
6,
13,
3,
1417029795
] |
def splice(act, **info):
'''
Form a splice event from a given act name and info.
Args:
act (str): The name of the action.
**info: Additional information about the event.
Example:
splice = splice('add:node', form='inet:ipv4', valu=0)
self.fire(splice)
Notes:
... | vivisect/synapse | [
280,
64,
280,
16,
1433978981
] |
def __init__(self, input_graph, output_node_names, perchannel,
start_node_name):
super(FuseNodeStartWithPad,
self).__init__(input_graph, output_node_names, perchannel,
start_node_name) | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
def _apply_pad_conv_fusion(self):
for _, value in self.node_name_mapping.items():
if value.node.op in ("Pad") and self.node_name_mapping[
value.
output[0]].node.op == "Conv2D" and self._find_relu_node(
value.node):
paddi... | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
def __init__(self, input_tensor, dilation_factor):
assert (layer_util.check_spatial_dims(
input_tensor, lambda x: x % dilation_factor == 0))
self._tensor = input_tensor
self.dilation_factor = dilation_factor
# parameters to transform input tensor
self.spatial_rank = l... | NifTK/NiftyNet | [
1325,
408,
1325,
103,
1504079743
] |
def __exit__(self, *args):
if self.dilation_factor > 1:
self._tensor = tf.batch_to_space_nd(self._tensor,
self.block_shape,
self.zero_paddings,
name='de-dil... | NifTK/NiftyNet | [
1325,
408,
1325,
103,
1504079743
] |
def tensor(self):
return self._tensor | NifTK/NiftyNet | [
1325,
408,
1325,
103,
1504079743
] |
def emnist_classes():
return (
[str(i) for i in range(10)]
+ [chr(i + ord('A')) for i in range(26)]
+ [chr(i + ord('a')) for i in range(26)]
) | e2crawfo/dps | [
1,
2,
1,
3,
1491848389
] |
def _validate_emnist(path):
if not os.path.isdir(path):
return False
return set(os.listdir(path)) == set(emnist_filenames) | e2crawfo/dps | [
1,
2,
1,
3,
1491848389
] |
def _emnist_load_helper(path_img, path_lbl):
with gzip.open(path_lbl, 'rb') as file:
magic, size = struct.unpack(">II", file.read(8))
if magic != 2049:
raise ValueError('Magic number mismatch, expected 2049,'
'got {}'.format(magic))
labels = array("B... | e2crawfo/dps | [
1,
2,
1,
3,
1491848389
] |
def maybe_download_emnist(data_dir, quiet=0, shape=None):
"""
Download emnist data if it hasn't already been downloaded. Do some
post-processing to put it in a more useful format. End result is a directory
called `emnist-byclass` which contains a separate pklz file for each emnist
class.
Pixel ... | e2crawfo/dps | [
1,
2,
1,
3,
1491848389
] |
def __init__(self):
super(ConnectionEventHandler, self).__init__() | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def connection_remote_closed(self, connection, pn_condition):
"""Peer has closed its end of the connection."""
LOG.debug("connection_remote_closed condition=%s", pn_condition)
connection.close() | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def __init__(self, count):
self._count = count
self._msg = Message()
self.calls = 0
self.total_ack_latency = 0.0
self.stop_time = None
self.start_time = None | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def _send_message(self, link):
now = time.time()
self._msg.body = {'tx-timestamp': now}
self._last_send = now
link.send(self._msg, self) | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def sender_remote_closed(self, sender_link, pn_condition):
LOG.debug("Sender peer_closed condition=%s", pn_condition)
sender_link.close() | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def __init__(self, count, capacity):
self._count = count
self._capacity = capacity
self._msg = Message()
self.receives = 0
self.tx_total_latency = 0.0 | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def receiver_remote_closed(self, receiver_link, pn_condition):
"""Peer has closed its end of the link."""
LOG.debug("receiver_remote_closed condition=%s", pn_condition)
receiver_link.close() | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def message_received(self, receiver, message, handle):
now = time.time()
receiver.message_accepted(handle)
self.tx_total_latency += now - message.body['tx-timestamp']
self.receives += 1
if self._count:
self._count -= 1
if self._count == 0:
... | kgiusti/pyngus | [
5,
3,
5,
7,
1386944542
] |
def zookeeper_server(configure_security):
service_options = {
"service": {"name": config.ZOOKEEPER_SERVICE_NAME, "virtual_network_enabled": True}
}
zk_account = "test-zookeeper-service-account"
zk_secret = "test-zookeeper-secret"
try:
sdk_install.uninstall(config.ZOOKEEPER_PACKAGE_N... | mesosphere/dcos-kafka-service | [
31,
34,
31,
1,
1453069144
] |
def kafka_server(zookeeper_server):
try:
# Get the zookeeper DNS values
zookeeper_dns = sdk_cmd.svc_cli(
zookeeper_server["package_name"],
zookeeper_server["service"]["name"],
"endpoint clientport",
parse_json=True,
)[1]["dns"]
sdk_in... | mesosphere/dcos-kafka-service | [
31,
34,
31,
1,
1453069144
] |
def fetch_topic(kafka_server: dict):
_, topic_list, _ = sdk_cmd.svc_cli(
config.PACKAGE_NAME, kafka_server["service"]["name"], "topic list", parse_json=True
)
return topic_list | mesosphere/dcos-kafka-service | [
31,
34,
31,
1,
1453069144
] |
def __init__(self, **kwargs):
super(OrderNamespace, self).__init__(**kwargs) | henrysher/opslib | [
2,
2,
2,
1,
1385896350
] |
def add_arguments(group, args):
"""
Add Arguments to CLI
"""
for kkk, vvv in args.iteritems():
if 'type' in vvv and vvv['type'] in type_map:
vvv['type'] = type_map[vvv['type']]
if 'help' in vvv and not vvv['help']:
vvv['help'] = argparse.SUPPRESS
changed =... | henrysher/opslib | [
2,
2,
2,
1,
1385896350
] |
def parse_args(args):
"""
Create the Command Line Interface
:type args: dict
:param args: describes the command structure for the CLI
"""
parser = argparse.ArgumentParser(description=args.get('Description', ''))
for k, v in args.iteritems():
if k == 'Subparsers':
parser ... | henrysher/opslib | [
2,
2,
2,
1,
1385896350
] |
def cancel_reserved_instances_listing(self):
if self.is_not_dryrun("CancelReservedInstances"):
raise NotImplementedError(
"ReservedInstances.cancel_reserved_instances_listing is not yet implemented"
) | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def describe_reserved_instances(self):
raise NotImplementedError(
"ReservedInstances.describe_reserved_instances is not yet implemented"
) | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def describe_reserved_instances_offerings(self):
raise NotImplementedError(
"ReservedInstances.describe_reserved_instances_offerings is not yet implemented"
) | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def __init__(self, notification):
self._device_id = notification[self.DEVICE_ID_KEY]
self._id = notification[self.ID_KEY]
self._notification = notification[self.NOTIFICATION_KEY]
self._parameters = notification[self.PARAMETERS_KEY]
self._timestamp = notification[self.TIMESTAMP_KE... | devicehive/devicehive-python | [
30,
22,
30,
3,
1354125752
] |
def device_id(self):
return self._device_id | devicehive/devicehive-python | [
30,
22,
30,
3,
1354125752
] |
def id(self):
return self._id | devicehive/devicehive-python | [
30,
22,
30,
3,
1354125752
] |
def notification(self):
return self._notification | devicehive/devicehive-python | [
30,
22,
30,
3,
1354125752
] |
def parameters(self):
return self._parameters | devicehive/devicehive-python | [
30,
22,
30,
3,
1354125752
] |
def __init__(self, col_name, col_type):
self.name = col_name
self.type = col_type | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def setUp(self):
self.kwargs = dict(
table='table',
partition=dict(col='col', value='value'),
metastore_conn_id='metastore_conn_id',
presto_conn_id='presto_conn_id',
mysql_conn_id='mysql_conn_id',
task_id='test_hive_stats_collection_operato... | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_get_default_exprs_excluded_cols(self):
col = 'excluded_col'
self.kwargs.update(dict(excluded_columns=[col]))
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, None)
assert default_exprs == {} | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_get_default_exprs_boolean(self):
col = 'col'
col_type = 'boolean'
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, col_type)
assert default_exprs == {
(col, 'false'): f'SUM(CASE WHEN NOT {col} THEN 1 ELSE 0 END)',
(col, ... | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_execute(self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollect... | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_execute_with_assignment_func(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def assignment_func(col, _):
return {(col, 'test'): f'TEST({col})'} | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_execute_with_assignment_func_no_return_value(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def assignment_func(_, __):
pass | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_execute_no_query_results(self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
mock_presto_hook.return_value.get_first.return_val... | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def test_execute_delete_previous_runs_rows(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps | apache/incubator-airflow | [
29418,
12032,
29418,
869,
1428948298
] |
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--power", required=True, default=None,
choices=["on", "off", "reset", "cycle"],
help="Control power state of all overcloud nodes")
args = parser.parse_args()
os_auth_url, os_tenant_name, ... | dsp-jetpack/JetPack | [
28,
63,
28,
1,
1509550389
] |
def __init__(self):
"""Initialise the object."""
# Setting Host Test Logger instance
ht_loggers = {
"BasePlugin": HtrunLogger("PLGN"),
"CopyMethod": HtrunLogger("COPY"),
"ResetMethod": HtrunLogger("REST"),
}
self.plugin_logger = ht_loggers.get(... | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def setup(self, *args, **kwargs):
"""Configure plugin.
This function should be called before plugin execute() method is used.
"""
return False | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def is_os_supported(self, os_name=None):
"""Check if the OS is supported by this plugin.
In some cases a plugin will not work under a particular OS. Usually because the
command line tool used to implement the plugin functionality is not available.
Args:
os_name: String desc... | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def print_plugin_error(self, text):
"""Print error messages to the console.
Args:
text: Text to print.
"""
self.plugin_logger.prn_err(text)
return False | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def print_plugin_char(self, char):
"""Print a char to stdout."""
stdout.write(char)
stdout.flush()
return True | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def check_serial_port_ready(self, serial_port, target_id=None, timeout=60):
"""Check and update serial port name information for DUT.
If no target_id is specified return the old serial port name.
Args:
serial_port: Current serial port name.
target_id: Target ID of a dev... | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def run_command(self, cmd, shell=True, stdin=None):
"""Run a shell command as a subprocess.
Prints 'cmd' return code if execution failed.
Args:
cmd: Command to execute.
shell: True if shell command should be executed (eg. ls, ps).
stdin: A custom stdin for t... | ARMmbed/greentea | [
28,
45,
28,
2,
1418315948
] |
def isScalar(v, val=None):
"""Check if v is scalar, i.e. int, float or complex.
Optional compare with val.
Examples
--------
>>> import pygimli as pg
>>> print(pg.isScalar(0))
True
>>> print(pg.isScalar(1.0))
True
>>> print(pg.isScalar(1.0, 0.0))
False
>>> print(pg.isSc... | gimli-org/gimli | [
257,
109,
257,
13,
1378329047
] |
def isComplex(vals):
"""Check numpy or pg.Vector if have complex data type"""
if isScalar(vals):
if isinstance(vals, (np.complex128, complex)):
return True
elif isArray(vals):
return isComplex(vals[0])
return False | gimli-org/gimli | [
257,
109,
257,
13,
1378329047
] |
def isR3Array(v, N=None):
"""Check if v is an array of size(N,3), a R3Vector or a list of pg.Pos.
Examples
--------
>>> import pygimli as pg
>>> print(pg.isR3Array([[0.0, 0.0, 1.], [1.0, 0.0, 1.]]))
True
>>> print(pg.isR3Array(np.ones((33, 3)), N=33))
True
>>> print(pg.isR3Array(pg.... | gimli-org/gimli | [
257,
109,
257,
13,
1378329047
] |
def construct_params_from_message(message: str) -> dict:
message_type = 'tagged_message' if '@[' in message else 'message'
return {
message_type: message
} | box/box-python-sdk | [
375,
216,
375,
21,
1423182655
] |
def reply(self, message: str) -> 'Comment':
"""
Add a reply to the comment.
:param message:
The content of the reply comment.
"""
url = self.get_type_url()
data = self.construct_params_from_message(message)
data['item'] = {
'type': 'commen... | box/box-python-sdk | [
375,
216,
375,
21,
1423182655
] |
def __init__(self, response):
"""Construct an API response from a Requests response
:param response: a ``requests`` library response
"""
super(APIResponse, self).__init__()
self.status = response.status_code
self.content = response.content
if self.content:
... | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def __init__(self, message=None, response=None):
self.response = response
if not message:
message = 'Unspecified error'
if response:
_status = response.status_code
_body = response.content
message = ('%(message)s\nStatus Code: %(_status)s\n'
... | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def __init__(self, response=None, message=None):
if not message:
message = "Authentication error"
super(OpenStackApiAuthenticationException, self).__init__(message,
response) | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def __init__(self, response=None, message=None):
if not message:
message = "Authorization error"
super(OpenStackApiAuthorizationException, self).__init__(message,
response) | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def __init__(self, response=None, message=None):
if not message:
message = "Item not found"
super(OpenStackApiNotFoundException, self).__init__(message, response) | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def __init__(self, auth_user, auth_key, auth_uri,
project_id=None):
super(TestOpenStackClient, self).__init__()
self.auth_result = None
self.auth_user = auth_user
self.auth_key = auth_key
self.auth_uri = auth_uri
if project_id is None:
self.pr... | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def _authenticate(self):
if self.auth_result:
return self.auth_result
auth_uri = self.auth_uri
headers = {'X-Auth-User': self.auth_user,
'X-Auth-Key': self.auth_key,
'X-Auth-Project-Id': self.project_id}
response = self.request(auth_uri,... | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def _decode_json(self, response):
resp = APIResponse(status=response.status_code)
if response.content:
resp.body = jsonutils.loads(response.content)
return resp | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def api_post(self, relative_uri, body, **kwargs):
kwargs['method'] = 'POST'
if body:
headers = kwargs.setdefault('headers', {})
headers['Content-Type'] = 'application/json'
kwargs['body'] = jsonutils.dumps(body)
kwargs.setdefault('check_response_status', [200... | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def api_delete(self, relative_uri, **kwargs):
kwargs['method'] = 'DELETE'
kwargs.setdefault('check_response_status', [200, 202, 204])
return APIResponse(self.api_request(relative_uri, **kwargs)) | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def get_server(self, server_id):
return self.api_get('/servers/%s' % server_id).body['server'] | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def post_server(self, server):
response = self.api_post('/servers', server).body
if 'reservation_id' in response:
return response
else:
return response['server'] | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def post_server_action(self, server_id, data):
return self.api_post('/servers/%s/action' % server_id, data).body | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def get_image(self, image_id):
return self.api_get('/images/%s' % image_id).body['image'] | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
def post_image(self, image):
return self.api_post('/images', image).body['image'] | cernops/nova | [
5,
2,
5,
2,
1418819480
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.