_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q267300 | add_new_message | test | def add_new_message():
"""
Add new java messages to ignore from user text file. It first reads in the new java ignored messages
from the user text file and generate a dict structure to out of the new java ignored messages. This
is achieved by function extract_message_to_dict. Next, new java messages will be added to the original
ignored java messages dict g_ok_java_messages. Again, this is achieved by function update_message_dict.
:return: none
"""
global g_new_messages_to_exclude # filename containing text file from user containing new java ignored messages
global g_dict_changed # True if new ignored java messages are added.
new_message_dict = extract_message_to_dict(g_new_messages_to_exclude)
if new_message_dict:
g_dict_changed = True
update_message_dict(new_message_dict,1) | python | {
"resource": ""
} |
q267301 | update_message_dict | test | def update_message_dict(message_dict,action):
"""
Update the g_ok_java_messages dict structure by
1. add the new java ignored messages stored in message_dict if action == 1
2. remove the java ignored messages stired in message_dict if action == 2.
Parameters
----------
message_dict : Python dict
key: unit test name or "general"
value: list of java messages that are to be ignored if they are found when running the test stored as the key. If
the key is "general", the list of java messages are to be ignored when running all tests.
action : int
if 1: add java ignored messages stored in message_dict to g_ok_java_messages dict;
if 2: remove java ignored messages stored in message_dict from g_ok_java_messages dict.
:return: none
"""
global g_ok_java_messages
allKeys = g_ok_java_messages.keys()
for key in message_dict.keys():
if key in allKeys: # key already exists, just add to it
for message in message_dict[key]:
if action == 1:
if message not in g_ok_java_messages[key]:
g_ok_java_messages[key].append(message)
if action == 2:
if message in g_ok_java_messages[key]:
g_ok_java_messages[key].remove(message)
else: # new key here. Can only add and cannot remove
if action == 1:
g_ok_java_messages[key] = message_dict[key] | python | {
"resource": ""
} |
q267302 | extract_message_to_dict | test | def extract_message_to_dict(filename):
"""
Read in a text file that java messages to be ignored and generate a dictionary structure out of
it with key and value pairs. The keys are test names and the values are lists of java message
strings associated with that test name where we are either going to add to the existing java messages
to ignore or remove them from g_ok_java_messages.
Parameters
----------
filename : Str
filename that contains ignored java messages. The text file shall contain something like this:
keyName = general
Message = nfolds: nfolds cannot be larger than the number of rows (406).
KeyName = pyunit_cv_cars_gbm.py
Message = Caught exception: Illegal argument(s) for GBM model: GBM_model_python_1452503348770_2586. \
Details: ERRR on field: _nfolds: nfolds must be either 0 or >1.
...
:return:
message_dict : dict
contains java message to be ignored with key as unit test name or "general" and values as list of ignored java
messages.
"""
message_dict = {}
if os.path.isfile(filename):
# open file to read in new exclude messages if it exists
with open(filename,'r') as wfile:
key = ""
val = ""
startMess = False
while 1:
each_line = wfile.readline()
if not each_line: # reached EOF
if startMess:
add_to_dict(val.strip(),key,message_dict)
break
# found a test name or general with values to follow
if "keyname" in each_line.lower(): # name of test file or the word "general"
temp_strings = each_line.strip().split('=')
if (len(temp_strings) > 1): # make sure the line is formatted sort of correctly
if startMess: # this is the start of a new key/value pair
add_to_dict(val.strip(),key,message_dict)
val = ""
key = temp_strings[1].strip()
startMess = False
if (len(each_line) > 1) and startMess:
val += each_line
if "ignoredmessage" in each_line.lower():
startMess = True # start of a Java message.
temp_mess = each_line.split('=')
if (len(temp_mess) > 1):
val = temp_mess[1]
return message_dict | python | {
"resource": ""
} |
q267303 | save_dict | test | def save_dict():
"""
Save the ignored java message dict stored in g_ok_java_messages into a pickle file for future use.
:return: none
"""
global g_ok_java_messages
global g_save_java_message_filename
global g_dict_changed
if g_dict_changed:
with open(g_save_java_message_filename,'wb') as ofile:
pickle.dump(g_ok_java_messages,ofile) | python | {
"resource": ""
} |
q267304 | print_dict | test | def print_dict():
"""
Write the java ignored messages in g_ok_java_messages into a text file for humans to read.
:return: none
"""
global g_ok_java_messages
global g_java_messages_to_ignore_text_filename
allKeys = sorted(g_ok_java_messages.keys())
with open(g_java_messages_to_ignore_text_filename,'w') as ofile:
for key in allKeys:
for mess in g_ok_java_messages[key]:
ofile.write('KeyName: '+key+'\n')
ofile.write('IgnoredMessage: '+mess+'\n')
print('KeyName: ',key)
print('IgnoredMessage: ',g_ok_java_messages[key])
print('\n') | python | {
"resource": ""
} |
q267305 | parse_args | test | def parse_args(argv):
"""
Parse user inputs and set the corresponing global variables to perform the
necessary tasks.
Parameters
----------
argv : string array
contains flags and input options from users
:return:
"""
global g_new_messages_to_exclude
global g_old_messages_to_remove
global g_load_java_message_filename
global g_save_java_message_filename
global g_print_java_messages
if len(argv) < 2: # print out help menu if user did not enter any arguments.
usage()
i = 1
while (i < len(argv)):
s = argv[i]
if (s == "--inputfileadd"): # input text file where new java messages are stored
i += 1
if (i > len(argv)):
usage()
g_new_messages_to_exclude = argv[i]
elif (s == "--inputfilerm"): # input text file containing java messages to be removed from the ignored list
i += 1
if (i > len(argv)):
usage()
g_old_messages_to_remove = argv[i]
elif (s == "--loadjavamessage"): # load previously saved java message pickle file from file other than
i += 1 # the default one before performing update
if i > len(argv):
usage()
g_load_java_message_filename = argv[i]
elif (s == "--savejavamessage"): # save updated java message in this file instead of default file
i += 1
if (i > len(argv)):
usage()
g_save_java_message_filename = argv[i]
elif (s == '--printjavamessage'): # will print java message out to console and save in a text file
i += 1
g_print_java_messages = True
g_load_java_message_filename = argv[i]
elif (s == '--help'): # print help menu and exit
usage()
else:
unknown_arg(s)
i += 1 | python | {
"resource": ""
} |
q267306 | usage | test | def usage():
"""
Illustrate what the various input flags are and the options should be.
:return: none
"""
global g_script_name # name of the script being run.
print("")
print("Usage: " + g_script_name + " [...options...]")
print("")
print(" --help print out this help menu and show all the valid flags and inputs.")
print("")
print(" --inputfileadd filename where the new java messages to ignore are stored in.")
print("")
print(" --inputfilerm filename where the java messages are removed from the ignored list.")
print("")
print(" --loadjavamessage filename pickle file that stores the dict structure containing java messages to include.")
print("")
print(" --savejavamessage filename pickle file that saves the final dict structure after update.")
print("")
print(" --printjavamessage filename print java ignored java messages stored in pickle file filenam onto console and save into a text file.")
print("")
sys.exit(1) | python | {
"resource": ""
} |
q267307 | locate_files | test | def locate_files(root_dir):
"""Find all python files in the given directory and all subfolders."""
all_files = []
root_dir = os.path.abspath(root_dir)
for dir_name, subdirs, files in os.walk(root_dir):
for f in files:
if f.endswith(".py"):
all_files.append(os.path.join(dir_name, f))
return all_files | python | {
"resource": ""
} |
q267308 | find_magic_in_file | test | def find_magic_in_file(filename):
"""
Search the file for any magic incantations.
:param filename: file to search
:returns: a tuple containing the spell and then maybe some extra words (or None if no magic present)
"""
with open(filename, "rt", encoding="utf-8") as f:
for line in f:
if line.startswith("#"):
comment = line[1:].strip()
if comment.startswith("~~~~* ") or comment.startswith("----* ") or comment.startswith("====* "):
spell = comment[5:].strip()
return tuple(spell.split())
else:
break
return None | python | {
"resource": ""
} |
q267309 | main | test | def main():
"""Executed when script is run as-is."""
# magic_files = {}
for filename in locate_files(ROOT_DIR):
print("Processing %s" % filename)
with open(filename, "rt") as f:
tokens = list(tokenize.generate_tokens(f.readline))
text1 = tokenize.untokenize(tokens)
ntokens = normalize_tokens(tokens)
text2 = tokenize.untokenize(ntokens)
assert text1 == text2 | python | {
"resource": ""
} |
q267310 | H2OMojoPipeline.transform | test | def transform(self, data, allow_timestamps=False):
"""
Transform H2OFrame using a MOJO Pipeline.
:param data: Frame to be transformed.
:param allow_timestamps: Allows datetime columns to be used directly with MOJO pipelines. It is recommended
to parse your datetime columns as Strings when using pipelines because pipelines can interpret certain datetime
formats in a different way. If your H2OFrame is parsed from a binary file format (eg. Parquet) instead of CSV
it is safe to turn this option on and use datetime columns directly.
:returns: A new H2OFrame.
"""
assert_is_type(data, H2OFrame)
assert_is_type(allow_timestamps, bool)
return H2OFrame._expr(ExprNode("mojo.pipeline.transform", self.pipeline_id[0], data, allow_timestamps)) | python | {
"resource": ""
} |
q267311 | summarizeFailedRuns | test | def summarizeFailedRuns():
"""
This function will look at the local directory and pick out files that have the correct start name and
summarize the results into one giant dict.
:return: None
"""
global g_summary_dict_all
onlyFiles = [x for x in listdir(g_test_root_dir) if isfile(join(g_test_root_dir, x))] # grab files
for f in onlyFiles:
for fileStart in g_file_start:
if (fileStart in f) and (os.path.getsize(f) > 10): # found the file containing failed tests
fFullPath = os.path.join(g_test_root_dir, f)
try:
temp_dict = json.load(open(fFullPath,'r'))
# scrape through temp_dict and see if we need to add the test to intermittents
for ind in range(len(temp_dict["TestName"])):
addFailedTests(g_summary_dict_all, temp_dict, ind)
except:
continue
break | python | {
"resource": ""
} |
q267312 | extractPrintSaveIntermittens | test | def extractPrintSaveIntermittens():
"""
This function will print out the intermittents onto the screen for casual viewing. It will also print out
where the giant summary dictionary is going to be stored.
:return: None
"""
# extract intermittents from collected failed tests
global g_summary_dict_intermittents
localtz = time.tzname[0]
for ind in range(len(g_summary_dict_all["TestName"])):
if g_summary_dict_all["TestInfo"][ind]["FailureCount"] >= g_threshold_failure:
addFailedTests(g_summary_dict_intermittents, g_summary_dict_all, ind)
# save dict in file
if len(g_summary_dict_intermittents["TestName"]) > 0:
json.dump(g_summary_dict_intermittents, open(g_summary_dict_name, 'w'))
with open(g_summary_csv_filename, 'w') as summaryFile:
for ind in range(len(g_summary_dict_intermittents["TestName"])):
testName = g_summary_dict_intermittents["TestName"][ind]
numberFailure = g_summary_dict_intermittents["TestInfo"][ind]["FailureCount"]
firstFailedTS = parser.parse(time.ctime(min(g_summary_dict_intermittents["TestInfo"][ind]["Timestamp"]))+
' '+localtz)
firstFailedStr = firstFailedTS.strftime("%a %b %d %H:%M:%S %Y %Z")
recentFail = parser.parse(time.ctime(max(g_summary_dict_intermittents["TestInfo"][ind]["Timestamp"]))+
' '+localtz)
recentFailStr = recentFail.strftime("%a %b %d %H:%M:%S %Y %Z")
eachTest = "{0}, {1}, {2}, {3}\n".format(testName, recentFailStr, numberFailure,
g_summary_dict_intermittents["TestInfo"][ind]["TestCategory"][0])
summaryFile.write(eachTest)
print("Intermittent: {0}, Last failed: {1}, Failed {2} times since "
"{3}".format(testName, recentFailStr, numberFailure, firstFailedStr)) | python | {
"resource": ""
} |
q267313 | H2OBinomialModelMetrics.plot | test | def plot(self, type="roc", server=False):
"""
Produce the desired metric plot.
:param type: the type of metric plot (currently, only ROC supported).
:param server: if True, generate plot inline using matplotlib's "Agg" backend.
:returns: None
"""
# TODO: add more types (i.e. cutoffs)
assert_is_type(type, "roc")
# check for matplotlib. exit if absent.
try:
imp.find_module('matplotlib')
import matplotlib
if server: matplotlib.use('Agg', warn=False)
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib is required for this function!")
return
if type == "roc":
plt.xlabel('False Positive Rate (FPR)')
plt.ylabel('True Positive Rate (TPR)')
plt.title('ROC Curve')
plt.text(0.5, 0.5, r'AUC={0:.4f}'.format(self._metric_json["AUC"]))
plt.plot(self.fprs, self.tprs, 'b--')
plt.axis([0, 1, 0, 1])
if not server: plt.show() | python | {
"resource": ""
} |
q267314 | H2OBinomialModelMetrics.confusion_matrix | test | def confusion_matrix(self, metrics=None, thresholds=None):
"""
Get the confusion matrix for the specified metric
:param metrics: A string (or list of strings) among metrics listed in :const:`max_metrics`. Defaults to 'f1'.
:param thresholds: A value (or list of values) between 0 and 1.
:returns: a list of ConfusionMatrix objects (if there are more than one to return), or a single ConfusionMatrix
(if there is only one).
"""
# make lists out of metrics and thresholds arguments
if metrics is None and thresholds is None:
metrics = ['f1']
if isinstance(metrics, list):
metrics_list = metrics
elif metrics is None:
metrics_list = []
else:
metrics_list = [metrics]
if isinstance(thresholds, list):
thresholds_list = thresholds
elif thresholds is None:
thresholds_list = []
else:
thresholds_list = [thresholds]
# error check the metrics_list and thresholds_list
assert_is_type(thresholds_list, [numeric])
assert_satisfies(thresholds_list, all(0 <= t <= 1 for t in thresholds_list))
if not all(m.lower() in H2OBinomialModelMetrics.max_metrics for m in metrics_list):
raise ValueError("The only allowable metrics are {}", ', '.join(H2OBinomialModelMetrics.max_metrics))
# make one big list that combines the thresholds and metric-thresholds
metrics_thresholds = [self.find_threshold_by_max_metric(m) for m in metrics_list]
for mt in metrics_thresholds:
thresholds_list.append(mt)
first_metrics_thresholds_offset = len(thresholds_list) - len(metrics_thresholds)
thresh2d = self._metric_json['thresholds_and_metric_scores']
actual_thresholds = [float(e[0]) for i, e in enumerate(thresh2d.cell_values)]
cms = []
for i, t in enumerate(thresholds_list):
idx = self.find_idx_by_threshold(t)
row = thresh2d.cell_values[idx]
tns = row[11]
fns = row[12]
fps = row[13]
tps = row[14]
p = tps + fns
n = tns + fps
c0 = n - fps
c1 = p - tps
if t in metrics_thresholds:
m = metrics_list[i - first_metrics_thresholds_offset]
table_header = "Confusion Matrix (Act/Pred) for max {} @ threshold = {}".format(m, actual_thresholds[idx])
else:
table_header = "Confusion Matrix (Act/Pred) @ threshold = {}".format(actual_thresholds[idx])
cms.append(ConfusionMatrix(cm=[[c0, fps], [c1, tps]], domains=self._metric_json['domain'],
table_header=table_header))
if len(cms) == 1:
return cms[0]
else:
return cms | python | {
"resource": ""
} |
q267315 | H2ODeepWaterEstimator.available | test | def available():
"""Returns True if a deep water model can be built, or False otherwise."""
builder_json = h2o.api("GET /3/ModelBuilders", data={"algo": "deepwater"})
visibility = builder_json["model_builders"]["deepwater"]["visibility"]
if visibility == "Experimental":
print("Cannot build a Deep Water model - no backend found.")
return False
else:
return True | python | {
"resource": ""
} |
q267316 | trim_data_back_to | test | def trim_data_back_to(monthToKeep):
"""
This method will remove data from the summary text file and the dictionary file for tests that occurs before
the number of months specified by monthToKeep.
:param monthToKeep:
:return:
"""
global g_failed_tests_info_dict
current_time = time.time() # unit in seconds
oldest_time_allowed = current_time - monthToKeep*30*24*3600 # in seconds
clean_up_failed_test_dict(oldest_time_allowed)
clean_up_summary_text(oldest_time_allowed) | python | {
"resource": ""
} |
q267317 | endpoint_groups | test | def endpoint_groups():
"""Return endpoints, grouped by the class which handles them."""
groups = defaultdict(list)
for e in endpoints():
groups[e["class_name"]].append(e)
return groups | python | {
"resource": ""
} |
q267318 | update_site_forward | test | def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "{{cookiecutter.domain_name}}",
"name": "{{cookiecutter.project_name}}",
},
) | python | {
"resource": ""
} |
q267319 | API.json_data | test | def json_data(self, data=None):
"""Adds the default_data to data and dumps it to a json."""
if data is None:
data = {}
data.update(self.default_data)
return json.dumps(data) | python | {
"resource": ""
} |
q267320 | comment_user | test | def comment_user(self, user_id, amount=None):
""" Comments last user_id's medias """
if not self.check_user(user_id, filter_closed_acc=True):
return False
self.logger.info("Going to comment user_%s's feed:" % user_id)
user_id = self.convert_to_user_id(user_id)
medias = self.get_user_medias(user_id, is_comment=True)
if not medias:
self.logger.info(
"None medias received: account is closed or medias have been filtered.")
return False
return self.comment_medias(medias[:amount]) | python | {
"resource": ""
} |
q267321 | get_credentials | test | def get_credentials(username=None):
"""Returns login and password stored in `secret.txt`."""
while not check_secret():
pass
while True:
try:
with open(SECRET_FILE, "r") as f:
lines = [line.strip().split(":", 2) for line in f.readlines()]
except ValueError:
msg = 'Problem with opening `{}`, will remove the file.'
raise Exception(msg.format(SECRET_FILE))
if username is not None:
for login, password in lines:
if login == username.strip():
return login, password
print("Which account do you want to use? (Type number)")
for ind, (login, password) in enumerate(lines):
print("%d: %s" % (ind + 1, login))
print("%d: %s" % (0, "add another account."))
print("%d: %s" % (-1, "delete all accounts."))
try:
ind = int(sys.stdin.readline())
if ind == 0:
add_credentials()
continue
elif ind == -1:
delete_credentials()
check_secret()
continue
elif 0 <= ind - 1 < len(lines):
return lines[ind - 1]
except Exception:
print("Wrong input, enter the number of the account to use.") | python | {
"resource": ""
} |
q267322 | like_user | test | def like_user(self, user_id, amount=None, filtration=True):
""" Likes last user_id's medias """
if filtration:
if not self.check_user(user_id):
return False
self.logger.info("Liking user_%s's feed:" % user_id)
user_id = self.convert_to_user_id(user_id)
medias = self.get_user_medias(user_id, filtration=filtration)
if not medias:
self.logger.info(
"None medias received: account is closed or medias have been filtered.")
return False
return self.like_medias(medias[:amount]) | python | {
"resource": ""
} |
q267323 | like_hashtag | test | def like_hashtag(self, hashtag, amount=None):
""" Likes last medias from hashtag """
self.logger.info("Going to like media with hashtag #%s." % hashtag)
medias = self.get_total_hashtag_medias(hashtag, amount)
return self.like_medias(medias) | python | {
"resource": ""
} |
q267324 | check_not_bot | test | def check_not_bot(self, user_id):
""" Filter bot from real users. """
self.small_delay()
user_id = self.convert_to_user_id(user_id)
if not user_id:
return False
if user_id in self.whitelist:
return True
if user_id in self.blacklist:
return False
user_info = self.get_user_info(user_id)
if not user_info:
return True # closed acc
skipped = self.skipped_file
if "following_count" in user_info and user_info["following_count"] > self.max_following_to_block:
msg = 'following_count > bot.max_following_to_block, skipping!'
self.console_print(msg, 'red')
skipped.append(user_id)
return False # massfollower
if search_stop_words_in_user(self, user_info):
msg = '`bot.search_stop_words_in_user` found in user, skipping!'
skipped.append(user_id)
return False
return True | python | {
"resource": ""
} |
q267325 | read_list_from_file | test | def read_list_from_file(file_path, quiet=False):
"""
Reads list from file. One line - one item.
Returns the list if file items.
"""
try:
if not check_if_file_exists(file_path, quiet=quiet):
return []
with codecs.open(file_path, "r", encoding="utf-8") as f:
content = f.readlines()
if sys.version_info[0] < 3:
content = [str(item.encode('utf8')) for item in content]
content = [item.strip() for item in content]
return [i for i in content if i]
except Exception as exception:
print(str(exception))
return [] | python | {
"resource": ""
} |
q267326 | Message.schedule | test | def schedule(self, schedule_time):
"""Add a specific enqueue time to the message.
:param schedule_time: The scheduled time to enqueue the message.
:type schedule_time: ~datetime.datetime
"""
if not self.properties.message_id:
self.properties.message_id = str(uuid.uuid4())
if not self.message.annotations:
self.message.annotations = {}
self.message.annotations[types.AMQPSymbol(self._x_OPT_SCHEDULED_ENQUEUE_TIME)] = schedule_time | python | {
"resource": ""
} |
q267327 | Message.defer | test | def defer(self):
"""Defer the message.
This message will remain in the queue but must be received
specifically by its sequence number in order to be processed.
:raises: ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
:raises: ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
:raises: ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
:raises: ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.
"""
self._is_live('defer')
try:
self.message.modify(True, True)
except Exception as e:
raise MessageSettleFailed("defer", e) | python | {
"resource": ""
} |
q267328 | VpnSitesConfigurationOperations.download | test | def download(
self, resource_group_name, virtual_wan_name, vpn_sites=None, output_blob_sas_url=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Gives the sas-url to download the configurations for vpn-sites in a
resource group.
:param resource_group_name: The resource group name.
:type resource_group_name: str
:param virtual_wan_name: The name of the VirtualWAN for which
configuration of all vpn-sites is needed.
:type virtual_wan_name: str
:param vpn_sites: List of resource-ids of the vpn-sites for which
config is to be downloaded.
:type vpn_sites:
list[~azure.mgmt.network.v2018_04_01.models.SubResource]
:param output_blob_sas_url: The sas-url to download the configurations
for vpn-sites
:type output_blob_sas_url: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises:
:class:`ErrorException<azure.mgmt.network.v2018_04_01.models.ErrorException>`
"""
raw_result = self._download_initial(
resource_group_name=resource_group_name,
virtual_wan_name=virtual_wan_name,
vpn_sites=vpn_sites,
output_blob_sas_url=output_blob_sas_url,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267329 | guess_service_info_from_path | test | def guess_service_info_from_path(spec_path):
"""Guess Python Autorest options based on the spec path.
Expected path:
specification/compute/resource-manager/readme.md
"""
spec_path = spec_path.lower()
spec_path = spec_path[spec_path.index("specification"):] # Might raise and it's ok
split_spec_path = spec_path.split("/")
rp_name = split_spec_path[1]
is_arm = split_spec_path[2] == "resource-manager"
return {
"rp_name": rp_name,
"is_arm": is_arm
} | python | {
"resource": ""
} |
q267330 | PowerShellOperations.update_command | test | def update_command(
self, resource_group_name, node_name, session, pssession, custom_headers=None, raw=False, polling=True, **operation_config):
"""Updates a running PowerShell command with more data.
:param resource_group_name: The resource group name uniquely
identifies the resource group within the user subscriptionId.
:type resource_group_name: str
:param node_name: The node name (256 characters maximum).
:type node_name: str
:param session: The sessionId from the user.
:type session: str
:param pssession: The PowerShell sessionId from the user.
:type pssession: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns
PowerShellCommandResults or
ClientRawResponse<PowerShellCommandResults> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.servermanager.models.PowerShellCommandResults]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.servermanager.models.PowerShellCommandResults]]
:raises:
:class:`ErrorException<azure.mgmt.servermanager.models.ErrorException>`
"""
raw_result = self._update_command_initial(
resource_group_name=resource_group_name,
node_name=node_name,
session=session,
pssession=pssession,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('PowerShellCommandResults', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267331 | ApplicationDefinitionsOperations.delete_by_id | test | def delete_by_id(
self, application_definition_id, custom_headers=None, raw=False, polling=True, **operation_config):
"""Deletes the managed application definition.
:param application_definition_id: The fully qualified ID of the
managed application definition, including the managed application name
and the managed application definition resource type. Use the format,
/subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applicationDefinitions/{applicationDefinition-name}
:type application_definition_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises:
:class:`ErrorResponseException<azure.mgmt.resource.managedapplications.models.ErrorResponseException>`
"""
raw_result = self._delete_by_id_initial(
application_definition_id=application_definition_id,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267332 | ApplicationDefinitionsOperations.create_or_update_by_id | test | def create_or_update_by_id(
self, application_definition_id, parameters, custom_headers=None, raw=False, polling=True, **operation_config):
"""Creates a new managed application definition.
:param application_definition_id: The fully qualified ID of the
managed application definition, including the managed application name
and the managed application definition resource type. Use the format,
/subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applicationDefinitions/{applicationDefinition-name}
:type application_definition_id: str
:param parameters: Parameters supplied to the create or update a
managed application definition.
:type parameters:
~azure.mgmt.resource.managedapplications.models.ApplicationDefinition
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns ApplicationDefinition
or ClientRawResponse<ApplicationDefinition> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]]
:raises:
:class:`ErrorResponseException<azure.mgmt.resource.managedapplications.models.ErrorResponseException>`
"""
raw_result = self._create_or_update_by_id_initial(
application_definition_id=application_definition_id,
parameters=parameters,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('ApplicationDefinition', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267333 | _HTTPClient.get_uri | test | def get_uri(self, request):
''' Return the target uri for the request.'''
protocol = request.protocol_override \
if request.protocol_override else self.protocol
protocol = protocol.lower()
port = HTTP_PORT if protocol == 'http' else HTTPS_PORT
return protocol + '://' + request.host + ':' + str(port) + request.path | python | {
"resource": ""
} |
q267334 | _HTTPClient.get_connection | test | def get_connection(self, request):
''' Create connection for the request. '''
protocol = request.protocol_override \
if request.protocol_override else self.protocol
protocol = protocol.lower()
target_host = request.host
# target_port = HTTP_PORT if protocol == 'http' else HTTPS_PORT
connection = _RequestsConnection(
target_host, protocol, self.request_session, self.timeout)
proxy_host = self.proxy_host
proxy_port = self.proxy_port
if self.proxy_host:
headers = None
if self.proxy_user and self.proxy_password:
auth = base64.b64encode("{0}:{1}".format(self.proxy_user, self.proxy_password).encode())
headers = {'Proxy-Authorization': 'Basic {0}'.format(auth.decode())}
connection.set_tunnel(proxy_host, int(proxy_port), headers)
return connection | python | {
"resource": ""
} |
q267335 | _HTTPClient.perform_request | test | def perform_request(self, request):
''' Sends request to cloud service server and return the response. '''
connection = self.get_connection(request)
try:
connection.putrequest(request.method, request.path)
self.send_request_headers(connection, request.headers)
self.send_request_body(connection, request.body)
if DEBUG_REQUESTS and request.body:
print('request:')
try:
print(request.body)
except: # pylint: disable=bare-except
pass
resp = connection.getresponse()
status = int(resp.status)
message = resp.reason
respheaders = resp.getheaders()
# for consistency across platforms, make header names lowercase
for i, value in enumerate(respheaders):
respheaders[i] = (value[0].lower(), value[1])
respbody = None
if resp.length is None:
respbody = resp.read()
elif resp.length > 0:
respbody = resp.read(resp.length)
if DEBUG_RESPONSES and respbody:
print('response:')
try:
print(respbody)
except: # pylint: disable=bare-except
pass
response = HTTPResponse(
status, resp.reason, respheaders, respbody)
if status == 307:
new_url = urlparse(dict(respheaders)['location'])
request.host = new_url.hostname
request.path = new_url.path
request.path, request.query = self._update_request_uri_query(request)
return self.perform_request(request)
if status >= 300:
raise HTTPError(status, message, respheaders, respbody)
return response
finally:
connection.close() | python | {
"resource": ""
} |
q267336 | ClustersOperations.execute_script_actions | test | def execute_script_actions(
self, resource_group_name, cluster_name, persist_on_success, script_actions=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Executes script actions on the specified HDInsight cluster.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param cluster_name: The name of the cluster.
:type cluster_name: str
:param persist_on_success: Gets or sets if the scripts needs to be
persisted.
:type persist_on_success: bool
:param script_actions: The list of run time script actions.
:type script_actions:
list[~azure.mgmt.hdinsight.models.RuntimeScriptAction]
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises:
:class:`ErrorResponseException<azure.mgmt.hdinsight.models.ErrorResponseException>`
"""
raw_result = self._execute_script_actions_initial(
resource_group_name=resource_group_name,
cluster_name=cluster_name,
persist_on_success=persist_on_success,
script_actions=script_actions,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267337 | FrontDoorManagementClient.check_front_door_name_availability | test | def check_front_door_name_availability(
self, name, type, custom_headers=None, raw=False, **operation_config):
"""Check the availability of a Front Door resource name.
:param name: The resource name to validate.
:type name: str
:param type: The type of the resource whose name is to be validated.
Possible values include: 'Microsoft.Network/frontDoors',
'Microsoft.Network/frontDoors/frontendEndpoints'
:type type: str or ~azure.mgmt.frontdoor.models.ResourceType
: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: CheckNameAvailabilityOutput or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.frontdoor.models.CheckNameAvailabilityOutput or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.mgmt.frontdoor.models.ErrorResponseException>`
"""
check_front_door_name_availability_input = models.CheckNameAvailabilityInput(name=name, type=type)
api_version = "2018-08-01"
# Construct URL
url = self.check_front_door_name_availability.metadata['url']
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
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')
# Construct body
body_content = self._serialize.body(check_front_door_name_availability_input, 'CheckNameAvailabilityInput')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CheckNameAvailabilityOutput', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267338 | VaultsOperations.purge_deleted | test | def purge_deleted(
self, vault_name, location, custom_headers=None, raw=False, polling=True, **operation_config):
"""Permanently deletes the specified vault. aka Purges the deleted Azure
key vault.
:param vault_name: The name of the soft-deleted vault.
:type vault_name: str
:param location: The location of the soft-deleted vault.
:type location: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._purge_deleted_initial(
vault_name=vault_name,
location=location,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267339 | HttpChallenge.get_authorization_server | test | def get_authorization_server(self):
""" Returns the URI for the authorization server if present, otherwise empty string. """
value = ''
for key in ['authorization_uri', 'authorization']:
value = self.get_value(key) or ''
if value:
break
return value | python | {
"resource": ""
} |
q267340 | HttpChallenge._validate_request_uri | test | def _validate_request_uri(self, uri):
""" Extracts the host authority from the given URI. """
if not uri:
raise ValueError('request_uri cannot be empty')
uri = parse.urlparse(uri)
if not uri.netloc:
raise ValueError('request_uri must be an absolute URI')
if uri.scheme.lower() not in ['http', 'https']:
raise ValueError('request_uri must be HTTP or HTTPS')
return uri.netloc | python | {
"resource": ""
} |
q267341 | get_cli_profile | test | def get_cli_profile():
"""Return a CLI profile class.
.. versionadded:: 1.1.6
:return: A CLI Profile
:rtype: azure.cli.core._profile.Profile
:raises: ImportError if azure-cli-core package is not available
"""
try:
from azure.cli.core._profile import Profile
from azure.cli.core._session import ACCOUNT
from azure.cli.core._environment import get_config_dir
except ImportError:
raise ImportError("You need to install 'azure-cli-core' to load CLI credentials")
azure_folder = get_config_dir()
ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
return Profile(storage=ACCOUNT) | python | {
"resource": ""
} |
q267342 | get_azure_cli_credentials | test | def get_azure_cli_credentials(resource=None, with_tenant=False):
"""Return Credentials and default SubscriptionID of current loaded profile of the CLI.
Credentials will be the "az login" command:
https://docs.microsoft.com/cli/azure/authenticate-azure-cli
Default subscription ID is either the only one you have, or you can define it:
https://docs.microsoft.com/cli/azure/manage-azure-subscriptions-azure-cli
.. versionadded:: 1.1.6
:param str resource: The alternative resource for credentials if not ARM (GraphRBac, etc.)
:param bool with_tenant: If True, return a three-tuple with last as tenant ID
:return: tuple of Credentials and SubscriptionID (and tenant ID if with_tenant)
:rtype: tuple
"""
profile = get_cli_profile()
cred, subscription_id, tenant_id = profile.get_login_credentials(resource=resource)
if with_tenant:
return cred, subscription_id, tenant_id
else:
return cred, subscription_id | python | {
"resource": ""
} |
q267343 | PredictionOperations.resolve | test | def resolve(
self, app_id, query, timezone_offset=None, verbose=None, staging=None, spell_check=None, bing_spell_check_subscription_key=None, log=None, custom_headers=None, raw=False, **operation_config):
"""Gets predictions for a given utterance, in the form of intents and
entities. The current maximum query size is 500 characters.
:param app_id: The LUIS application ID (Guid).
:type app_id: str
:param query: The utterance to predict.
:type query: str
:param timezone_offset: The timezone offset for the location of the
request.
:type timezone_offset: float
:param verbose: If true, return all intents instead of just the top
scoring intent.
:type verbose: bool
:param staging: Use the staging endpoint slot.
:type staging: bool
:param spell_check: Enable spell checking.
:type spell_check: bool
:param bing_spell_check_subscription_key: The subscription key to use
when enabling Bing spell check
:type bing_spell_check_subscription_key: str
:param log: Log query (default is true)
:type log: bool
: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: LuisResult or ClientRawResponse if raw=true
:rtype:
~azure.cognitiveservices.language.luis.runtime.models.LuisResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.language.luis.runtime.models.APIErrorException>`
"""
# Construct URL
url = self.resolve.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'appId': self._serialize.url("app_id", app_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if timezone_offset is not None:
query_parameters['timezoneOffset'] = self._serialize.query("timezone_offset", timezone_offset, 'float')
if verbose is not None:
query_parameters['verbose'] = self._serialize.query("verbose", verbose, 'bool')
if staging is not None:
query_parameters['staging'] = self._serialize.query("staging", staging, 'bool')
if spell_check is not None:
query_parameters['spellCheck'] = self._serialize.query("spell_check", spell_check, 'bool')
if bing_spell_check_subscription_key is not None:
query_parameters['bing-spell-check-subscription-key'] = self._serialize.query("bing_spell_check_subscription_key", bing_spell_check_subscription_key, 'str')
if log is not None:
query_parameters['log'] = self._serialize.query("log", log, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(query, 'str')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('LuisResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267344 | MixedRealityClient.check_name_availability_local | test | def check_name_availability_local(
self, location, name, type, custom_headers=None, raw=False, **operation_config):
"""Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource Name To Verify
:type name: str
:param type: Fully qualified resource type which includes provider
namespace
:type type: 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: CheckNameAvailabilityResponse or ClientRawResponse if
raw=true
:rtype: ~azure.mgmt.mixedreality.models.CheckNameAvailabilityResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.mgmt.mixedreality.models.ErrorResponseException>`
"""
check_name_availability = models.CheckNameAvailabilityRequest(name=name, type=type)
# Construct URL
url = self.check_name_availability_local.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'location': self._serialize.url("location", location, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
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')
# Construct body
body_content = self._serialize.body(check_name_availability, 'CheckNameAvailabilityRequest')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CheckNameAvailabilityResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267345 | _WinHttpRequest.open | test | def open(self, method, url):
'''
Opens the request.
method:
the request VERB 'GET', 'POST', etc.
url:
the url to connect
'''
flag = VARIANT.create_bool_false()
_method = BSTR(method)
_url = BSTR(url)
_WinHttpRequest._Open(self, _method, _url, flag) | python | {
"resource": ""
} |
q267346 | _WinHttpRequest.set_timeout | test | def set_timeout(self, timeout_in_seconds):
''' Sets up the timeout for the request. '''
timeout_in_ms = int(timeout_in_seconds * 1000)
_WinHttpRequest._SetTimeouts(
self, 0, timeout_in_ms, timeout_in_ms, timeout_in_ms) | python | {
"resource": ""
} |
q267347 | _WinHttpRequest.set_request_header | test | def set_request_header(self, name, value):
''' Sets the request header. '''
_name = BSTR(name)
_value = BSTR(value)
_WinHttpRequest._SetRequestHeader(self, _name, _value) | python | {
"resource": ""
} |
q267348 | _WinHttpRequest.get_all_response_headers | test | def get_all_response_headers(self):
''' Gets back all response headers. '''
bstr_headers = c_void_p()
_WinHttpRequest._GetAllResponseHeaders(self, byref(bstr_headers))
bstr_headers = ctypes.cast(bstr_headers, c_wchar_p)
headers = bstr_headers.value
_SysFreeString(bstr_headers)
return headers | python | {
"resource": ""
} |
q267349 | _WinHttpRequest.send | test | def send(self, request=None):
''' Sends the request body. '''
# Sends VT_EMPTY if it is GET, HEAD request.
if request is None:
var_empty = VARIANT.create_empty()
_WinHttpRequest._Send(self, var_empty)
else: # Sends request body as SAFEArray.
_request = VARIANT.create_safearray_from_str(request)
_WinHttpRequest._Send(self, _request) | python | {
"resource": ""
} |
q267350 | _WinHttpRequest.status | test | def status(self):
''' Gets status of response. '''
status = c_long()
_WinHttpRequest._Status(self, byref(status))
return int(status.value) | python | {
"resource": ""
} |
q267351 | _WinHttpRequest.status_text | test | def status_text(self):
''' Gets status text of response. '''
bstr_status_text = c_void_p()
_WinHttpRequest._StatusText(self, byref(bstr_status_text))
bstr_status_text = ctypes.cast(bstr_status_text, c_wchar_p)
status_text = bstr_status_text.value
_SysFreeString(bstr_status_text)
return status_text | python | {
"resource": ""
} |
q267352 | _WinHttpRequest.response_body | test | def response_body(self):
'''
Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
'''
var_respbody = VARIANT()
_WinHttpRequest._ResponseBody(self, byref(var_respbody))
if var_respbody.is_safearray_of_bytes():
respbody = var_respbody.str_from_safearray()
return respbody
else:
return '' | python | {
"resource": ""
} |
q267353 | _WinHttpRequest.set_client_certificate | test | def set_client_certificate(self, certificate):
'''Sets client certificate for the request. '''
_certificate = BSTR(certificate)
_WinHttpRequest._SetClientCertificate(self, _certificate) | python | {
"resource": ""
} |
q267354 | _HTTPConnection.putrequest | test | def putrequest(self, method, uri):
''' Connects to host and sends the request. '''
protocol = unicode(self.protocol + '://')
url = protocol + self.host + unicode(uri)
self._httprequest.set_timeout(self.timeout)
self._httprequest.open(unicode(method), url)
# sets certificate for the connection if cert_file is set.
if self.cert_file is not None:
self._httprequest.set_client_certificate(unicode(self.cert_file)) | python | {
"resource": ""
} |
q267355 | _HTTPConnection.putheader | test | def putheader(self, name, value):
''' Sends the headers of request. '''
if sys.version_info < (3,):
name = str(name).decode('utf-8')
value = str(value).decode('utf-8')
self._httprequest.set_request_header(name, value) | python | {
"resource": ""
} |
q267356 | _HTTPConnection.send | test | def send(self, request_body):
''' Sends request body. '''
if not request_body:
self._httprequest.send()
else:
self._httprequest.send(request_body) | python | {
"resource": ""
} |
q267357 | _HTTPConnection.getresponse | test | def getresponse(self):
''' Gets the response and generates the _Response object'''
status = self._httprequest.status()
status_text = self._httprequest.status_text()
resp_headers = self._httprequest.get_all_response_headers()
fixed_headers = []
for resp_header in resp_headers.split('\n'):
if (resp_header.startswith('\t') or\
resp_header.startswith(' ')) and fixed_headers:
# append to previous header
fixed_headers[-1] += resp_header
else:
fixed_headers.append(resp_header)
headers = []
for resp_header in fixed_headers:
if ':' in resp_header:
pos = resp_header.find(':')
headers.append(
(resp_header[:pos].lower(), resp_header[pos + 1:].strip()))
body = self._httprequest.response_body()
length = len(body)
return _Response(status, status_text, length, headers, body) | python | {
"resource": ""
} |
q267358 | _get_readable_id | test | def _get_readable_id(id_name, id_prefix_to_skip):
"""simplified an id to be more friendly for us people"""
# id_name is in the form 'https://namespace.host.suffix/name'
# where name may contain a forward slash!
pos = id_name.find('//')
if pos != -1:
pos += 2
if id_prefix_to_skip:
pos = id_name.find(id_prefix_to_skip, pos)
if pos != -1:
pos += len(id_prefix_to_skip)
pos = id_name.find('/', pos)
if pos != -1:
return id_name[pos + 1:]
return id_name | python | {
"resource": ""
} |
q267359 | _get_serialization_name | test | def _get_serialization_name(element_name):
"""converts a Python name into a serializable name"""
known = _KNOWN_SERIALIZATION_XFORMS.get(element_name)
if known is not None:
return known
if element_name.startswith('x_ms_'):
return element_name.replace('_', '-')
if element_name.endswith('_id'):
element_name = element_name.replace('_id', 'ID')
for name in ['content_', 'last_modified', 'if_', 'cache_control']:
if element_name.startswith(name):
element_name = element_name.replace('_', '-_')
return ''.join(name.capitalize() for name in element_name.split('_')) | python | {
"resource": ""
} |
q267360 | FaceOperations.verify_face_to_person | test | def verify_face_to_person(
self, face_id, person_id, person_group_id=None, large_person_group_id=None, custom_headers=None, raw=False, **operation_config):
"""Verify whether two faces belong to a same person. Compares a face Id
with a Person Id.
:param face_id: FaceId of the face, comes from Face - Detect
:type face_id: str
:param person_id: Specify a certain person in a person group or a
large person group. personId is created in PersonGroup Person - Create
or LargePersonGroup Person - Create.
:type person_id: str
:param person_group_id: Using existing personGroupId and personId for
fast loading a specified person. personGroupId is created in
PersonGroup - Create. Parameter personGroupId and largePersonGroupId
should not be provided at the same time.
:type person_group_id: str
:param large_person_group_id: Using existing largePersonGroupId and
personId for fast loading a specified person. largePersonGroupId is
created in LargePersonGroup - Create. Parameter personGroupId and
largePersonGroupId should not be provided at the same time.
:type large_person_group_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: VerifyResult or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.vision.face.models.VerifyResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
body = models.VerifyFaceToPersonRequest(face_id=face_id, person_group_id=person_group_id, large_person_group_id=large_person_group_id, person_id=person_id)
# Construct URL
url = self.verify_face_to_person.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(body, 'VerifyFaceToPersonRequest')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VerifyResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267361 | JobOperations.add | test | def add(
self, job, job_add_options=None, custom_headers=None, raw=False, **operation_config):
"""Adds a job to the specified account.
The Batch service supports two ways to control the work done as part of
a job. In the first approach, the user specifies a Job Manager task.
The Batch service launches this task when it is ready to start the job.
The Job Manager task controls all other tasks that run under this job,
by using the Task APIs. In the second approach, the user directly
controls the execution of tasks under an active job, by using the Task
APIs. Also note: when naming jobs, avoid including sensitive
information such as user names or secret project names. This
information may appear in telemetry logs accessible to Microsoft
Support engineers.
:param job: The job to be added.
:type job: ~azure.batch.models.JobAddParameter
:param job_add_options: Additional parameters for the operation
:type job_add_options: ~azure.batch.models.JobAddOptions
: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: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`BatchErrorException<azure.batch.models.BatchErrorException>`
"""
timeout = None
if job_add_options is not None:
timeout = job_add_options.timeout
client_request_id = None
if job_add_options is not None:
client_request_id = job_add_options.client_request_id
return_client_request_id = None
if job_add_options is not None:
return_client_request_id = job_add_options.return_client_request_id
ocp_date = None
if job_add_options is not None:
ocp_date = job_add_options.ocp_date
# Construct URL
url = self.add.metadata['url']
path_format_arguments = {
'batchUrl': self._serialize.url("self.config.batch_url", self.config.batch_url, 'str', skip_quote=True)
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
if timeout is not None:
query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['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')
if client_request_id is not None:
header_parameters['client-request-id'] = self._serialize.header("client_request_id", client_request_id, 'str')
if return_client_request_id is not None:
header_parameters['return-client-request-id'] = self._serialize.header("return_client_request_id", return_client_request_id, 'bool')
if ocp_date is not None:
header_parameters['ocp-date'] = self._serialize.header("ocp_date", ocp_date, 'rfc-1123')
# Construct body
body_content = self._serialize.body(job, 'JobAddParameter')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [201]:
raise models.BatchErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
client_raw_response.add_headers({
'client-request-id': 'str',
'request-id': 'str',
'ETag': 'str',
'Last-Modified': 'rfc-1123',
'DataServiceId': 'str',
})
return client_raw_response | python | {
"resource": ""
} |
q267362 | _MinidomXmlToObject.get_entry_properties_from_node | test | def get_entry_properties_from_node(entry, include_id, id_prefix_to_skip=None, use_title_as_id=False):
''' get properties from entry xml '''
properties = {}
etag = entry.getAttributeNS(METADATA_NS, 'etag')
if etag:
properties['etag'] = etag
for updated in _MinidomXmlToObject.get_child_nodes(entry, 'updated'):
properties['updated'] = updated.firstChild.nodeValue
for name in _MinidomXmlToObject.get_children_from_path(entry, 'author', 'name'):
if name.firstChild is not None:
properties['author'] = name.firstChild.nodeValue
if include_id:
if use_title_as_id:
for title in _MinidomXmlToObject.get_child_nodes(entry, 'title'):
properties['name'] = title.firstChild.nodeValue
else:
# TODO: check if this is used
for id in _MinidomXmlToObject.get_child_nodes(entry, 'id'):
properties['name'] = _get_readable_id(
id.firstChild.nodeValue, id_prefix_to_skip)
return properties | python | {
"resource": ""
} |
q267363 | _MinidomXmlToObject.get_children_from_path | test | def get_children_from_path(node, *path):
'''descends through a hierarchy of nodes returning the list of children
at the inner most level. Only returns children who share a common parent,
not cousins.'''
cur = node
for index, child in enumerate(path):
if isinstance(child, _strtype):
next = _MinidomXmlToObject.get_child_nodes(cur, child)
else:
next = _MinidomXmlToObject._get_child_nodesNS(cur, *child)
if index == len(path) - 1:
return next
elif not next:
break
cur = next[0]
return [] | python | {
"resource": ""
} |
q267364 | _MinidomXmlToObject._find_namespaces_from_child | test | def _find_namespaces_from_child(parent, child, namespaces):
"""Recursively searches from the parent to the child,
gathering all the applicable namespaces along the way"""
for cur_child in parent.childNodes:
if cur_child is child:
return True
if _MinidomXmlToObject._find_namespaces_from_child(cur_child, child, namespaces):
# we are the parent node
for key in cur_child.attributes.keys():
if key.startswith('xmlns:') or key == 'xmlns':
namespaces[key] = cur_child.attributes[key]
break
return False | python | {
"resource": ""
} |
q267365 | _ServiceBusManagementXmlSerializer.xml_to_namespace | test | def xml_to_namespace(xmlstr):
'''Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
<NamespaceDescription
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>myunittests</Name>
<Region>West US</Region>
<DefaultKey>0000000000000000000000000000000000000000000=</DefaultKey>
<Status>Active</Status>
<CreatedAt>2012-08-22T16:48:10.217Z</CreatedAt>
<AcsManagementEndpoint>https://myunittests-sb.accesscontrol.windows.net/</AcsManagementEndpoint>
<ServiceBusEndpoint>https://myunittests.servicebus.windows.net/</ServiceBusEndpoint>
<ConnectionString>Endpoint=sb://myunittests.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=0000000000000000000000000000000000000000000=</ConnectionString>
<SubscriptionId>00000000000000000000000000000000</SubscriptionId>
<Enabled>true</Enabled>
</NamespaceDescription>
</content>
</entry>
'''
xmldoc = minidom.parseString(xmlstr)
namespace = ServiceBusNamespace()
mappings = (
('Name', 'name', None),
('Region', 'region', None),
('DefaultKey', 'default_key', None),
('Status', 'status', None),
('CreatedAt', 'created_at', None),
('AcsManagementEndpoint', 'acs_management_endpoint', None),
('ServiceBusEndpoint', 'servicebus_endpoint', None),
('ConnectionString', 'connection_string', None),
('SubscriptionId', 'subscription_id', None),
('Enabled', 'enabled', _parse_bool),
)
for desc in _MinidomXmlToObject.get_children_from_path(
xmldoc,
'entry',
'content',
'NamespaceDescription'):
for xml_name, field_name, conversion_func in mappings:
node_value = _MinidomXmlToObject.get_first_child_node_value(desc, xml_name)
if node_value is not None:
if conversion_func is not None:
node_value = conversion_func(node_value)
setattr(namespace, field_name, node_value)
return namespace | python | {
"resource": ""
} |
q267366 | _ServiceBusManagementXmlSerializer.xml_to_region | test | def xml_to_region(xmlstr):
'''Converts xml response to service bus region
The xml format for region:
<entry>
<id>uuid:157c311f-081f-4b4a-a0ba-a8f990ffd2a3;id=1756759</id>
<title type="text"></title>
<updated>2013-04-10T18:25:29Z</updated>
<content type="application/xml">
<RegionCodeDescription
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>East Asia</Code>
<FullName>East Asia</FullName>
</RegionCodeDescription>
</content>
</entry>
'''
xmldoc = minidom.parseString(xmlstr)
region = ServiceBusRegion()
for desc in _MinidomXmlToObject.get_children_from_path(xmldoc, 'entry', 'content',
'RegionCodeDescription'):
node_value = _MinidomXmlToObject.get_first_child_node_value(desc, 'Code')
if node_value is not None:
region.code = node_value
node_value = _MinidomXmlToObject.get_first_child_node_value(desc, 'FullName')
if node_value is not None:
region.fullname = node_value
return region | python | {
"resource": ""
} |
q267367 | _ServiceBusManagementXmlSerializer.xml_to_namespace_availability | test | def xml_to_namespace_availability(xmlstr):
'''Converts xml response to service bus namespace availability
The xml format:
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<id>uuid:9fc7c652-1856-47ab-8d74-cd31502ea8e6;id=3683292</id>
<title type="text"></title>
<updated>2013-04-16T03:03:37Z</updated>
<content type="application/xml">
<NamespaceAvailability
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Result>false</Result>
</NamespaceAvailability>
</content>
</entry>
'''
xmldoc = minidom.parseString(xmlstr)
availability = AvailabilityResponse()
for desc in _MinidomXmlToObject.get_children_from_path(xmldoc, 'entry', 'content',
'NamespaceAvailability'):
node_value = _MinidomXmlToObject.get_first_child_node_value(desc, 'Result')
if node_value is not None:
availability.result = _parse_bool(node_value)
return availability | python | {
"resource": ""
} |
q267368 | _ServiceBusManagementXmlSerializer.xml_to_metrics | test | def xml_to_metrics(xmlstr, object_type):
'''Converts xml response to service bus metrics objects
The xml format for MetricProperties
<entry>
<id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id>
<title/>
<updated>2014-10-09T11:56:50Z</updated>
<author>
<name/>
</author>
<content type="application/xml">
<m:properties>
<d:Name>listeners.active</d:Name>
<d:PrimaryAggregation>Average</d:PrimaryAggregation>
<d:Unit>Count</d:Unit>
<d:DisplayName>Active listeners</d:DisplayName>
</m:properties>
</content>
</entry>
The xml format for MetricValues
<entry>
<id>https://sbgm.windows.net/MetricValues(datetime\'2014-10-02T00:00:00Z\')</id>
<title/>
<updated>2014-10-09T18:38:28Z</updated>
<author>
<name/>
</author>
<content type="application/xml">
<m:properties>
<d:Timestamp m:type="Edm.DateTime">2014-10-02T00:00:00Z</d:Timestamp>
<d:Min m:type="Edm.Int64">-118</d:Min>
<d:Max m:type="Edm.Int64">15</d:Max>
<d:Average m:type="Edm.Single">-78.44444</d:Average>
<d:Total m:type="Edm.Int64">0</d:Total>
</m:properties>
</content>
</entry>
'''
xmldoc = minidom.parseString(xmlstr)
return_obj = object_type()
members = dict(vars(return_obj))
# Only one entry here
for xml_entry in _MinidomXmlToObject.get_children_from_path(xmldoc,
'entry'):
for node in _MinidomXmlToObject.get_children_from_path(xml_entry,
'content',
'properties'):
for name in members:
xml_name = _get_serialization_name(name)
children = _MinidomXmlToObject.get_child_nodes(node, xml_name)
if not children:
continue
child = children[0]
node_type = child.getAttributeNS("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata", 'type')
node_value = _ServiceBusManagementXmlSerializer.odata_converter(child.firstChild.nodeValue, node_type)
setattr(return_obj, name, node_value)
for name, value in _MinidomXmlToObject.get_entry_properties_from_node(
xml_entry,
include_id=True,
use_title_as_id=False).items():
if name in members:
continue # Do not override if already members
setattr(return_obj, name, value)
return return_obj | python | {
"resource": ""
} |
q267369 | RunbookDraftOperations.replace_content | test | def replace_content(
self, resource_group_name, automation_account_name, runbook_name, runbook_content, custom_headers=None, raw=False, callback=None, polling=True, **operation_config):
"""Replaces the runbook draft content.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param automation_account_name: The name of the automation account.
:type automation_account_name: str
:param runbook_name: The runbook name.
:type runbook_name: str
:param runbook_content: The runbook draft content.
:type runbook_content: Generator
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns object or
ClientRawResponse<object> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[Generator]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[Generator]]
:raises:
:class:`ErrorResponseException<azure.mgmt.automation.models.ErrorResponseException>`
"""
raw_result = self._replace_content_initial(
resource_group_name=resource_group_name,
automation_account_name=automation_account_name,
runbook_name=runbook_name,
runbook_content=runbook_content,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
header_dict = {
'location': 'str',
}
deserialized = self._deserialize('object', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267370 | DomainsOperations.list_recommendations | test | def list_recommendations(
self, keywords=None, max_domain_recommendations=None, custom_headers=None, raw=False, **operation_config):
"""Get domain name recommendations based on keywords.
Get domain name recommendations based on keywords.
:param keywords: Keywords to be used for generating domain
recommendations.
:type keywords: str
:param max_domain_recommendations: Maximum number of recommendations.
:type max_domain_recommendations: int
: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 NameIdentifier
:rtype:
~azure.mgmt.web.models.NameIdentifierPaged[~azure.mgmt.web.models.NameIdentifier]
:raises:
:class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
"""
parameters = models.DomainRecommendationSearchParameters(keywords=keywords, max_domain_recommendations=max_domain_recommendations)
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list_recommendations.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
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')
# Construct body
body_content = self._serialize.body(parameters, 'DomainRecommendationSearchParameters')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.DefaultErrorResponseException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.NameIdentifierPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.NameIdentifierPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267371 | KnowledgebaseOperations.update | test | def update(
self, kb_id, update_kb, custom_headers=None, raw=False, **operation_config):
"""Asynchronous operation to modify a knowledgebase.
:param kb_id: Knowledgebase id.
:type kb_id: str
:param update_kb: Post body of the request.
:type update_kb:
~azure.cognitiveservices.knowledge.qnamaker.models.UpdateKbOperationDTO
: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: Operation or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.knowledge.qnamaker.models.Operation
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException>`
"""
# Construct URL
url = self.update.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'kbId': self._serialize.url("kb_id", kb_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(update_kb, 'UpdateKbOperationDTO')
# Construct and send request
request = self._client.patch(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [202]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 202:
deserialized = self._deserialize('Operation', response)
header_dict = {
'Location': 'str',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267372 | UsersOperations.get_member_groups | test | def get_member_groups(
self, object_id, security_enabled_only, additional_properties=None, custom_headers=None, raw=False, **operation_config):
"""Gets a collection that contains the object IDs of the groups of which
the user is a member.
:param object_id: The object ID of the user for which to get group
membership.
:type object_id: str
:param security_enabled_only: If true, only membership in
security-enabled groups should be checked. Otherwise, membership in
all groups should be checked.
:type security_enabled_only: bool
:param additional_properties: Unmatched properties from the message
are deserialized this collection
:type additional_properties: dict[str, object]
: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 str
:rtype: ~azure.graphrbac.models.StrPaged[str]
:raises:
:class:`GraphErrorException<azure.graphrbac.models.GraphErrorException>`
"""
parameters = models.UserGetMemberGroupsParameters(additional_properties=additional_properties, security_enabled_only=security_enabled_only)
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.get_member_groups.metadata['url']
path_format_arguments = {
'objectId': self._serialize.url("object_id", object_id, 'str'),
'tenantID': self._serialize.url("self.config.tenant_id", self.config.tenant_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
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')
# Construct body
body_content = self._serialize.body(parameters, 'UserGetMemberGroupsParameters')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.GraphErrorException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.StrPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.StrPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267373 | build_package_from_pr_number | test | def build_package_from_pr_number(gh_token, sdk_id, pr_number, output_folder, *, with_comment=False):
"""Will clone the given PR branch and vuild the package with the given name."""
con = Github(gh_token)
repo = con.get_repo(sdk_id)
sdk_pr = repo.get_pull(pr_number)
# "get_files" of Github only download the first 300 files. Might not be enough.
package_names = {f.filename.split('/')[0] for f in sdk_pr.get_files() if f.filename.startswith("azure")}
absolute_output_folder = Path(output_folder).resolve()
with tempfile.TemporaryDirectory() as temp_dir, \
manage_git_folder(gh_token, Path(temp_dir) / Path("sdk"), sdk_id, pr_number=pr_number) as sdk_folder:
for package_name in package_names:
_LOGGER.debug("Build {}".format(package_name))
execute_simple_command(
["python", "./build_package.py", "--dest", str(absolute_output_folder), package_name],
cwd=sdk_folder
)
_LOGGER.debug("Build finished: {}".format(package_name))
if with_comment:
files = [f.name for f in absolute_output_folder.iterdir()]
comment_message = None
dashboard = DashboardCommentableObject(sdk_pr, "(message created by the CI based on PR content)")
try:
installation_message = build_installation_message(sdk_pr)
download_message = build_download_message(sdk_pr, files)
comment_message = installation_message + "\n\n" + download_message
dashboard.create_comment(comment_message)
except Exception:
_LOGGER.critical("Unable to do PR comment:\n%s", comment_message) | python | {
"resource": ""
} |
q267374 | RedisOperations.import_data | test | def import_data(
self, resource_group_name, name, files, format=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Import data into Redis cache.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param name: The name of the Redis cache.
:type name: str
:param files: files to import.
:type files: list[str]
:param format: File format.
:type format: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._import_data_initial(
resource_group_name=resource_group_name,
name=name,
files=files,
format=format,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267375 | RunbookOperations.publish | test | def publish(
self, resource_group_name, automation_account_name, runbook_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Publish runbook draft.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param automation_account_name: The name of the automation account.
:type automation_account_name: str
:param runbook_name: The parameters supplied to the publish runbook
operation.
:type runbook_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises:
:class:`ErrorResponseException<azure.mgmt.automation.models.ErrorResponseException>`
"""
raw_result = self._publish_initial(
resource_group_name=resource_group_name,
automation_account_name=automation_account_name,
runbook_name=runbook_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
client_raw_response.add_headers({
'location': 'str',
})
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | {
"resource": ""
} |
q267376 | Message.renew_lock | test | async def renew_lock(self):
"""Renew the message lock.
This will maintain the lock on the message to ensure
it is not returned to the queue to be reprocessed. In order to complete (or otherwise settle)
the message, the lock must be maintained. Messages received via ReceiveAndDelete mode are not
locked, and therefore cannot be renewed. This operation can also be performed as an asynchronous
background task by registering the message with an `azure.servicebus.aio.AutoLockRenew` instance.
This operation is only available for non-sessionful messages.
:raises: TypeError if the message is sessionful.
:raises: ~azure.servicebus.common.errors.MessageLockExpired is message lock has already expired.
:raises: ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
:raises: ~azure.servicebus.common.errors.MessageAlreadySettled is message has already been settled.
"""
if hasattr(self._receiver, 'locked_until'):
raise TypeError("Session messages cannot be renewed. Please renew the Session lock instead.")
self._is_live('renew')
expiry = await self._receiver._renew_locks(self.lock_token) # pylint: disable=protected-access
self._expiry = datetime.datetime.fromtimestamp(expiry[b'expirations'][0]/1000.0) | python | {
"resource": ""
} |
q267377 | AlterationsOperations.replace | test | def replace(
self, word_alterations, custom_headers=None, raw=False, **operation_config):
"""Replace alterations data.
:param word_alterations: Collection of word alterations.
:type word_alterations:
list[~azure.cognitiveservices.knowledge.qnamaker.models.AlterationsDTO]
: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: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException>`
"""
word_alterations1 = models.WordAlterationsDTO(word_alterations=word_alterations)
# Construct URL
url = self.replace.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(word_alterations1, 'WordAlterationsDTO')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise models.ErrorResponseException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response | python | {
"resource": ""
} |
q267378 | MeshSecretValueOperations.add_value | test | def add_value(
self, secret_resource_name, secret_value_resource_name, name, value=None, custom_headers=None, raw=False, **operation_config):
"""Adds the specified value as a new version of the specified secret
resource.
Creates a new value of the specified secret resource. The name of the
value is typically the version identifier. Once created the value
cannot be changed.
:param secret_resource_name: The name of the secret resource.
:type secret_resource_name: str
:param secret_value_resource_name: The name of the secret resource
value which is typically the version identifier for the value.
:type secret_value_resource_name: str
:param name: Version identifier of the secret value.
:type name: str
:param value: The actual value of the secret.
:type value: 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: SecretValueResourceDescription or ClientRawResponse if
raw=true
:rtype: ~azure.servicefabric.models.SecretValueResourceDescription or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`FabricErrorException<azure.servicefabric.models.FabricErrorException>`
"""
secret_value_resource_description = models.SecretValueResourceDescription(name=name, value=value)
# Construct URL
url = self.add_value.metadata['url']
path_format_arguments = {
'secretResourceName': self._serialize.url("secret_resource_name", secret_resource_name, 'str', skip_quote=True),
'secretValueResourceName': self._serialize.url("secret_value_resource_name", secret_value_resource_name, 'str', skip_quote=True)
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(secret_value_resource_description, 'SecretValueResourceDescription')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201, 202]:
raise models.FabricErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SecretValueResourceDescription', response)
if response.status_code == 201:
deserialized = self._deserialize('SecretValueResourceDescription', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized | python | {
"resource": ""
} |
q267379 | ServiceManagementService.get_storage_account_properties | test | def get_storage_account_properties(self, service_name):
'''
Returns system properties for the specified storage account.
service_name:
Name of the storage service account.
'''
_validate_not_none('service_name', service_name)
return self._perform_get(self._get_storage_service_path(service_name),
StorageService) | python | {
"resource": ""
} |
q267380 | ServiceManagementService.get_storage_account_keys | test | def get_storage_account_keys(self, service_name):
'''
Returns the primary and secondary access keys for the specified
storage account.
service_name:
Name of the storage service account.
'''
_validate_not_none('service_name', service_name)
return self._perform_get(
self._get_storage_service_path(service_name) + '/keys',
StorageService) | python | {
"resource": ""
} |
q267381 | ServiceManagementService.regenerate_storage_account_keys | test | def regenerate_storage_account_keys(self, service_name, key_type):
'''
Regenerates the primary or secondary access key for the specified
storage account.
service_name:
Name of the storage service account.
key_type:
Specifies which key to regenerate. Valid values are:
Primary, Secondary
'''
_validate_not_none('service_name', service_name)
_validate_not_none('key_type', key_type)
return self._perform_post(
self._get_storage_service_path(
service_name) + '/keys?action=regenerate',
_XmlSerializer.regenerate_keys_to_xml(
key_type),
StorageService) | python | {
"resource": ""
} |
q267382 | ServiceManagementService.create_storage_account | test | def create_storage_account(self, service_name, description, label,
affinity_group=None, location=None,
geo_replication_enabled=None,
extended_properties=None,
account_type='Standard_GRS'):
'''
Creates a new storage account in Windows Azure.
service_name:
A name for the storage account that is unique within Windows Azure.
Storage account names must be between 3 and 24 characters in length
and use numbers and lower-case letters only.
description:
A description for the storage account. The description may be up
to 1024 characters in length.
label:
A name for the storage account. The name may be up to 100
characters in length. The name can be used to identify the storage
account for your tracking purposes.
affinity_group:
The name of an existing affinity group in the specified
subscription. You can specify either a location or affinity_group,
but not both.
location:
The location where the storage account is created. You can specify
either a location or affinity_group, but not both.
geo_replication_enabled:
Deprecated. Replaced by the account_type parameter.
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
account_type:
Specifies whether the account supports locally-redundant storage,
geo-redundant storage, zone-redundant storage, or read access
geo-redundant storage.
Possible values are:
Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS
'''
_validate_not_none('service_name', service_name)
_validate_not_none('description', description)
_validate_not_none('label', label)
if affinity_group is None and location is None:
raise ValueError(
'location or affinity_group must be specified')
if affinity_group is not None and location is not None:
raise ValueError(
'Only one of location or affinity_group needs to be specified')
if geo_replication_enabled == False:
account_type = 'Standard_LRS'
return self._perform_post(
self._get_storage_service_path(),
_XmlSerializer.create_storage_service_input_to_xml(
service_name,
description,
label,
affinity_group,
location,
account_type,
extended_properties),
as_async=True) | python | {
"resource": ""
} |
q267383 | ServiceManagementService.update_storage_account | test | def update_storage_account(self, service_name, description=None,
label=None, geo_replication_enabled=None,
extended_properties=None,
account_type='Standard_GRS'):
'''
Updates the label, the description, and enables or disables the
geo-replication status for a storage account in Windows Azure.
service_name:
Name of the storage service account.
description:
A description for the storage account. The description may be up
to 1024 characters in length.
label:
A name for the storage account. The name may be up to 100
characters in length. The name can be used to identify the storage
account for your tracking purposes.
geo_replication_enabled:
Deprecated. Replaced by the account_type parameter.
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
account_type:
Specifies whether the account supports locally-redundant storage,
geo-redundant storage, zone-redundant storage, or read access
geo-redundant storage.
Possible values are:
Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS
'''
_validate_not_none('service_name', service_name)
if geo_replication_enabled == False:
account_type = 'Standard_LRS'
return self._perform_put(
self._get_storage_service_path(service_name),
_XmlSerializer.update_storage_service_input_to_xml(
description,
label,
account_type,
extended_properties)) | python | {
"resource": ""
} |
q267384 | ServiceManagementService.delete_storage_account | test | def delete_storage_account(self, service_name):
'''
Deletes the specified storage account from Windows Azure.
service_name:
Name of the storage service account.
'''
_validate_not_none('service_name', service_name)
return self._perform_delete(
self._get_storage_service_path(service_name),
as_async=True) | python | {
"resource": ""
} |
q267385 | ServiceManagementService.check_storage_account_name_availability | test | def check_storage_account_name_availability(self, service_name):
'''
Checks to see if the specified storage account name is available, or
if it has already been taken.
service_name:
Name of the storage service account.
'''
_validate_not_none('service_name', service_name)
return self._perform_get(
self._get_storage_service_path() +
'/operations/isavailable/' +
_str(service_name) + '',
AvailabilityResponse) | python | {
"resource": ""
} |
q267386 | ServiceManagementService.get_hosted_service_properties | test | def get_hosted_service_properties(self, service_name, embed_detail=False):
'''
Retrieves system properties for the specified hosted service. These
properties include the service name and service type; the name of the
affinity group to which the service belongs, or its location if it is
not part of an affinity group; and optionally, information on the
service's deployments.
service_name:
Name of the hosted service.
embed_detail:
When True, the management service returns properties for all
deployments of the service, as well as for the service itself.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('embed_detail', embed_detail)
return self._perform_get(
self._get_hosted_service_path(service_name) +
'?embed-detail=' +
_str(embed_detail).lower(),
HostedService) | python | {
"resource": ""
} |
q267387 | ServiceManagementService.create_hosted_service | test | def create_hosted_service(self, service_name, label, description=None,
location=None, affinity_group=None,
extended_properties=None):
'''
Creates a new hosted service in Windows Azure.
service_name:
A name for the hosted service that is unique within Windows Azure.
This name is the DNS prefix name and can be used to access the
hosted service.
label:
A name for the hosted service. The name can be up to 100 characters
in length. The name can be used to identify the storage account for
your tracking purposes.
description:
A description for the hosted service. The description can be up to
1024 characters in length.
location:
The location where the hosted service will be created. You can
specify either a location or affinity_group, but not both.
affinity_group:
The name of an existing affinity group associated with this
subscription. This name is a GUID and can be retrieved by examining
the name element of the response body returned by
list_affinity_groups. You can specify either a location or
affinity_group, but not both.
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('label', label)
if affinity_group is None and location is None:
raise ValueError(
'location or affinity_group must be specified')
if affinity_group is not None and location is not None:
raise ValueError(
'Only one of location or affinity_group needs to be specified')
return self._perform_post(self._get_hosted_service_path(),
_XmlSerializer.create_hosted_service_to_xml(
service_name,
label,
description,
location,
affinity_group,
extended_properties),
as_async=True) | python | {
"resource": ""
} |
q267388 | ServiceManagementService.delete_hosted_service | test | def delete_hosted_service(self, service_name, complete=False):
'''
Deletes the specified hosted service from Windows Azure.
service_name:
Name of the hosted service.
complete:
True if all OS/data disks and the source blobs for the disks should
also be deleted from storage.
'''
_validate_not_none('service_name', service_name)
path = self._get_hosted_service_path(service_name)
if complete == True:
path = path +'?comp=media'
return self._perform_delete(path, as_async=True) | python | {
"resource": ""
} |
q267389 | ServiceManagementService.create_deployment | test | def create_deployment(self, service_name, deployment_slot, name,
package_url, label, configuration,
start_deployment=False,
treat_warnings_as_error=False,
extended_properties=None):
'''
Uploads a new service package and creates a new deployment on staging
or production.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service is deployed. Valid
values are: staging, production
name:
The name for the deployment. The deployment name must be unique
among other deployments for the hosted service.
package_url:
A URL that refers to the location of the service package in the
Blob service. The service package can be located either in a
storage account beneath the same subscription or a Shared Access
Signature (SAS) URI from any storage account.
label:
A name for the hosted service. The name can be up to 100 characters
in length. It is recommended that the label be unique within the
subscription. The name can be used to identify the hosted service
for your tracking purposes.
configuration:
The base-64 encoded service configuration file for the deployment.
start_deployment:
Indicates whether to start the deployment immediately after it is
created. If false, the service model is still deployed to the
virtual machines but the code is not run immediately. Instead, the
service is Suspended until you call Update Deployment Status and
set the status to Running, at which time the service will be
started. A deployed service still incurs charges, even if it is
suspended.
treat_warnings_as_error:
Indicates whether to treat package validation warnings as errors.
If set to true, the Created Deployment operation fails if there
are validation warnings on the service package.
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_slot', deployment_slot)
_validate_not_none('name', name)
_validate_not_none('package_url', package_url)
_validate_not_none('label', label)
_validate_not_none('configuration', configuration)
return self._perform_post(
self._get_deployment_path_using_slot(
service_name, deployment_slot),
_XmlSerializer.create_deployment_to_xml(
name,
package_url,
label,
configuration,
start_deployment,
treat_warnings_as_error,
extended_properties),
as_async=True) | python | {
"resource": ""
} |
q267390 | ServiceManagementService.delete_deployment | test | def delete_deployment(self, service_name, deployment_name,delete_vhd=False):
'''
Deletes the specified deployment.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
path= self._get_deployment_path_using_name(service_name, deployment_name)
if delete_vhd:
path += '?comp=media'
return self._perform_delete(
path,
as_async=True) | python | {
"resource": ""
} |
q267391 | ServiceManagementService.swap_deployment | test | def swap_deployment(self, service_name, production, source_deployment):
'''
Initiates a virtual IP swap between the staging and production
deployment environments for a service. If the service is currently
running in the staging environment, it will be swapped to the
production environment. If it is running in the production
environment, it will be swapped to staging.
service_name:
Name of the hosted service.
production:
The name of the production deployment.
source_deployment:
The name of the source deployment.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('production', production)
_validate_not_none('source_deployment', source_deployment)
return self._perform_post(self._get_hosted_service_path(service_name),
_XmlSerializer.swap_deployment_to_xml(
production, source_deployment),
as_async=True) | python | {
"resource": ""
} |
q267392 | ServiceManagementService.change_deployment_configuration | test | def change_deployment_configuration(self, service_name, deployment_name,
configuration,
treat_warnings_as_error=False,
mode='Auto', extended_properties=None):
'''
Initiates a change to the deployment configuration.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
configuration:
The base-64 encoded service configuration file for the deployment.
treat_warnings_as_error:
Indicates whether to treat package validation warnings as errors.
If set to true, the Created Deployment operation fails if there
are validation warnings on the service package.
mode:
If set to Manual, WalkUpgradeDomain must be called to apply the
update. If set to Auto, the Windows Azure platform will
automatically apply the update To each upgrade domain for the
service. Possible values are: Auto, Manual
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('configuration', configuration)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + '/?comp=config',
_XmlSerializer.change_deployment_to_xml(
configuration,
treat_warnings_as_error,
mode,
extended_properties),
as_async=True) | python | {
"resource": ""
} |
q267393 | ServiceManagementService.update_deployment_status | test | def update_deployment_status(self, service_name, deployment_name, status):
'''
Initiates a change in deployment status.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
status:
The change to initiate to the deployment status. Possible values
include:
Running, Suspended
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('status', status)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + '/?comp=status',
_XmlSerializer.update_deployment_status_to_xml(
status),
as_async=True) | python | {
"resource": ""
} |
q267394 | ServiceManagementService.upgrade_deployment | test | def upgrade_deployment(self, service_name, deployment_name, mode,
package_url, configuration, label, force,
role_to_upgrade=None, extended_properties=None):
'''
Initiates an upgrade.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
mode:
If set to Manual, WalkUpgradeDomain must be called to apply the
update. If set to Auto, the Windows Azure platform will
automatically apply the update To each upgrade domain for the
service. Possible values are: Auto, Manual
package_url:
A URL that refers to the location of the service package in the
Blob service. The service package can be located either in a
storage account beneath the same subscription or a Shared Access
Signature (SAS) URI from any storage account.
configuration:
The base-64 encoded service configuration file for the deployment.
label:
A name for the hosted service. The name can be up to 100 characters
in length. It is recommended that the label be unique within the
subscription. The name can be used to identify the hosted service
for your tracking purposes.
force:
Specifies whether the rollback should proceed even when it will
cause local data to be lost from some role instances. True if the
rollback should proceed; otherwise false if the rollback should
fail.
role_to_upgrade:
The name of the specific role to upgrade.
extended_properties:
Dictionary containing name/value pairs of storage account
properties. You can have a maximum of 50 extended property
name/value pairs. The maximum length of the Name element is 64
characters, only alphanumeric characters and underscores are valid
in the Name, and the name must start with a letter. The value has
a maximum length of 255 characters.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('mode', mode)
_validate_not_none('package_url', package_url)
_validate_not_none('configuration', configuration)
_validate_not_none('label', label)
_validate_not_none('force', force)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + '/?comp=upgrade',
_XmlSerializer.upgrade_deployment_to_xml(
mode,
package_url,
configuration,
label,
role_to_upgrade,
force,
extended_properties),
as_async=True) | python | {
"resource": ""
} |
q267395 | ServiceManagementService.walk_upgrade_domain | test | def walk_upgrade_domain(self, service_name, deployment_name,
upgrade_domain):
'''
Specifies the next upgrade domain to be walked during manual in-place
upgrade or configuration change.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
upgrade_domain:
An integer value that identifies the upgrade domain to walk.
Upgrade domains are identified with a zero-based index: the first
upgrade domain has an ID of 0, the second has an ID of 1, and so on.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('upgrade_domain', upgrade_domain)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + '/?comp=walkupgradedomain',
_XmlSerializer.walk_upgrade_domain_to_xml(
upgrade_domain),
as_async=True) | python | {
"resource": ""
} |
q267396 | ServiceManagementService.reboot_role_instance | test | def reboot_role_instance(self, service_name, deployment_name,
role_instance_name):
'''
Requests a reboot of a role instance that is running in a deployment.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
role_instance_name:
The name of the role instance.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('role_instance_name', role_instance_name)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + \
'/roleinstances/' + _str(role_instance_name) + \
'?comp=reboot',
'',
as_async=True) | python | {
"resource": ""
} |
q267397 | ServiceManagementService.delete_role_instances | test | def delete_role_instances(self, service_name, deployment_name,
role_instance_names):
'''
Reinstalls the operating system on instances of web roles or worker
roles and initializes the storage resources that are used by them. If
you do not want to initialize storage resources, you can use
reimage_role_instance.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
role_instance_names:
List of role instance names.
'''
_validate_not_none('service_name', service_name)
_validate_not_none('deployment_name', deployment_name)
_validate_not_none('role_instance_names', role_instance_names)
return self._perform_post(
self._get_deployment_path_using_name(
service_name, deployment_name) + '/roleinstances/?comp=delete',
_XmlSerializer.role_instances_to_xml(role_instance_names),
as_async=True) | python | {
"resource": ""
} |
q267398 | ServiceManagementService.check_hosted_service_name_availability | test | def check_hosted_service_name_availability(self, service_name):
'''
Checks to see if the specified hosted service name is available, or if
it has already been taken.
service_name:
Name of the hosted service.
'''
_validate_not_none('service_name', service_name)
return self._perform_get(
'/' + self.subscription_id +
'/services/hostedservices/operations/isavailable/' +
_str(service_name) + '',
AvailabilityResponse) | python | {
"resource": ""
} |
q267399 | ServiceManagementService.list_service_certificates | test | def list_service_certificates(self, service_name):
'''
Lists all of the service certificates associated with the specified
hosted service.
service_name:
Name of the hosted service.
'''
_validate_not_none('service_name', service_name)
return self._perform_get(
'/' + self.subscription_id + '/services/hostedservices/' +
_str(service_name) + '/certificates',
Certificates) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.