blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8997508dde0407076d1fc2ee84ba66d8517bbd0e | srihariprasad-r/workable-code | /Practice problems/foundation/2D-arrays/wavetraversal.py | 592 | 4.3125 | 4 | """
Wave traversal is first go top to bottom, for next column go from bottom to top and continue
[
| 1 | 2 | 3
| 4 | 5 | 6
]
To achieve this, for even columns, we go top to bottom and vice-versa for odd columns
"""
def wavetraversal(arr1):
r1, c1 = len(arr1), len(arr1[0])
for i in range(len(arr1[0])):
if i % 2 == 0:
for j in range(len(arr1)):
print(arr1[j][i])
else:
for j in range(len(arr1) -1, -1, -1):
print(arr1[j][i])
arr1 = [
[1, 2, 3],
[4, 5, 6]
]
print(wavetraversal(arr1)) |
6c5d26b9e2663817378906ad2ca9d4f56317c046 | Anubamagpljecs07/Codekata_Hunter | /Pal_using_stack.py | 711 | 3.640625 | 4 | class Stack:
def __init__(self):
self.items=[]
def push(self,data):
return self.items.append(data)
def pop(self):
return self.items.pop()
def is_empty(self):
if self.items==[]:
return True
else:
return False
def get(self):
return self.items
a=input()
s=Stack()
is_pal=False
if len(a)%2==0:
pass
else:
a=a[0:len(a)//2]+a[(len(a)//2)+1:len(a)]
for i in range(len(a)//2):
g=a[i]
s.push(g)
for i in range((len(a)//2),len(a)):
g=a[i]
top=s.pop()
if top==g :
is_pal=True
else:
is_pal=False
break
if s.is_empty() and is_pal:
print("YES")
else:
print("NO")
|
08601c461854255623a05ff639ec0b4771972f8e | beidou9313/deeptest | /第一期/上海-Jason/pyLearn/task02/breakAndContinue.py | 1,428 | 3.875 | 4 | # _*_ coding : utf-8 _*_
__author__ = "Jason"
'''
break和continue语句及循环中的else子句
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
continue语句被 用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
'''
#for语句的break和continue
#break
for counter in range(0,10):
print("counter值为%d"%counter)
if counter == 1:
print("测试break中断if语句")
print("counter值为%d"%counter)
print("break中断前")#可打印
break
print("break中断后")#不打印,且counter值最大为1,即循环到1时就终止循环
print()
print('-'*50)
#continue
for i in range(0,3):
print("测试continue跳出if语句")
print("i值为%d"%i)
print("continue跳出前")#可打印
continue
print("continue跳出后")#不打印
print('-'*50)
#while语句的break和continue
#break
i = 0
while i <= 3:
print("i值为%d"%i)
if i > 1:
print("break前")
break
print("break后")#i大于1后不循环
i = i +1
print('-'*50)
#continue
i = 0
while i <= 3:
print("i值为%d"%i)
i = i + 1
if i > 1:
print("continue前")
continue
print("continue后")#大于1后循环继续,不打印
#i = i + 1 如果自增放在这里,会无限循环 |
c1426068a73977b07388fbaa02e2250ba3ad0ed0 | m-01101101/code_wars | /multiplication_table.py | 563 | 4.25 | 4 | """
Your task, is to create NxN multiplication table, of size provided in parameter.
for example, when given size is 3:
1 2 3
2 4 6
3 6 9
"""
def multiplication_table(size):
meta_list = []
list1 = []
for i in range(size):
list1.append(i + 1)
meta_list.append(list1)
for i in range(size - 1):
newlist = [x * (i + 2) for x in list1]
meta_list.append(newlist)
return meta_list
"""
alternative approach
def multiplicationTable(size):
return [[j*i for j in range(1, size+1)] for i in range(1, size+1)]
"""
|
13821533695b84cab42b1daca172891a03a58afb | daniel-reich/ubiquitous-fiesta | /fpJXv7Qn9LCxX8FYq_13.py | 161 | 3.640625 | 4 |
def solve(eq):
lst = eq.split(' ')
if lst[1] == '+':
return eval(lst[-1] + '-' + lst[2])
elif lst[1] == '-':
return eval(lst[-1] + '+' + lst[2])
|
58809beb7946fb5b3f896b731f152a9be7052334 | h-main81423/main_h_python | /functions.py | 642 | 3.96875 | 4 | def greetings():
print("Hello from the greetings function")
# the greetings function just says hello
# invoke or call the function
greetings()
def greetingsWithArgs(msg="a default message"):
# print the msg variable
print("now we're saying", msg, "from another function.")
greetingsWithArgs("eat my fuckin weenie")
greetingsWithArgs("damn dis sucks cock")
greetingsWithArgs()
# returning values from functions can be a very powerful tool
def someMath(num1=2, num2=4):
return num1 + num2
sum = someMath()
print("We are doing math and getting", sum)
sum = someMath(10, 15)
print("More math and we are getting", sum)
|
cfab6dc766951b3a9161cb015c625de3bb55c02d | ruslanvs/Bike | /Bike.py | 1,007 | 4.25 | 4 | class Bike( object ):
def __init__( self, price, max_speed, miles = 0 ):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo( self ):
print self.price, self.max_speed, self.miles
return self
def ride( self ):
print "Miles before the ride", self.miles
print "Riding ..."
self.miles += 10
print "Miles after the ride", self.miles
return( self )
def reverse( self ):
if self.miles < 5:
print "We only have", self.miles, "miles. Cannot reverse anymore!"
return( self )
print "Revesing..."
self.miles -= 5
print "Miles after reversing", self.miles
return( self )
Harley = Bike( 20000, "120mph" )
Dukatti = Bike( 30000, "160mph" )
Suzuki = Bike( 25000, "200mph" )
Harley.ride().ride().ride().reverse().displayInfo()
Dukatti.ride().ride().reverse().reverse().displayInfo()
Suzuki.reverse().reverse().reverse().displayInfo() |
27b711d9e12bb397878fa9c87ec648b15ff9add1 | PkYang-2020/- | /ques56.py | 624 | 3.828125 | 4 | num = [[1,2],[2,3],[3,5]]
res = []
def quick_sort(num):
if len(num) < 2:
return
p = num[0][0]
L = []
M = []
R = []
while len(num) > 0:
if p > num[-1][0]:
L.append(num.pop())
elif p == num[-1][0]:
M.append(num.pop())
else:
R.append(num.pop())
quick_sort(L)
quick_sort(R)
num.extend(L)
num.extend(M)
num.extend(R)
return num
quick_sort(num)
for interval in num:
if len(res) == 0 or interval[0] > res[-1][1]:
res.append(interval)
else:
res[-1][1] = max(res[-1][1],interval[1])
print(res) |
00df03ae6d38a12bd04675f0a5a415d7f6a052c2 | j-kroon/HackerRank | /hacker/function.py | 461 | 4.1875 | 4 | """
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
"""
def is_leap(year):
leap = False
if leap % 4 != 0:
return leap
elif leap%100 == 0 & leap%400 != 0:
return leap
else:
leap = "WTF"
return leap
year = 2001 # int(input())
print(is_leap(year)) |
bd4209636cdacc6482ee1e914d5617e350184338 | dguan4/HanStory | /src/button.py | 1,052 | 4.0625 | 4 | """
Button class for doing actions
"""
import pygame
class Button:
def __init__(self, text, x, y, width, height, action=None):
"""
Creates a button at a location and some text
:param text: text to display
:param x: x location
:param y: y location
:param width: width of button
:param height: height of button
:param action: action to perform
:return:
"""
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.action = action
def button_clicked(self, x, y, width, height):
"""
Checks if the button is clicked
:param x:
:param y:
:param width:
:param height:
:param action:
:return:
"""
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+width > mouse[0] > x and y+height > mouse[1] > y:
if click[0] == 1:
return True
return False
|
919e2493e1b46750f22563d27bce479473312340 | bsherwood9/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,700 | 4.375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
if end >= start:
mid = (start + end)//2
if arr[mid] == target:
return mid
if arr[mid] > target:
return binary_search(arr, target, start, mid - 1)
if arr[mid] <= target:
return binary_search(arr, target, mid + 1, end)
else:
return -1
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
# Your code here
if arr[0] < arr[len(arr)-1]:
low = 0
high = len(arr)-1
print("running")
while high >= low:
mid = (low + high)//2
if arr[mid] == target:
return mid
if arr[mid] > target:
high = mid - 1
# return agnostic_binary_search(arr, target)
if arr[mid] <= target:
low = mid + 1
# return agnostic_binary_search(arr, target)
else:
return -1
else:
print("descending")
high = 0
low = len(arr)-1
while low >= high:
mid = (low + high)//2
if arr[mid] == target:
return mid
if arr[mid] >= target:
high = mid + 1
if arr[mid] < target:
low = mid - 1
else:
return -1
|
f139032627edeea7b0e6bdeeb4df291d75a6b4dc | iwuch/python_examples | /merge_intervals.py | 280 | 3.765625 | 4 | intervals = [[1,2],[3,4],[5,6],[0,10],[7,12]]
def merge(intervals):
intervals.sort()
results = []
for i in intervals:
if not results or results[-1][-1]<i[0]:
results.append(i)
else:
results[-1][-1] = max(results[-1][-1],i[-1])
return results
print(merge(intervals)) |
9679335e7efea656319de208270b1eaf9bd84d49 | tjwudi/learn-python | /codewars/character-frequency.py | 562 | 3.984375 | 4 | # return a list of tuples sorted by frequency with
# the most frequent letter first. Any letters with the
# same frequency are ordered alphabetically
dic = {}
def inc(c):
if 'a' <= c <= 'z':
if dic.get(c, 0) == 0:
dic[c] = 1
else:
dic[c] += 1
def letter_frequency(text):
text = text.lower()
for c in text:
inc(c)
result = []
for key in dic:
value = dic[key]
result.append((key, value))
return sorted(result, key = lambda x: (-x[1], x[0]))
print(letter_frequency("""wklv lv d vhfuhw phvvdjh""")) |
fadfe2612478e80ef8615a581bd1826f895e6069 | mercado-joshua/Program__Spell-Checker | /pyspellchecker-package/main1.py | 186 | 3.609375 | 4 | from spellchecker import SpellChecker
spell = SpellChecker()
misspelled = spell.unknown(['pythn', 'is', 'populr', 'languge'])
for word in misspelled:
print(spell.correction(word)) |
275c024bc09b30b666f8c6f86e35c77b73a6ab92 | SJeliazkova/SoftUni | /Python-Fundamentals/Exercises-and-Labs/data_type_more_exercises/04_decrypting_messages.py | 194 | 3.546875 | 4 | key = int(input())
lines = int(input())
message = ""
for l in range(lines):
character = input()
new_character = chr(ord(character) + key)
message += new_character
print(message)
|
8d8afbe790ccfff8d4caa8a3dfce3d23dfb37ccc | Frans-L/Algorithm-Challenge-Heaps | /visualize/misc.py | 5,775 | 3.96875 | 4 | # This is used for the visualization. The function calculates
# the positions of the nodes for the tree visualization
# Licensed under Creative Commons Attribution-Share Alike
# (C) Joel
# https://stackoverflow.com/a/29597209/2966723
import networkx as nx
import random
def hierarchy_pos(
G, root=None, width=1.0, vert_gap=0.2, vert_loc=0, leaf_vs_root_factor=0.5
):
"""
If the graph is a tree this will return the positions to plot this in a
hierarchical layout.
Based on Joel's answer at https://stackoverflow.com/a/29597209/2966723,
but with some modifications.
We include this because it may be useful for plotting transmission trees,
and there is currently no networkx equivalent (though it may be coming soon).
There are two basic approaches we think of to allocate the horizontal
location of a node.
- Top down: we allocate horizontal space to a node. Then its ``k``
descendants split up that horizontal space equally. This tends to result
in overlapping nodes when some have many descendants.
- Bottom up: we allocate horizontal space to each leaf node. A node at a
higher level gets the entire space allocated to its descendant leaves.
Based on this, leaf nodes at higher levels get the same space as leaf
nodes very deep in the tree.
We use use both of these approaches simultaneously with ``leaf_vs_root_factor``
determining how much of the horizontal space is based on the bottom up
or top down approaches. ``0`` gives pure bottom up, while 1 gives pure top
down.
:Arguments:
**G** the graph (must be a tree)
**root** the root node of the tree
- if the tree is directed and this is not given, the root will be found and used
- if the tree is directed and this is given, then the positions will be
just for the descendants of this node.
- if the tree is undirected and not given, then a random choice will be used.
**width** horizontal space allocated for this branch - avoids overlap with other branches
**vert_gap** gap between levels of hierarchy
**vert_loc** vertical location of root
**leaf_vs_root_factor**
xcenter: horizontal location of root
"""
# if not nx.is_tree(G):
# raise TypeError('cannot use hierarchy_pos on a graph that is not a tree')
if root is None:
if isinstance(G, nx.DiGraph):
# allows back compatibility with nx version 1.11
root = next(iter(nx.topological_sort(G)))
else:
root = random.choice(list(G.nodes))
def _hierarchy_pos(
G,
root,
leftmost,
width,
leafdx=0.2,
vert_gap=0.2,
vert_loc=0,
xcenter=0.5,
rootpos=None,
leafpos=None,
parent=None,
):
"""
see hierarchy_pos docstring for most arguments
pos: a dict saying where all nodes go if they have been assigned
parent: parent of this branch. - only affects it if non-directed
"""
if rootpos is None:
rootpos = {root: (xcenter, vert_loc)}
else:
rootpos[root] = (xcenter, vert_loc)
if leafpos is None:
leafpos = {}
children = list(G.neighbors(root))
leaf_count = 0
if not isinstance(G, nx.DiGraph) and parent is not None:
children.remove(parent)
if len(children) != 0:
rootdx = width / len(children)
nextx = xcenter - width / 2 - rootdx / 2
for child in children:
nextx += rootdx
rootpos, leafpos, newleaves = _hierarchy_pos(
G,
child,
leftmost + leaf_count * leafdx,
width=rootdx,
leafdx=leafdx,
vert_gap=vert_gap,
vert_loc=vert_loc - vert_gap,
xcenter=nextx,
rootpos=rootpos,
leafpos=leafpos,
parent=root,
)
leaf_count += newleaves
leftmostchild = min((x for x, y in [leafpos[child] for child in children]))
rightmostchild = max((x for x, y in [leafpos[child] for child in children]))
leafpos[root] = ((leftmostchild + rightmostchild) / 2, vert_loc)
else:
leaf_count = 1
leafpos[root] = (leftmost, vert_loc)
# pos[root] = (leftmost + (leaf_count-1)*dx/2., vert_loc)
# print(leaf_count)
return rootpos, leafpos, leaf_count
xcenter = width / 2.0
if isinstance(G, nx.DiGraph):
leafcount = len(
[node for node in nx.descendants(G, root) if G.out_degree(node) == 0]
)
elif isinstance(G, nx.Graph):
leafcount = len(
[
node
for node in nx.node_connected_component(G, root)
if G.degree(node) == 1 and node != root
]
)
rootpos, leafpos, leaf_count = _hierarchy_pos(
G,
root,
0,
width,
leafdx=width * 1.0 / leafcount,
vert_gap=vert_gap,
vert_loc=vert_loc,
xcenter=xcenter,
)
pos = {}
for node in rootpos:
pos[node] = (
leaf_vs_root_factor * leafpos[node][0]
+ (1 - leaf_vs_root_factor) * rootpos[node][0],
leafpos[node][1],
)
# pos = {node:(leaf_vs_root_factor*x1+(1-leaf_vs_root_factor)*x2, y1) for ((x1,y1), (x2,y2)) in (leafpos[node], rootpos[node]) for node in rootpos}
xmax = max(x for x, y in pos.values())
for node in pos:
pos[node] = (pos[node][0] * width / xmax, pos[node][1])
return pos
|
73295b96438c3a148c377eddd639b9e2b52ad2aa | msagar7/collegematch | /processdata.py | 1,008 | 3.78125 | 4 | import csv
from collections import defaultdict
# Loads the csv file of college data into a dictionary
# params:
# - filename: name of csv file containing the dataset
# return:
# - dictionary:
# - key: college UNITID defined by DOE
# - value: dictionary containing different data
# points of each college (eg. city,
# % undergraduate males)
def createDataDictionary(filename):
column_names = []
master = defaultdict(dict)
header = True
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for row in reader:
if header:
column_names = row
header = False
else:
college_id = int(row[0])
for i in range(1, len(row)):
datapoint = None
if row[i].isnumeric(): # numerical data
datapoint = float(row[i])
elif row[i] != "NULL":
datapoint = row[i]
master[college_id][column_names[i]] = datapoint
return master
if __name__ == "__main__":
master = createDataDictionary('dataset.csv')
print(master[101116]['ZIP'])
|
4e49424909f9442207f35e01d14a4af291dc523d | cedricbasuel/flames-with-plot-generator | /flames.py | 2,229 | 3.921875 | 4 | from collections import Counter
def remove_common_letters(string1, string2):
'''Given two strings, remove common letters.
Params
------
string1, string2 : str
Returns
-------
uniqueDict : dict
Dictionary of unique letters in both strings and their counts.
'''
# dict1 = Counter(string1)
# dict2 = Counter(string2)
# common1 = dict1 - dict2
# common2 = dict2 - dict1
# commonDict = common1 + common2
#### if lahat ng common letters tatanggalin
unique1 = [char for char in string1 if char not in string2]
unique2 = [char for char in string2 if char not in string1]
uniqueDict = unique1 + unique2
uniqueDict = Counter(uniqueDict)
####
if len(uniqueDict) == 0:
print('No letters in common')
return None
else:
return uniqueDict
def get_flames_status(letter_list):
'''Eliminate letters from FLAMES until one
is left given number of unique letters.
Params
------
letter_list : dict
Dictionary of unique letters and their counts.
Returns
-------
flames_status : str
One of the letters in 'FLAMES'.
'''
FLAMES_DICTIONARY = {
'F':'Friendship',
'L':'Love',
'A':'Affection',
'M':'Marriage',
'E':'Enemy',
'S':'Sibling'
}
flames_number = sum(letter_list.values())
# print('Remaining letters:', flames_number)
flames_letters = [char for char in 'FLAMES']
flames_index = (flames_number % len(flames_letters)) - 1
while len(flames_letters) > 1 :
# print('letter to remove: ',flames_letters[flames_index])
flames_letters.pop(flames_index)
temp_letters = [0 for i in range(len(flames_letters))]
temp_letters = [flames_letters[n-(flames_index)-1] for n in range(len(flames_letters))]
flames_letters = temp_letters
flames_index = (flames_number % len(flames_letters)) - 1
flames_status = flames_letters[0]
return FLAMES_DICTIONARY[flames_status]
if __name__ == '__main__':
letters = remove_common_letters('elisabeth','alexander')
flames_status = get_flames_status(letters)
print(flames_status) |
4b8b1629494a37ba9c2beae07c7a22650b47273d | SebastVR/test | /Data_Science_Python/Introduction_to_Data_Sciencein_Python/Assignment2.py | 11,462 | 4.125 | 4 | '''Assignment 2 - Pandas Introduction
All questions are weighted the same in this assignment.
Part 1
The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on
All Time Olympic Games Medals, and does some basic data cleaning.
The columns are organized as # of Summer games, Summer medals, # of Winter games, Winter medals, total
# number of games, total # of medals. Use this dataset to answer the questions below.'''
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0] # the [0] element is the country name (new index)
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
df = df.drop('Totals')
df.head()
#---------- ANSWER ----------
'''
# Summer Gold Silver ... Bronze.2 Combined total ID
Afghanistan 13 0 0 ... 2 2 AFG
Algeria 12 5 2 ... 8 15 ALG
Argentina 23 18 24 ... 28 70 ARG
Armenia 5 1 2 ... 9 12 ARM
Australasia 2 3 4 ... 5 12 ANZ
[5 rows x 16 columns]'''
#-----------------------------------------------------------------------
'''Question 0 (Example).
What is the first country in df? This function should return a Series.'''
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the row for Afghanistan, which is a Series object. The assignment
# question description will tell you the general format the autograder is expecting
return df.iloc[0]
# You can examine what your function returns by calling it in the cell. If you have questions
# about the assignment formats, check out the discussion forums for any FAQs
answer_zero()
#---------- ANSWER ----------
'''
# Summer 13
Gold 0
Silver 0
Bronze 2
Total 2
# Winter 0
Gold.1 0
Silver.1 0
Bronze.1 0
Total.1 0
# Games 13
Gold.2 0
Silver.2 0
Bronze.2 2
Combined total 2
ID AFG
Name: Afghanistan, dtype: object'''
#-----------------------------------------------------------------------
'''Question 1
Which country has won the most gold medals in summer games?
This function should return a single string value.'''
def answer_one():
return df['Gold'].idxmax()
answer_one()
#---------- ANSWER ----------
'United States'
#-----------------------------------------------------------------------
'''Question 2
Which country had the biggest difference between their summer and winter gold medal counts?
This function should return a single string value.'''
def answer_two():
return ((df['Gold'] - df['Gold.1']).idxmax())
answer_two()
#---------- ANSWER ----------
'United States'
#-----------------------------------------------------------------------
'''Question 3
Which country has the biggest difference between their summer gold medal counts and winter gold medal
counts relative to their total gold medal count?
(Summer Gold−Winter Gold)/ Total Gold
Only include countries that have won at least 1 gold in both summer and winter.
This function should return a single string value'''
def answer_three():
only_gold = df.where((df['Gold'] > 0) & (df['Gold.1'] > 0))
only_gold = only_gold.dropna()
return (abs((only_gold['Gold'] - only_gold['Gold.1']) / only_gold['Gold.2'])).idxmax()
answer_three()
#---------- ANSWER ----------
'Bulgaria'
#-----------------------------------------------------------------------
'''Question 4
Write a function that creates a Series called "Points" which is a weighted value where each gold medal
(Gold.2) counts for 3 points, silver medals (Silver.2) for 2 points, and bronze medals (Bronze.2)
for 1 point. The function should return only the column (a Series object) which you created, with the
country names as indices.
This function should return a Series named Points of length 146'''
def answer_for():
df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2']*1
return df['Points']
answer_for()
#---------- ANSWER ----------
'''
Afghanistan 2
Algeria 27
Argentina 130
Armenia 16
Australasia 22
Australia 923
Austria 569
Azerbaijan 43
Bahamas 24
Bahrain 1
Barbados 1
Belarus 154
Belgium 276
Bermuda 1
Bohemia 5
Botswana 2
Brazil 184
British West Indies 2
Bulgaria 411
Burundi 3
Cameroon 12
Canada 846
Chile 24
China 1120
Colombia 29
Costa Rica 7
Ivory Coast 2
Croatia 67
Cuba 420
Cyprus 2
...
Spain 268
Sri Lanka 4
Sudan 2
Name: Points, dtype: int64 '''
#-----------------------------------------------------------------------
'''Part 2
For the next set of questions, we will be using census data from the United States Census Bureau.
Counties are political and geographic subdivisions of states in the United States. This dataset contains
population data for counties and states in the US from 2010 to 2015. See this document for a description of
the variable names.
The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate.
Question 5
Which state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for
future questions too...)
This function should return a single string value.'''
census_df = pd.read_csv('census.csv')
census_df.head()
'''SUMLEV REGION DIVISION STATE COUNTY STNAME CTYNAME CENSUS2010POP ESTIMATESBASE2010 POPESTIMATE2010 ... RDOMESTICMIG2011 RDOMESTICMIG2012 RDOMESTICMIG2013 RDOMESTICMIG2014 RDOMESTICMIG2015 RNETMIG2011 RNETMIG2012 RNETMIG2013 RNETMIG2014 RNETMIG2015
0 40 3 6 1 0 Alabama Alabama 4779736 4780127 4785161 ... 0.002295 -0.193196 0.381066 0.582002 -0.467369 1.030015 0.826644 1.383282 1.724718 0.712594
1 50 3 6 1 1 Alabama Autauga County 54571 54571 54660 ... 7.242091 -2.915927 -3.012349 2.265971 -2.530799 7.606016 -2.626146 -2.722002 2.592270 -2.187333
2 50 3 6 1 3 Alabama Baldwin County 182265 182265 183193 ... 14.832960 17.647293 21.845705 19.243287 17.197872 15.844176 18.559627 22.727626 20.317142 18.293499
3 50 3 6 1 5 Alabama Barbour County 27457 27457 27341 ... -4.728132 -2.500690 -7.056824 -3.904217 -10.543299 -4.874741 -2.758113 -7.167664 -3.978583 -10.543299
4 50 3 6 1 7 Alabama Bibb County 22915 22919 22861 ... -5.527043 -5.068871 -6.201001 -0.177537 0.177258 -5.088389 -4.363636 -5.403729 0.754533 1.107861
5 rows × 100 columns'''
def answer_five():
new_df = census_df[census_df['SUMLEV'] == 50]
return new_df.groupby('STNAME').count()['SUMLEV'].idxmax()
answer_five()
#---------- ANSWER ----------
'Texas'
#-----------------------------------------------------------------------
'''Question 6
Only looking at the three most populous counties for each state, what are the three most populous states
(in order of highest population to lowest population)? Use CENSUS2010POP.
This function should return a list of string values.'''
def answer_six():
new_df = census_df[census_df['SUMLEV'] == 50]
most_populous_counties = new_df.sort_values('CENSUS2010POP', ascending=False).groupby('STNAME').head(3)
return most_populous_counties.groupby('STNAME').sum().sort_values('CENSUS2010POP', ascending=False).head(3).index.tolist()
answer_six()
#---------- ANSWER ----------
['California', 'Texas', 'Illinois']
#-----------------------------------------------------------------------
'''Question 7
Which county has had the largest absolute change in population within the period 2010-2015?
(Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to
consider all six columns.)
e.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its largest change in
the period would be |130-80| = 50. This function should return a single string value.'''
def answer_seven():
new_df = census_df[census_df['SUMLEV'] == 50][[6, 9, 10, 11, 12, 13, 14]]
new_df["MaxDiff"] = abs(new_df.max(axis=1) - new_df.min(axis=1))
most_change = new_df.sort_values(by=["MaxDiff"], ascending = False)
return most_change.iloc[0][0]
answer_seven()
#---------- ANSWER ----------
'Harris County'
#-----------------------------------------------------------------------
'''Question 8
In this datafile, the United States is broken up into four regions using the "REGION" column.
Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington',
and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.
This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index
ID as the census_df (sorted ascending by index)'''
def answer_eight():
counties = census_df[census_df['SUMLEV'] == 50]
region = counties[(counties['REGION'] == 1) | (counties['REGION'] == 2)]
washington = region[region['CTYNAME'].str.startswith("Washington")]
grew = washington[washington['POPESTIMATE2015'] > washington['POPESTIMATE2014']]
return grew[['STNAME', 'CTYNAME']]
answer_eight()
#---------- ANSWER ----------
''' STNAME CTYNAME
896 Iowa Washington County
1419 Minnesota Washington County
2345 Pennsylvania Washington County
2355 Rhode Island Washington County
3163 Wisconsin Washington County'''
#----------------------------------------------------------------------- |
4a17e1fdb8f65183e2e7e30e3fa265c76f570c16 | AlexanderWeismannn/Pierian-Data-Python-Course | /Methods and Functions Questions/Challenging/spy_game.py | 636 | 3.90625 | 4 | #CHALLENGING PROBLEMS #1 (SPY GAME)
#TAKES IN A LIST OF NUMS AN RETURNS TRUE if there exists a [0, 0, 7] in order
def spy_game(nums):
exists = 0# if the number reaches 3 then the 007 string exists in order
for i in range(len(nums)):
if(nums[i] == 0 and exists == 0):
exists = exists + 1
continue
if(nums[i] == 0 and exists == 1):
exists = exists + 1
continue
if(nums[i] == 7 and exists == 2):
exists = exists + 1
if(exists == 3):
return True
else:
return False
print(spy_game([1,7,2,0,4,5,0]))
|
13394710d887a6c7ffb93f28cb294f032d916175 | patkhai/LeetCode-Python | /OA/Goldman_Sach/rotateTheString_GoldManSachs.py | 1,035 | 3.953125 | 4 | def rotateTheString(originalString, direction, amount):
lengthS = len(originalString)
for rotate in amount:
for j in range(rotate-1):
if direction == 1: #rotate right
originalString = originalString[lengthS - 1] + originalString[0:lengthS-1]
else: #rotate left
originalString = originalString[1:lengthS] + originalString[0]
return originalString
s = "hurart"
print(rotateTheString(s,[0,1],[4,1]))
s = "ephjos"
print(rotateTheString(s,[1,1],[4,1]))
# def RotateMe(text,mode=0,steps=1):
# # Takes a text string and rotates
# # the characters by the number of steps.
# # mode=0 rotate right
# # mode=1 rotate left
# length=len(text)
# for step, i in enumerate(steps):
# # repeat for required steps
# if mode==0:
# # rotate right
# text=text[length-1] + text[0:length-1]
# else:
# # rotate left
# text=text[1:length] + text[0]
# return text
# s = "hurart"
# print(RotateMe(s,[0,1],[4,1])) |
679e8559e444aecf44063540bb7f33ad9dbc2668 | AirGear02/PyLabs | /Lab1/task1.py | 361 | 3.78125 | 4 | from math import cos, factorial, fabs
eps = float(input('Eps = '))
a = float(input('a = '))
x = float(input('b = '))
all_sum = 0
k = 0
while True:
curr_sum = cos(a ** k + x ** k) / factorial(k ** 2)
k = k + 1
all_sum += curr_sum
if fabs(curr_sum) <= eps:
print('Sum = ', all_sum)
print('Additions count = ', k)
break
|
a44a818c3b1e2920f3370262d140cdca3f7721d9 | anti-Alz/leetcode-python | /232. Implement Queue using Stacks.py | 2,058 | 4.21875 | 4 | '''
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push
to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may
simulate a stack by using a list or deque (double-ended queue), as long as
you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek
operations will be called on an empty queue).
'''
class MyQueue:
def __init__(self):
'''
Initialize your data structure here.
'''
self.array = []
self.head, self.tail = 0, 0
def push(self, x):
'''
Push element x to the back of queue.
:type x: int
:rtype: void
'''
self.array.append(x)
self.tail += 1
def pop(self):
'''
Removes the element from in front of queue and returns that element.
:rtype: int
'''
if self.tail > self.head:
self.head += 1
return self.array[self.head-1]
else:
return None
def peek(self):
'''
Get the front element.
:rtype: int
'''
if self.tail > self.head:
return self.array[self.head]
else:
return None
def empty(self):
'''
Returns whether the queue is empty.
:rtype: bool
'''
if self.tail==self.head:
return True
else:
return False
def __str__(self):
return str(self.array[self.head:self.tail])
obj = MyQueue()
obj.push(3)
obj.push(4)
obj.push(5)
print(obj)
obj.pop()
print(obj)
obj.peek()
print(obj)
obj.push(6)
print(obj)
obj.empty()
'''
''' |
ba6e56383b9ff760e2403cfd7535e9f09f29ecf9 | Aadesh-Shigavan/Python_Daily_Flash | /Day 13/Program2.py | 342 | 4.09375 | 4 | ''' Program 2: Write a Program that accepts Two integers from user and prints the
series of factorial of all numbers between those two inputs. '''
num1, num2 = [int(i) for i in input("Input : ").split()]
for i in range(num1, num2 + 1):
fact = 1
for j in range(1, i + 1):
fact *= j
print("Fact of ", i, " = ", fact)
|
8af95c151a6feb1af56cb9a2b92d4bddf91d2e5d | nickwu241/coding-problems | /leetcode/235-lowest-common-ancestor-of-a-binary-search-tree.py | 549 | 3.734375 | 4 | # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
low = min(p.val, q.val)
high = max(p.val, q.val)
while not low <= root.val <= high:
root = root.left if root.val > high else root.right
return root
|
814cb1338a7da04658d43e513ab202534a4317ed | jeffchen/DailyCodingProblem | /problem21/solution.py | 1,202 | 3.671875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Snapchat.
Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
'''
def findMinimumRooms(arr):
arr = sorted(arr)
minRooms = 0
print arr
for i in xrange(len(arr)):
occupiedRooms = 0
for j in xrange(i):
if arr[i][0] < arr[j][1]:
occupiedRooms = occupiedRooms + 1
if occupiedRooms >= minRooms:
minRooms = minRooms + 1
return minRooms
def sorting(arr):
time = []
for x in arr:
time.append((x[0], 0))
time.append((x[1], 1))
return sorted(time)
def findMinimumRoomsFast(arr):
sortedArr = sorting(arr)
minRooms = 0
counter = 0
for x in sortedArr:
counter = counter + 1 if x[1] == 0 else counter - 1
if minRooms < counter:
minRooms = counter
return minRooms
inputArr = [(30, 75), (0, 50), (60, 150), (60, 70)]
#inputArr = [(1, 4), (5, 6), (8, 9), (2, 6)]
print findMinimumRoomsFast(inputArr)
|
a34cebfb50f8041f7a6ce3647aa830f0108f957f | jacobabrennan/space-shuttle-sim | /main.py | 1,886 | 3.6875 | 4 |
# - Game ----------------------------------------------------------------------
"""
This file is the main entry point for the game. Execute this file to play:
$ py main.py
The game is a 3D spaceship simulation. The user can fly a spaceship around a
sparsely populated solar system. The controls are as follows:
W+S: Pitch control (vertical view angle)
A+D: Yaw control (horizontal view angle)
Q+E: Roll control (rotates view screen)
Arrow Up + Down: Increase thrust, Decrease thrust
The Curses library is used throughout the project for input and output.
The game is mutithreaded, allowing for separate input and output threads
to execute concurrently. The game collects input from the player in real time,
updates the game world, and then updates a 3D game environment display. The
Game class is a singleton which handles all gameplay logic, while the Client
class is also a singleton handling input and display.
"""
# - Dependencies ---------------------------------
# Python Modules
import curses
import threading
import time
# Local Modules
from config import *
from client import get_client
from game import get_game
# - Create and start Game ------------------------
def main(standard_screen):
# Determine if shell is configured properly to play
size = standard_screen.getmaxyx()
if(size[1] < SCREEN_CHARACTER_WIDTH or size[0] < SCREEN_CHARACTER_HEIGHT):
print(MESSAGE_SCREEN_SIZE_CONDITION_NOT_MET)
exit(1)
# Configure Curses (shell display)
curses.curs_set(False) # Make the cursor invisible
curses.cbreak() # Make keyboard input non-breaking
standard_screen.keypad(True) # Enable use of arrow keys
# Create Client and Game
client = get_client(standard_screen)
game = get_game(standard_screen)
client.finished.wait()
exit(0)
# - Start Main ---------------------------------------
curses.wrapper(main)
|
5cab90a49611d104b97c0af2d17a9232b856ac36 | ervitis/challenges | /leetcode/factorial_trailing_zeroes/main.py | 333 | 4.1875 | 4 | """
Given an integer n, return the number of trailing zeroes in n!.
"""
def trailing_zeroes(n: int) -> int:
c = 0
while n > 0:
n //= 5
c += n
return c
if __name__ == '__main__':
print(trailing_zeroes(3))
print(trailing_zeroes(5))
print(trailing_zeroes(0))
print(trailing_zeroes(120))
|
56bcd22d6c7e02c78e6ebe7edc171d94f2f06388 | lyneca/ncss2017 | /roman_numerals.py | 1,743 | 3.703125 | 4 | import string
class RomanNumeral:
def __init__(self, i):
if isinstance(i, int) or i[0] in string.digits:
self.r = to_roman(int(i))
self.i = int(i)
else:
self.r = i.upper()
self.i = to_decimal(i.upper())
def __add__(self, o):
return RomanNumeral(self.i + o.i)
def __mul__(self, o):
return RomanNumeral(self.i * o.i)
def __str__(self):
return self.r + ' ({})'.format(self.i)
def __repr__(self):
return self.__str__()
numerals = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
r_numerals = {numerals[x]: x for x in numerals}
order = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
def to_roman(number):
out = ''
while number > 0:
for i in order:
if i <= number:
out += numerals[i]
number -= i
break
return out
def to_decimal(r):
r = r.upper()
i = 0
total = 0
while i < len(r):
if i + 1 < len(r):
if r_numerals[r[i]] < r_numerals[r[i+1]]:
total += r_numerals[r[i]+r[i+1]]
i += 1
else:
total += r_numerals[r[i]]
else:
total += r_numerals[r[i]]
i += 1
return total
def parse_calculation(e):
expr = e.split()
if expr[1] == '+':
return RomanNumeral(expr[0]) + RomanNumeral(expr[2])
elif expr[1] == '*':
return RomanNumeral(expr[0]) * RomanNumeral(expr[2])
if __name__ == '__main__':
print(parse_calculation(input('Enter the expression: ')).r)
|
3d72956e64d1306dee9080bcf33832627215f16b | MrTy13r/geekbrains_python_OkhitinLA | /Урок 3. Функции/Задание 3.1.py | 685 | 4.28125 | 4 | """3.1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль"""
def division(num1, num2):
if num2 == 0:
print("Делить на ноль нельзя, аллё")
else:
return int(num1 / num2)
user_number1 = int(input("Введите число-делимое: "))
user_number2 = int(input("Введите число-делитель: "))
print(division(user_number1, user_number2))
|
e625208e4d8af4cd5fc57564b527260056c63e83 | hyc12345hyc/hyc | /py_basic_exercises/chapter2/2-1suoyin.py | 650 | 4.34375 | 4 | #-*-coding:utf-*-
#根据给定的数字形式的年月日打印出日期。
months = ['January','February','March','April','May','June','July','August','September','October','November','December']
#以1~31的数字作为结尾的列表。
endings = ['st','nd','rd'] + 17 * ['th']\
+ ['st','nd','rd'] + 7 * ['th']\
+ ['st']
year = raw_input('Year: ')
month = raw_input('Month(1~12): ')
day = raw_input('Day(1~31):')
month_number = int(month)
day_number = int(day)
#月份和天数要减一,以获得正确的索引。
month_name = months[month_number - 1]
ordinal = day + endings[day_number - 1]
print month_name + ' ' + ordinal + '. ' + year
|
26bda2145ace52e26f85c701c03dd796851fb847 | Thorarinng/prog_01_kaflaverkefni | /timaverkefni/12-5.py | 2,019 | 3.8125 | 4 | #12-5 GAME OF EIGHTS
#game_of_eights() function goes here
def game_of_eights(i_list):
"""athugar hvort 8 se lika i saetinu a undan"""
is_eight = False
# i_list = change_to_ints(nlist)
for i in range(len(i_list)):
if i_list[i] == 8 and i_list[i-1] == 8:
is_eight = True
print(is_eight)
def main():
a_list = input("Enter elements of list separated by commas: ").split(',')
# remainder of main() goes here
# i_list = change_to_ints(a_list)
i_list = []
try:
for s_num in a_list:
num = int(s_num)
i_list.append(num)
except:
print("Error. Please enter only integers.")
return
game_of_eights(i_list)
main()
############################################################################
# def change_to_ints(nlist):
# """Breytir listann i ints"""
# i_list = []
# try:
# for s_num in nlist:
# num = int(s_num)
# i_list.append(num)
# except:
# print("Error. Please enter only integers")
# exit
# return i_list
# def main():
# a_list = input("Enter elements of list separated by commas: ").split(',')
# # remainder of main() goes here
# # i_list = change_to_ints(a_list)
# i_list = []
# try:
# for s_num in a_list:
# num = int(s_num)
# i_list.append(num)
# except:
# print("Error. Please enter only integers")
# return
# game_of_eights(i_list)
# main()
# def game_of_eights(alist):
# eights = False
# prev = '0'
# for i in alist:
# try:
# i = int(i)
# i = str(i)
# except:
# print("Error. Please enter only integers.")
# return
# if i == '8' and prev == '8':
# eights = True
# prev = i
# print(eights)
# def main():
# a_list = input("Enter elements of list separated by commas: ").split(',')
# game_of_eights(a_list)
# main() |
c74dad953f8a1435fe6c0c270a9858ef9992c8cc | KShaz/Machine-Learning-Basics | /python code/ANN 2-1 OR-Sigmoid.py | 1,007 | 4 | 4 | import numpy as np
def Sigmoid(x):
return 1/(1+np.exp(-x))
def Sigmoid_deriv(x):
return x*(1-x)
# input dataset
X = np.array([ [0,0],
[0,1],
[1,0],
[1,1] ])
# output dataset
y = np.array([[0],[1],[1],[1]])
# seed random numbers to make calculation deterministic. (1) is the sequence used for random
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((2,1)) - 1 # random=[0,1], we want weight=[-1,1], random(line,column), syn0 is vertical
l0 = X
for iter in range(10000):
# forward propagation
S = Sigmoid(np.dot(l0,syn0)) #l1 = nonlin (l0 x syn0), matrix-matrix multiplication
# how much did we miss?
l1_error = y - S
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
l1_delta = l1_error * Sigmoid_deriv(S)
# update weights
syn0 = syn0 + np.dot(l0.T,l1_delta)
print ("Output After Training:")
print (S)
|
9aca842a286eae90d60176aa46d9261b2a0f2562 | sas342/hackerRank | /datastructures/Stacks.py | 6,215 | 3.5625 | 4 | '''
Created on Jun 11, 2016
@author: sstimmel
'''
class BalancedParen():
def __init__(self):
self.balanced = True
self.stack1 = []
def nextchar(self, char):
if self.balanced == False:
return
if char == '{' or char == '[' or char == '(':
self.stack1.append(char)
elif char == '}' or char == ']' or char == ')':
try:
d = self.stack1.pop()
if char == '}' and d != '{':
self.balanced = False
elif char == ']' and d != '[':
self.balanced = False
elif char == ')' and d != '(':
self.balanced = False
except:
self.balanced = False
def isBalanced(self):
if not self.balanced:
print "NO"
return
if len(self.stack1) == 0:
print "YES"
return
print "NO"
class MaxStack():
maxStack = []
allStack = []
def push(self, number):
self.allStack.append(number)
size = len(self.maxStack)
if size == 0:
self.maxStack.append(number)
elif self.maxStack[size-1] <= number:
self.maxStack.append(number)
def delete(self):
num = self.allStack.pop()
size = len(self.maxStack)
if self.maxStack[size-1] == num:
self.maxStack.pop()
def printMax(self):
size = len(self.maxStack)
print self.maxStack[size-1]
class MaxRectangle():
def __init__(self):
self.stack = []
self.max = 0
def insert(self, number, index):
#if num < top, keep popping until <=
#calculate size for popped entries and store max if needed
currentSize = len(self.stack)
lastStart = None
while currentSize > 0 and self.stack[currentSize-1].val > number:
r = self.stack.pop()
print "popping of ",r.val, "at start",r.start
m = r.val * (index - r.start)
lastStart = r.start
if m > self.max:
self.max = m
print "new max is ",self.max
currentSize = currentSize - 1
if lastStart != None:
r = Rect(number, lastStart)
self.stack.append(r)
if lastStart == None and (currentSize == 0 or self.stack[currentSize-1].val < number):
r = Rect(number, index)
self.stack.append(r)
print "adding ",r.val
def getMax(self, index):
while len(self.stack) > 0:
try:
r = self.stack.pop()
possibleMax = r.val * (index - r.start)
print "computing ",r.val, "start = ",r.start," end is ",index
if possibleMax > self.max:
self.max = possibleMax
except:
pass
return self.max
class Rect():
def __init__(self, val, start):
self.val = val
self.start = start
class TextEditor():
def __init__(self):
self.operations = []
self.w = ""
def add(self, value):
self.w = self.w + value
def delete(self, number):
self.w = self.w[0:len(self.w)-int(number)]
def printKth(self, k):
print self.w[int(k)-1]
def undo(self):
op = self.operations.pop()
self.performCalc(op, False)
# print self.w
def performCalc(self, operation, add=True):
tmp = operation.strip().split(' ')
action = tmp[0]
if action != '4':
val = tmp[1]
if add and (action == '1' or action == '2'):
if action == '1':
l = len(val)
self.operations.append('2 '+str(l))
elif action == '2':
x = self.w[len(self.w)-int(val):]
self.operations.append('1 '+x)
if action == '1':
self.add(val)
elif action == '2':
self.delete(val)
elif action == '3':
self.printKth(val)
elif action == '4':
self.undo()
class Poison():
def __init__(self):
self.stack = []
def findMaxNumberOfDays(self, array):
maxN = 0
for i in array:
iv = int(i)
daysAlive = 0
if len(self.stack) == 0:
self.stack.append([iv, daysAlive])
#print "current is ",iv
print self.stack
while len(self.stack) > 0 and iv <= self.stack[len(self.stack)-1][0]:
daysAlive = max(daysAlive, self.stack.pop()[1])
#if stack is empty, set days alive to 0
if len(self.stack) == 0:
daysAlive = 0
else:
daysAlive = daysAlive + 1
#print "days alive ",daysAlive
maxN = max(maxN, daysAlive)
self.stack.append([iv, daysAlive])
return maxN
#maxstack = MaxStack()
#N = input()
# for i in range(0, N):
# tmp = raw_input().strip().split(' ')
# if int(tmp[0]) == 1:
# maxstack.push(int(tmp[1]))
# elif int(tmp[0]) == 2:
# maxstack.delete()
# else:
# maxstack.printMax()
#N = input()
# for i in range(0, N):
# p = BalancedParen()
# tmp = raw_input()
# for c in tmp:
# p.nextchar(c)
#
# p.isBalanced()
#rect
# n = input()
# tmp = raw_input().strip().split(' ')
# i=1
# maxR = MaxRectangle()
# for h in tmp:
# maxR.insert(int(h), i)
# i = i+1
# print maxR.getMax(i)
#
# n = input()
# t = TextEditor()
# for x in xrange(n):
# i = raw_input().strip()
# t.performCalc(i)
n = input()
p = Poison()
tmp = raw_input().strip().split(' ')
print p.findMaxNumberOfDays(tmp)
|
cd7e90e197f912a9fd67d302d59232bd7980f8d9 | lokeshkumar9600/python_train | /dct1.py | 162 | 3.8125 | 4 | me = {"name" : "lokesh" , "age" : 18}
print(me)
print(me["name"] , me["age"])
me["age"]=19
print(me) #updated dict
me.pop("name")
print(me)
me.clear()
print(me)
|
6d50c296b96e8642e28587c53102aae41a9b4469 | SeongHyukJang/HackerRank | /Python/Regex and Parsing/Regex Substitution.py | 232 | 3.71875 | 4 | import re
string = ''
n = int(input())
for i in range(n):
line = input()
res1 = re.sub(r'(\s)(&&)(?=\s)', ' and',line)
res2 = re.sub(r'(\s)(\|\|)(?=\s)', ' or', res1)
string += res2
string += '\n'
print(string) |
0e0db3d5f8e14200b1996aaacac96100b46da261 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4148/codes/1800_2567.py | 111 | 3.921875 | 4 |
j = int(input("numero: "))
for i in range(j):
print((j-i)*"*" )
for i in range(j):
print((i + 1)*'*')
|
72b220305ffbc210100b8d6f0786784232c02877 | Prakort/competitive_programming | /flatten-binary-tree-to-linked-list.py | 514 | 3.65625 | 4 | class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.helper(root)
def helper(self,root):
if not root:
return None
if not root.right and not root.left:
return root
left = self.helper(root.left)
right = self.helper(root.right)
if left:
left.right = root.right
root.right = root.left
root.left = None
return right if right else left
|
ec0616524fda3c75b55d6e3c35d9ddf2faa17bfb | kakkarotssj/Algorithms | /Greedy/union_find_detect_cycle.py | 903 | 3.90625 | 4 | from collections import defaultdict
graph = defaultdict(list)
def addedge(node1, node2):
graph[node1].append(node2)
graph[node2].append(node1)
vertices_count = 5
addedge(0, 1)
addedge(0, 2)
addedge(1, 3)
addedge(1, 4)
addedge(3, 4)
def findparent(parent, node):
if parent[node] == -1:
return node
else:
return findparent(parent, parent[node])
def union(parent, n1set, n2set):
parent[n1set] = n2set
def iscyclic(graph, vertices_count):
parent = [-1] * vertices_count
visited = [False] * vertices_count
for n1 in range(vertices_count):
for n2 in graph[n1]:
if not visited[n2]:
n1set = findparent(parent, n1)
n2set = findparent(parent, n2)
if n1set == n2set:
return True
else:
union(parent, n1set, n2set)
visited[n1] = True
return False
if iscyclic(graph, vertices_count):
print "Graph contains a cycle"
else:
print "Graph does not contain a cycle" |
59a08272be6a31ccdec8d1892d5e893c7afe9892 | kaustav1996/networking- | /kaustav networking/networkin.py | 571 | 3.59375 | 4 | print("Enter Bit Sequence: \n")
s=raw_input()
flag=0
x=list()
for i in range(len(s)):
x.append(s[i])
if(s[i]=="1"):
flag=flag+1
else:
flag=0
if(flag==3):
x.append("0")
flag=0
y="".join(x)
print("message sent: "+y)
z=list()
i=0
while(i<len(y)):
z.append(y[i])
if(y[i]=="1"):
flag=flag+1
else:
flag=0
if(flag==3):
if(y[i+1]=="0"):
i=i+1
flag=0
else:
flag=2
i=i+1
w="".join(z)
print("message recieved:"+w)
|
8df45c4b31d033e88d3909d662eecd8e6475ca68 | jooonyliks/Album-photo-viewer | /PhotoAlbum/media/demand.py | 1,786 | 4.09375 | 4 | # A program that deals with demand
# getting cross elasticity of demand
def crossElastcityofDemand():
'''This is a program that gets the cross elasticity of two products requires the // change in quantity demanded of product x//the original quantity of product x //change in price of product y//the original price of product y'''
# PRODUCT X
newQuantityFx= int(input("Please enter the new quantity of product x:" ))
originalQuantityFx = int(input("Please enter the original quantity of product x:" ))
changeQuantityFx = newQuantityFx - originalQuantityFx
#PRODUCT Y
newPRICEFy = int(input("Please enter the new price of product y:" ))
originalPRICEFy = int(input("Please enter theoriginal price of product y:" ))
changePriceyFy = newPRICEFy - originalPRICEFy
CED = changeQuantityFx/originalQuantityFx * changePriceyFy/originalPRICEFy
print("The cross elasticity of the two goods are {}".format(CED))
if CED >= 0:
print("The two goods are substitutes")
elif CED <= 0:
print("The two goods are complimentary")
else:
print("The two goods are independent")
# crossElastcityofDemand()
def changeofBaseFormula():
'''
This is a program that changes the base formola in q logarithimic situations ===>
LOG-b[N] = LOG-a[N]/LOG-a[b] //where a is the new base
'''
import math
logbase = int(input("Please enter the initial base:"))
logNumber = int(input("Please enter the number of the log:"))
print("The log you want to conVert is=\n LOG-{}[{}]".format(logbase,logNumber))
newbase = int(input("Please enter the new base you want:"))
x = math.log(logNumber,newbase) / math.log(logbase,newbase)
print(changeofBaseFormula.__doc__)
print("The converted log is \n LOG-{}[{}]".format(newbase,x))
changeofBaseFormula() |
d9d09bba2ad08685272c1c96a4ccb13b1ba851b3 | CristofherAndres/Codigos_Python | /ejercicio_propuesto6.py | 641 | 3.953125 | 4 | #Datos de entrada
dinero = int(input("Ingrese el dinero: "))
b10 = dinero//10000
dinero = dinero%10000
print("Billetes de 10.000:",b10)
b5 = dinero//5000
dinero = dinero%5000
print("Billetes de 5.000:",b5)
b1 = dinero//1000
dinero = dinero%1000
print("Billetes de 1.000:",b1)
m500 = dinero//500
dinero = dinero%500
print("Moneda de 500:",m500)
m100 = dinero//100
dinero = dinero%100
print("Moneda de 100:",m100)
m50 = dinero//50
dinero = dinero%50
print("Moneda de 50:",m50)
m10 = dinero//10
dinero = dinero%10
print("Moneda de 10:",m10)
m5 = dinero//5
dinero = dinero%5
print("Moneda de 5:",m5)
m1 = dinero
print("Moneda de 1:",m1) |
66fd6cb1853a18cdf7affdc308bdefcd66500dbf | realbakari/python-program | /Random/Anti-median/test.py | 1,491 | 3.84375 | 4 | # Author: Bakari Mustafa, contact@bakarimustafa.com
from main import anti_median_permutation
# Test case 1
# There is only one test case with n = 2.
# The permutation is given as [1, -1], which means that the first element
# is given and the second element is unknown.
# There is only one anti-median permutation in this case, which is [1, 2].
assert anti_median_permutation(2, [1, -1]) == 1
# Test case 2
# There are two test cases with n = 4.
# In the first test case, the permutation is given as [1, 2, -1, -1], which
# means that the first two elements are given and the last two elements are
# unknown.
# There are two anti-median permutations in this case, which are [1, 2, 3, 4]
# and [1, 2, 4, 3].
# In the second test case, the permutation is given as [-1, -1, -1, -1], which
# means that all elements are unknown.
# There are six anti-median permutations in this case, which are [1, 2, 3, 4],
# [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], and [1, 4, 3, 2].
assert anti_median_permutation(4, [1, 2, -1, -1]) == 2
assert anti_median_permutation(4, [-1, -1, -1, -1]) == 6
# Test case 3
# There is only one test case with n = 6.
# The permutation is given as [1, 2, 3, -1, -1, -1], which means that the
# first three elements are given and the last three elements are unknown.
# There are four anti-median permutations in this case, which are
# [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 6, 5], [1, 2, 3, 5, 4, 6], and
# [1, 2, 3, 5, 6, 4].
assert anti_median_permutation(6, [1, 2, 3, -1, -1, -1]) == 4
|
faafc54a60b70eccd0334d07eee209e53a386bbc | botaoap/DesenvolvimentoPython_Botao_2020 | /Revisao/Exercicio08/ex5.py | 176 | 4 | 4 | # Faça um programa que mostre a tabuada do 8 na tela.
# Lembrando que a tabuada é de 0 a 10
for i in range(10):
tabuada = 8 * (i+1)
print(f"8 X {i+1} = {tabuada}")
|
979ae11d0a020f4994bce73e2246b1bc54051781 | MerlynAllen/JLU-VPN | /vpn.py | 1,129 | 3.53125 | 4 | '''
Generate a url to JiLin University VPN
'''
import urllib.parse, os
key = [0x6f, 0x68, 0xde, 0x3, 0xb8, 0xaf, 0xf7, 0xcf, 0xe1, 0x97, 0x16, 0x33, 0x7, 0xca, 0xbc, 0xaa, 0xc6]
meaningless_bullshit = '77726476706e69737468656265737421'
def generate(origin: str):
info = urllib.parse.urlparse(origin)
host = info.hostname
print(info)
print('Original Host Name : %s' % host)
tmp = []
for i in range(len(host)):
tmp.append(hex(ord(host[i]) ^ 0xff ^ key[i])[2:])
for index, t in enumerate(tmp):
if len(t) < 2:
tmp[index] = '0' + t
print(tmp)
text = ''.join(tmp)
print(text)
full = 'https://vpns.jlu.edu.cn/' + info.scheme + '/' + meaningless_bullshit + text + info.path
if info.params:
full += '?' + info.params
if info.query:
full += '?' + info.query
if info.fragment:
full += '#' + info.fragment
return full
if __name__ == '__main__':
while 1:
query = input('Please input url you want to convert:\n')
result = generate(query)
print(result)
os.system('start ' + result)
input()
|
afbb935c4dd7438adac5784ffc4a0f9ce83a48a9 | VillaEdwar/Ciclo_1_MisionTic2022_Python | /Unidad_2/reto_completo_2.py | 2,617 | 4.125 | 4 | #Utilizando python, escriba una función que
# reciba como parámetro un diccionario en el cuál
# las llaves son los nombres de las variables mencionadas anteriormente. Retorne un nuevo
# diccionario con las llaves “banco”, “usuario” y “mensaje” dónde esta última tenga como
# valor una variable de tipo “str” que muestre el mensaje de cada una de las condiciones.
#definicion de funcion
def cajero(informacion: dict)->dict: # Debe devolver un diccionario
#str
p1 = str(informacion["banco"])
p2 = str(informacion["usuario"])
#int
p3 = int(informacion["clave"])
p4 = int(informacion["retiro"])
p5 = int(informacion["saldo_inicial"])
p6 = int(informacion["nuevo_saldo"])
mensaje = str("mensaje")
# Creacion del diccionario de salida
nuevo_diccionario:dict = {
"banco": p1,
"usuario": p2,
"mensaje": mensaje
}
# Verifica si la clave es correcta
if p3 == 1234:
# Condiciona si el saldo a retirar es mayor a 200000
if p4 > 200000:
p4 = p4 + 2000
# Si el saldo inicial es menor que el saldo a retirar entonces continua
if p4 <= p5:
# El nuevo saldo sera
p6 = p5 - p4
# Asigna un nuervo valor a la llave "mensaje" en el diccionario informacion
nuevo_diccionario["mensaje"] = "Su saldo actual es: {} Muchas Gracias!".format(p6)
else:
# Asigna un nuervo valor a la llave "mensaje" en el diccionario informacion
nuevo_diccionario["mensaje"] = "El valor solicitado más el costo de la transacción es mayor al saldo"
else:
# Si el saldo inicial es menor que el saldo a retirar entonces continua
if p4 <= p5:
p6 = p5 - p4
# Asigna un nuervo valor a la llave "mensaje" en el diccionario informacion
nuevo_diccionario["mensaje"] = "Su saldo actual es: {} Muchas Gracias!".format(p6)
else:
# Asigna un nuervo valor a la llave "mensaje" en el diccionario informacion
nuevo_diccionario["mensaje"] = "El valor solicitado es mayor al saldo actual"
else:
# Asigna un nuervo valor a la llave "mensaje" en el diccionario informacion
nuevo_diccionario["mensaje"] = "Clave incorrecta"
return nuevo_diccionario
informacion:dict = {
"banco": "Banco ABC",
"usuario": "Carlos",
"clave": 1234,
"retiro": 798000,
"saldo_inicial": 800000,
"nuevo_saldo": 0
}
print(cajero(informacion)) |
70f5d24ff721f6d993ad22312a2054a57be2e7e5 | Magneet/CodeConnect_2021_Samples | /vmware_horizon.py | 264,965 | 3.59375 | 4 | import json, requests, ssl, urllib
from typing import get_args
class Connection:
"""The Connection class is used to handle connections and disconnections to and from the VMware Horizon REST API's"""
def __init__(self, username: str, password: str, domain: str, url:str):
""""The default object for the connection class needs to be created using username, password, domain and url in plain text."""
self.username = username
self.password = password
self.domain = domain
self.url = url
self.access_token = ""
self.refresh_token = ""
def hv_connect(self):
"""Used to authenticate to the VMware Horizon REST API's"""
headers = {
'accept': '*/*',
'Content-Type': 'application/json',
}
data = {"domain": self.domain, "password": self.password, "username": self.username}
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/login', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
data = response.json()
self.access_token = {
'accept': '*/*',
'Authorization': 'Bearer ' + data['access_token']
}
self.refresh_token = data['refresh_token']
return self
def hv_disconnect(self):
""""Used to close close the connection with the VMware Horizon REST API's"""
headers = {
'accept': '*/*',
'Content-Type': 'application/json',
}
data = {'refresh_token': self.refresh_token}
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/logout', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
class Inventory:
def __init__(self, url: str, access_token: dict):
"""Default object for the pools class where all Desktop Pool Actions will be performed."""
self.url = url
self.access_token = access_token
def get_desktop_pools(self) -> list:
"""Returns a list of dictionaries with all available Desktop Pools.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_desktop_pool(self, desktop_pool_id: str) -> dict:
"""Gets the Desktop Pool information.
Requires id of a desktop pool
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_desktop_pool_installed_applications(self, desktop_pool_id: str) -> list:
"""Lists the installed applications on the given desktop pool.
Requires id of a desktop pool
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/installed-applications', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_farms(self) -> list:
"""Lists the Farms in the environment.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/farms', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_farm(self, farm_id:str) -> dict:
"""Gets the Farm information.
Requires id of a RDS Farm
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/farms/{farm_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_farm_installed_applications(self, farm_id:str) -> list:
"""Lists the installed applications on the given farm.
Requires id of a RDS Farm
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/farms/{farm_id}/installed-applications', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_farm(self,farm_data:dict):
"""Creates a farm.
Requires farm_data as a dict
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(farm_data)
response = requests.post(f'{self.url}/rest/inventory/v1/farms', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code == 401:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code == 409:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_farm(self,farm_data : dict, farm_id : str):
"""Updates a farm.
Requires farm_data as a dict
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(farm_data)
response = requests.put(f'{self.url}rest/inventory/v1/farms/{farm_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code == 401:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_farm(self, farm_id:str) -> list:
"""Deletes a farm.
Requires id of a RDS Farm
Available for Horizon 8 2103 and later."""
response = requests.delete(f'{self.url}/rest/inventory/v1/farms/{farm_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def check_farm_name_availability(self,farm_name: str)-> dict:
"""Checks if the given name is available for farm creation.
Requires the name of the RDS farm to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = farm_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/farms/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_machine(self, machine_id:str) -> dict:
"""Gets the Machine information.
Requires id of a machine
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/machines/{machine_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_machines(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the Machines in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2006 and later."""
def int_get_machines(self, page:int, maxpagesize: int, filter:dict="") ->list:
if filter != "":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"{filter_url}"
response = requests.get(f'{self.url}/rest/inventory/v1/machines?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/machines?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_machines(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_machines(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def delete_machine(self, machine_id:str, delete_from_multiple_pools:bool=False, force_logoff:bool=False, delete_from_disk:bool=False):
"""Deletes a machine.
Requires id of the machine to delete machine
Optional arguments (all default to False): delete_from_multiple_pools, force_logoff and delete_from_disk
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data={}
data["allow_delete_from_multi_desktop_pools"] = delete_from_multiple_pools
data["archive_persistent_disk"] = False
data["delete_from_disk"] = delete_from_disk
data["force_logoff_session"] = force_logoff
json_data = json.dumps(data)
response = requests.delete(f'{self.url}/rest/inventory/v1/machines/{machine_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def delete_machines(self, machine_ids:list, delete_from_multiple_pools:bool=False, force_logoff:bool=False, delete_from_disk:bool=False):
"""deletes the specified machines
Requires list of ids of the machines to remove
Optional arguments (all default to False): delete_from_multiple_pools, force_logoff and delete_from_disk
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data={}
machine_delete_data={}
machine_delete_data["allow_delete_from_multi_desktop_pools"] = delete_from_multiple_pools
machine_delete_data["archive_persistent_disk"] = False
machine_delete_data["delete_from_disk"] = delete_from_disk
machine_delete_data["force_logoff_session"] = force_logoff
data["machine_delete_data"] = machine_delete_data
data["machine_ids"] = machine_ids
json_data = json.dumps(data)
response = requests.delete(f'{self.url}/rest/inventory/v1/machines', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def machines_enable_maintenance_mode(self, machine_ids:list):
"""Puts a machine in maintenance mode.
Requires a List of Machine Ids representing the machines to be put into maintenance mode.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/enter-maintenance', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def machines_exit_maintenance_mode(self, machine_ids:list):
"""Takes a machine out of maintenance mode.
Requires a List of Machine Ids representing the machines to be taken out of maintenance mode.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/exit-maintenance', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def rebuild_machines(self, machine_ids:list):
"""Rebuilds the specified machines.
Requires a List of Machine Ids representing the machines to be rebuild.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/rebuild', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def recover_machines(self, machine_ids:list):
"""Recovers the specified machines.
Requires a List of Machine Ids representing the machines to be recovered.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/recover', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def reset_machines(self, machine_ids:list):
"""Resets the specified machines.
Requires a List of Machine Ids representing the machines to be reset.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/reset', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def restart_machines(self, machine_ids:list):
"""Restarts the specified machines.
Requires a List of Machine Ids representing the machines to be restarted.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/restart', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def check_machine_name_availability(self,machine_name: str)-> dict:
"""Checks if the given name is available for machine creation.
Requires the name of the application to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = machine_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_sessions(self, filter:dict="", maxpagesize:int=100) -> list:
"""Lists the Session information in the environment.
Will default to 1000 results with a pagesize of 100, max pagesize is 1000.
Available for Horizon 8 2006 and later, filtering available since Horizon 2103."""
def int_get_sessions(self, page:int, maxpagesize: int, filter:dict="") ->list:
if filter !="":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"{filter_url}"
response = requests.get(f'{self.url}/rest/inventory/v1/sessions?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/sessions?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
# response = requests.get(f'{self.url}/rest/inventory/v1/sessions?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_sessions(self,page = page, maxpagesize= maxpagesize, filter= filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_sessions(self,page = page, maxpagesize= maxpagesize, filter= filter)
results += response.json()
return results
def get_session(self, session_id: str) -> dict:
"""Gets the Session information.
Requires session_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/sessions/{session_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def disconnect_sessions(self, session_ids: list):
"""Disconnects user sessions.
Requires list of session ids
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(session_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/sessions/action/disconnect', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def logoff_sessions(self, session_ids: list, forced_logoff:bool=False):
"""Logs user sessions off.
Requires list of session ids optional to set forced to True to force a log off (defaults to False)
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(session_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/sessions/action/logoff?forced={forced_logoff}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def reset_session_machines(self, session_ids: list):
"""Resets machine of user sessions. The machine must be managed by Virtual Center and the session cannot be an application or an RDS desktop session.
Requires list of session ids
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(session_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/sessions/action/reset', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def restart_session_machines(self, session_ids: list):
"""Restarts machine of user sessions. The machine must be managed by Virtual Center and the session cannot be an application or an RDS desktop session.
Requires list of session ids
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(session_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/sessions/action/reset', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def send_message_sessions(self, session_ids: list, message:str, message_type:str="INFO"):
"""Sends the message to user sessions
Requires list of session ids, message type (INFO,WARNING,ERROR) and a message
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data={}
data["message"] = message
data["message_type"] = message_type
data["session_ids"] = session_ids
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/sessions/action/send-message', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_messages"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_application_pools(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the application pools in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2006 and later."""
def int_get_application_pools(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"?filter={filter_url}"
response = requests.get(f'{self.url}/rest/inventory/v1/application-pools{add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/application-pools?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_application_pools(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_application_pools(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_application_pool(self, application_pool_id: str) -> dict:
"""Gets a single Application pool
Requires Application_pool_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/application-pools/{application_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_application_pool(self,application_pool_data:dict):
"""Creates an application pool.
Requires application_pool_data as a dict
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_data)
response = requests.post(f'{self.url}/rest/inventory/v1/application-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_application_pool(self, application_pool_id:str, application_pool_data:dict):
"""Updates an application pool.
The following keys are required to be present in the json: multi_session_mode, executable_path and enable_pre_launch
Requires ad_domain_id, username and password in plain text.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_data)
response = requests.put(f'{self.url}/rest/inventory/v1/application-pools/{application_pool_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_messages"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 401:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_application_pool(self,application_pool_id:str):
"""Deletes an application pool.
Requires application_pool_id as a str
Available for Horizon 8 2006 and later."""
response = requests.delete(f'{self.url}/rest/inventory/v1/application-pools/{application_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 401:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def get_application_icons(self, application_pool_id: str) -> list:
"""Lists the application icons for the given application pool.
Requires Application_pool_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/application-icons?application_pool_id={application_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_application_icon(self, application_icon_id: str) -> dict:
"""Gets application icon
Requires application_icon_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/application-icons/{application_icon_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_application_icon(self,data : str,height : str,width : str) -> dict:
"""Creates an application icon.
Requires data, width and height as string
Data needs to be Base64 encoded binary data of the image
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
raw_data={}
raw_data["data"] = data
raw_data["height"] = height
raw_data["width"] = width
json_data = json.dumps(raw_data)
response = requests.post(f'{self.url}/rest/inventory/v1/application-icons', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def set_application_pool_icon(self,application_pool_id : str, icon_id : str):
"""Associates a custom icon to the application pool.
Requires application_pool_id and asicon_id as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data={}
data["icon_id"] = icon_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/application-pools/{application_pool_id}/action/add-custom-icon', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 401:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_application_pool_icon(self,application_pool_id : str):
"""Removes the associated custom icon from the application pool.
Requires application_pool_id as string
Available for Horizon 8 2103 and later."""
response = requests.post(f'{self.url}/rest/inventory/v1/application-pools/{application_pool_id}/action/remove-custom-icon', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 401:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def remove_machines(self, desktop_pool_id:str,machine_ids: list):
"""Removes machines from the given manual desktop pool.
Requires list of machine_ids and desktop_pool_id to remove them from
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/action/remove-machines', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def add_machines(self, desktop_pool_id:str,machine_ids: list):
"""Adds machines to the given manual desktop pool.
Requires list of machine_ids and desktop_pool_id to add them to
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/action/add-machines', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def add_machines_by_name(self, desktop_pool_id:str, machine_data: list):
"""Adds machines to the given manual desktop pool.
Requires requires desktop_pool_id and list of of dicts where each dict has name and user_id.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(machine_data)
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/action/add-machines-by-name', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def assign_user_to_machine(self, machine_id:str, user_ids: list):
"""Assigns the specified users to the machine.
Requires machine_id of the machine and list of user_ids.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(user_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/{machine_id}/action/assign-users', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def unassign_user_to_machine(self, machine_id:str, user_ids: list):
"""Unassigns the specified users to the machine.
Requires machine_id of the machine and list of user_ids.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(user_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/machines/{machine_id}/action/unassign-users', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_desktop_entitlement(self, global_desktop_entitlement_id:str) -> dict:
"""Gets the Global Desktop Entitlement in the environment.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-desktop-entitlements/{global_desktop_entitlement_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_desktop_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the Global Application Entitlements in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2006 and later."""
def int_get_global_desktop_entitlements(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/inventory/v1/global-desktop-entitlements?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/global-desktop-entitlements?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_global_desktop_entitlements(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_global_desktop_entitlements(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def add_global_desktop_entitlement(self, global_desktop_entitlement_data: dict):
"""Creates a Global Desktop Entitlement.
Requires global_desktop_entitlement_data as a dict
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(global_desktop_entitlement_data)
response = requests.post(f'{self.url}/rest/inventory/v1/global-desktop-entitlements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_global_desktop_entitlement_compatible_desktop_pools(self, global_desktop_entitlement_id:str) -> list:
"""Lists Local Application Pools which are compatible with Global Application Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-desktop-entitlements/{global_desktop_entitlement_id}/compatible-local-desktop-pools', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def add_global_desktop_entitlement_local_desktop_pools(self, global_desktop_entitlement_id:str, desktop_pool_ids: list):
"""Adds a local desktop pool to a GLobal desktop Entitlement
Requires global_desktop_entitlement_id as a string and desktop_pool_ids as a list
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(desktop_pool_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/global-desktop-entitlements/{global_desktop_entitlement_id}/local-desktop-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_desktop_entitlement_local_desktop_pools(self, global_desktop_entitlement_id:str) -> list:
"""Lists Local Desktop Pools which are assigned to Global Desktop Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-desktop-entitlements/{global_desktop_entitlement_id}/local-desktop-pools', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def remove_global_desktop_entitlement_local_desktop_pools(self, global_desktop_entitlement_id:str, desktop_pool_ids: list):
"""Removes Local Desktop Pools from Global Desktop Entitlement.
Requires global_desktop_entitlement_id as a string and desktop_pool_ids as a list
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(desktop_pool_ids)
response = requests.delete(f'{self.url}/rest/inventory/v1/global-desktop-entitlements/{global_desktop_entitlement_id}/local-desktop-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_application_entitlement(self, global_application_entitlement_id:str) -> dict:
"""Gets the Global Application Entitlement in the environment.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-application-entitlements/{global_application_entitlement_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_application_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the Global Application Entitlements in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2006 and later."""
def int_get_global_application_entitlements(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/inventory/v1/global-application-entitlements?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/global-application-entitlements?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_global_application_entitlements(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_global_application_entitlements(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_global_application_entitlement_compatible_application_pools(self, global_application_entitlement_id:str) -> list:
"""Lists Local Application Pools which are compatible with Global Application Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-application-entitlements/{global_application_entitlement_id}/compatible-local-application-pools', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def add_global_application_entitlement_local_Application_pools(self, global_application_entitlement_id:str, application_pool_ids: list):
"""Adds a local Application pool to a GLobal Application Entitlement
Requires global_application_entitlement_id as a string and application_pool_ids as a list
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_ids)
response = requests.post(f'{self.url}/rest/inventory/v1/global-application-entitlements/{global_application_entitlement_id}/local-application-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_application_entitlement_local_Application_pools(self, global_application_entitlement_id:str) -> list:
"""Lists Local Application Pools which are assigned to Global Application Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/global-application-entitlements/{global_application_entitlement_id}/local-application-pools', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def remove_global_application_entitlement_local_Application_pools(self, global_application_entitlement_id:str, application_pool_ids: list):
"""Removes Local Application Pools from Global Application Entitlement.
Requires global_application_entitlement_id as a string and application_pool_ids as a list
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_ids)
response = requests.delete(f'{self.url}/rest/inventory/v1/global-application-entitlements/{global_application_entitlement_id}/local-application-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def desktop_pool_push_image(self, desktop_pool_id:str, start_time:str, add_virtual_tpm:bool=False, im_stream_id:str="",im_tag_id:str="",logoff_policy:str="WAIT_FOR_LOGOFF",parent_vm_id:str="",snapshot_id:str="", stop_on_first_error:bool=True):
"""Schedule/reschedule a request to update the image in an instant clone desktop pool
Requires start_time in epoch, desktop_pool_id as string and either im_stream_id and im_tag_id OR parent_vm_id and snapshit_id as string.
Optional: stop_on_first_error as bool, add_virtual_tpm as bool, logoff_policy as string with these options: FORCE_LOGOFF or WAIT_FOR_LOGOFF
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
if add_virtual_tpm !=False:
data["add_virtual_tpm"] = add_virtual_tpm
if im_stream_id != "" and im_tag_id !="":
data["im_stream_id"] = im_stream_id
data["im_tag_id"] = im_tag_id
data["logoff_policy"] = logoff_policy
if parent_vm_id != "" and snapshot_id !="":
data["parent_vm_id"] = parent_vm_id
data["snapshot_id"] = snapshot_id
data["start_time"]= start_time
data["stop_on_first_error"] = stop_on_first_error
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/action/schedule-push-image', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def cancel_desktop_pool_push_image(self, desktop_pool_id:str):
"""Lists Local Application Pools which are assigned to Global Application Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/action/cancel-scheduled-push-image', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_rds_servers(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the RDS Servers in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2012 and later."""
def int_get_rds_servers(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/inventory/v1/rds-servers?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/rds-servers?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_rds_servers(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_rds_servers(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_rds_server(self, rds_server_id:str) -> dict:
"""Gets the RDS Server information.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/rds-servers/{rds_server_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def delete_rds_server(self, rds_server_id:str) -> dict:
"""Deletes the RDS Server.
Available for Horizon 8 2012 and later."""
response = requests.delete(f'{self.url}/rest/inventory/v1/rds-servers/{rds_server_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def recover_rds_servers(self, rds_server_ids:list) -> list:
"""Recovers the specified RDS Servers.
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = rds_server_ids
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/rds-servers/action/recover', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def update_rds_server(self, rds_server_id:str, max_sessions_count_configured:int,max_sessions_type_configured:str, enabled:bool=True):
"""Schedule/reschedule a request to update the image in an instant clone desktop pool
Requires the rds_server_id as string, enabled as booleanm max_sessions_count_configured as int and max_sessions_type_configured as string
enabled defaults to True, the options for max_sessions_type_configured are: UNLIMITED, LIMITED, UNCONFIGURED
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["enabled"] = enabled
data["max_sessions_count_configured"] = max_sessions_count_configured
data["max_sessions_type_configured"] = max_sessions_type_configured
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/inventory/v1/rds-servers/{rds_server_id}', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def add_rds_server(self,description: str, dns_name: str, operating_system: str, farm_id: str):
"""Registers the RDS Server.
Requires description, dns_name, operating_system and farm_id as string
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["description"] = description
data["dns_name"] = dns_name
data["farm_id"] = farm_id
data["operating_system"] = operating_system
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/rds-servers/action/register', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def check_rds_server_name_availability(self,machine_name: str)-> dict:
"""Checks if the given prefix is available for RDS Server creation.
Requires the name of the RDS Server to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = machine_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/rds-servers/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_physical_machines(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the Physical Machines in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2012 and later."""
def int_get_physical_machines(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/inventory/v1/physical-machines?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/inventory/v1/physical-machines?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_physical_machines(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_physical_machines(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_physical_machine(self, physical_machine_id:str) -> dict:
"""Gets the Physical Machine information.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/physical-machines/{physical_machine_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def delete_physical_machine(self, physical_machine_id:str):
"""Deletes the Physical Machine.
Available for Horizon 8 2012 and later."""
response = requests.delete(f'{self.url}/rest/inventory/v1/physical-machines/{physical_machine_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def add_physical_machine(self,description: str, dns_name: str, operating_system: str):
"""Registers the Physical Machine.
Requires ad_domain_id, username and password in plain text.
Available for Horizon 7.11 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["description"] = description
data["dns_name"] = dns_name
data["operating_system"] = operating_system
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/physical-machines/action/register', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_desktop_pool_tasks(self, desktop_pool_id:str) -> list:
"""Lists the tasks on the desktop pool.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/tasks', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_desktop_pool_task(self, desktop_pool_id:str, task_id:str) -> dict:
"""Gets the task information on the desktop pool.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/tasks/{task_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def cancel_desktop_pool_task(self, desktop_pool_id:str, task_id:str) -> dict:
"""Cancels the instant clone desktop pool push image task.
Available for Horizon 8 2012 and later."""
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/{desktop_pool_id}/tasks/{task_id}/action/cancel', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def check_application_name_availability(self,application_name: str)-> dict:
"""Checks if the given name is available for application pool creation.
Requires the name of the application to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = application_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/application-pools/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def check_desktop_pool_name_availability(self,desktop_pool_name: str)-> dict:
"""Checks if the given name is available for desktop pool creation.
Requires the name of the desktop pool to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = desktop_pool_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/desktop-pools/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def check_farm_name_availability(self,farm_name: str)-> dict:
"""Checks if the given name is available for farm creation.
Requires the name of the farm to test as string
Available for Horizon 8 2103 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = farm_name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/inventory/v1/farms/action/check-name-availability', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
class Monitor:
def __init__(self, url: str, access_token: dict):
"""Default object for the monitor class used for the monitoring of the various VMware Horiozn services."""
self.url = url
self.access_token = access_token
def ad_domains(self) -> list:
"""Lists monitoring information related to AD Domains of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/ad-domains', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def connection_servers(self) -> list:
"""Lists monitoring information related to Connection Servers of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/connection-servers', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def connection_server(self, id: str) ->dict:
"""Lists monitoring information related to a single Connection Server.
Requires the id of a Connection Server to be provided as id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/connection-servers/{id}', verify=False, headers=self.access_token) # Only available in Horion 8.0 2006 and newer
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def event_database(self) -> dict:
"""Returns monitoring information related to Event database of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/event-database', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def farms(self) -> list:
"""Lists monitoring information related to RDS Farms of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/farms', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def farm(self, id: str) -> dict:
"""Lists monitoring information related to a single RDS Farm.
Requires the id of a farm to be provided as id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/farms/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def gateways(self) -> list:
"""Lists monitoring information related to Gateways registered in the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/gateways', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def gateway(self, id: str) -> dict:
"""Lists monitoring information related to a single gateway.
Requires the id of a Gateway to be provided as id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/gateways/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def rds_servers(self) -> list:
"""Lists monitoring information related to RDS Servers of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/rds-servers', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def rds_server(self, id: str) -> dict:
"""Lists monitoring information related to a single RDS Server.
Requires the id of a RDS Server to be provided as id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/rds-servers/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def saml_authenticators(self) -> list:
"""Lists monitoring information related to SAML Authenticators of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/saml-authenticators', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def saml_authenticator(self, id: str) -> dict:
"""Lists monitoring information related to a single SAML Authenticator.
Requires the id of a SAML Authenticator to be provided as id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/saml-authenticators/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def view_composers(self) -> list:
"""Lists monitoring information related to View Composers of the environment.
Available for Horizon 7.10 to Horizon 8 2006."""
response = requests.get(f'{self.url}/rest/monitor/view-composers', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def view_composer(self, vcId: str):
"""Lists monitoring information related to a single View Composers.
Requires the id of a Virtual Center to be provided as vcId
Only available for Horizon 8 2006."""
response = requests.get(f'{self.url}/rest/monitor/v1/view-composers/{vcId}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def virtual_centers(self) -> list:
"""Lists monitoring information related to Virtual Centers of the environment.
Available for Horizon 7.10 and later."""
response = requests.get(f'{self.url}/rest/monitor/virtual-centers', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def virtual_center(self, id:str) -> dict:
"""Lists monitoring information related to a single Virtual Center.
Requires the id of a Virtual Center to be provided as id
Only available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/virtual-centers/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def remote_pods(self) -> list:
"""Lists monitoring information related to the remote pods.
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/pods', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def remote_pod(self, id:str) -> dict:
"""Lists monitoring information related to a single remote pod.
Requires the id of a Remote Pod to be provided as id
Only available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/pods/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def true_sso(self) -> list:
"""Lists monitoring information related to True SSO connectors.
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/monitor/v1/true-sso', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_desktop_pool_metrics(self, desktop_pool_ids:list) -> list:
"""Lists metrics of desktop pools (except RDS desktop pools).
Available for Horizon 8 2012 and later."""
urlstring='&ids='.join(desktop_pool_ids)
response = requests.get(f'{self.url}/rest/monitor/v1/desktop-pools/metrics?ids={urlstring}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
class Config:
def __init__(self, url: str, access_token: dict):
"""Default object for the config class used for the general configuration of VMware Horizon."""
self.url = url
self.access_token = access_token
def get_ic_domain_accounts(self) -> list:
"""Lists instant clone domain accounts of the environment.
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/config/v1/ic-domain-accounts', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_ic_domain_account(self,id) -> dict:
"""Gets a single instant clone domain account.
Requires the id of an Instant Clone Admin account to be provided as id
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/config/v1/ic-domain-accounts/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_ic_domain_account(self,ad_domain_id: str,username: str,password: str):
"""Creates Instant Clone Domain Account
Requires ad_domain_id, username and password in plain text.
Available for Horizon 7.11 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {"ad_domain_id": ad_domain_id, "password": password, "username": username}
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/ic-domain-accounts', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_ic_domain_account(self,id: str,password: str):
"""Changes password for an Instant Clone Domain account
Requires id of an Instant CLone Domain account and a plain text password.
Available for Horizon 7.11 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {"password": password}
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/config/v1/ic-domain-accounts/{id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_ic_domain_account(self,id: str):
"""Removes Instant Clone Domain Account from the environment
Requires id of an Instant CLone Domain account
Available for Horizon 7.11 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/ic-domain-accounts/{id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def get_virtual_centers(self) -> list:
"""Lists Virtual Centers configured in the environment.
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/config/v1/virtual-centers', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_environment_properties(self) -> dict:
"""Retrieves the environment settings.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/environment-properties', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_settings(self) -> dict:
"""Retrieves the environment settings.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/settings', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_settings_feature(self) -> dict:
"""Retrieves the feature settings.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/settings/feature', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_settings_general(self) -> dict:
"""Retrieves the general settings.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/settings/general', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_settings_security(self) -> dict:
"""Retrieves the security settings.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/settings/security', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def update_settings_general(self,settings: dict):
"""Updates the general settings.
Requires a dictionary with updated settings.
AVailablke settings can be retreived using get_settings_general()
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
config = self.get_settings_general()
for key, value in settings.items():
if key in config:
config[key] = value
else:
error_key = key
raise Exception(f"{error_key} is not a valid setting")
json_data = json.dumps(config)
response = requests.put(f'{self.url}/rest/config/v1/settings/general', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_settings_feature(self,settings: dict):
"""Updates the feature settings.
Requires a dictionary with updated settings.
Available settings can be retreived using get_settings_feature()
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
config = self.get_settings_feature()
for key, value in settings.items():
if key in config:
config[key] = value
else:
error_key = key
raise Exception(f"{error_key} is not a valid setting")
json_data = json.dumps(config)
response = requests.put(f'{self.url}/rest/config/v1/settings/feature', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_settings_security(self,settings: dict):
"""Updates the security settings.
Requires a dictionary with updated settings.
Available settings can be retreived using get_settings_security()
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
config = self.get_settings_security()
for key, value in settings.items():
if key in config:
config[key] = value
else:
error_key = key
raise Exception(f"{error_key} is not a valid setting")
json_data = json.dumps(config)
response = requests.put(f'{self.url}/rest/config/v1/settings/security', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status
def update_settings(self,settings: dict):
"""Updates the settings.
Requires a dictionary with updated settings.
Available settings can be retreived using get_settings()
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
config = self.get_settings()
for key, value in settings.items():
if key in config:
config[key] = value
else:
error_key = key
raise Exception(f"{error_key} is not a valid setting")
json_data = json.dumps(config)
response = requests.put(f'{self.url}/rest/config/v1/settings', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status
def get_local_access_groups(self) -> list:
"""Lists all local access groups.
Available for Horizon 8 2103 and later."""
response = requests.get(f'{self.url}/rest/config/v1/local-access-groups', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_local_access_group(self,local_access_group_id: str) -> dict:
"""Retrieves a local access group.
Requires the id of an local access group as string
Available for Horizon 8 2103 and later."""
response = requests.get(f'{self.url}/rest/config/v1/local-access-groups/{local_access_group_id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_assets(self,im_version_id : str) ->list:
"""Lists image management assets.
Requires im_version_id as string
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-assets?im_version_id={im_version_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_asset(self,im_asset_id : str) ->dict:
"""Gets image management asset.
Requires im_version_id as string
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-assets/{im_asset_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_streams(self) -> list:
"""Lists image management streams.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-streams', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_stream(self, im_stream_id : str) -> dict:
"""Gets image management stream.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-streams/{im_stream_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_tags(self, im_stream_id : str) -> list:
"""Lists image management tags.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-tags?im_stream_id={im_stream_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_tag(self, im_tag_id : str) -> dict:
"""Gets image management stream.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-tags/{im_tag_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_versions(self, im_stream_id : str) -> list:
"""Lists image management versions.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-versions?im_stream_id={im_stream_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_im_version(self, im_version_id : str) -> dict:
"""Gets image management version.
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/config/v1/im-versions/{im_version_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_im_asset(self,im_stream_id : str,im_version_id : str, clone_type:str,image_type : str,status : str,vcenter_id : str,
additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = "", base_snapshot_id : str = "", base_vm_id : str = "", vm_template_id: str = "" ):
"""Creates image management asset.
Requires all as string:
im_stream_id
im_version_id
clone_type : either FULL_CLONE or INSTANT_CLONE
image_type : RDSH_APPS, RDSH_DESKTOP or VDI_DESKTOP"
status : AVAILABLE, DEPLOYING_VM, DEPLOYMENT_DONE, DELETED, DISABLED, FAILED, REPLICATING, RETRY_PENDING or SPECIALIZING_VM
vcenter_id
Choice between:
base_snapshot_id and base_vm_id
OR
vm_template_id
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_image_type = [ "RDSH_APPS", "RDSH_DESKTOP", "VDI_DESKTOP" ]
valid_status = [ "AVAILABLE", "DEPLOYING_VM", "DEPLOYMENT_DONE", "DELETED", "DISABLED", "FAILED", "REPLICATING", "RETRY_PENDING", "SPECIALIZING_VM" ]
valid_clone_type = [ "FULL_CLONE", "INSTANT_CLONE" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["additional_details"] = additional_details
if vm_template_id != "" and (base_vm_id != "" or base_snapshot_id != ""):
raise Exception("Error: either vm_template_id or base_vm_id and base_snapshot_id is required")
elif vm_template_id == "" and (base_vm_id == "" or base_snapshot_id == ""):
raise Exception("Error: Both base_vm_id and base_snapshot_id are required")
elif vm_template_id == "" and (base_vm_id != "" and base_snapshot_id != ""):
data["base_snapshot_id"] = base_snapshot_id
data["base_vm_id"] = base_vm_id
if clone_type in valid_clone_type:
data["clone_type"] = clone_type
else:
raise Exception(f"Error: please provide a valid clone_type from these options: {valid_clone_type}")
data["im_stream_id"] = im_stream_id
data["im_version_id"] = im_version_id
if image_type in valid_image_type:
data["image_type"] = image_type
else:
raise Exception(f"Error: please provide a valid image_type from these options: {valid_image_type}")
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
data["vcenter_id"] = vcenter_id
if vm_template_id != "":
data["vm_template_id"] = vm_template_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/im-assets', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_im_asset(self,im_asset_id : str, clone_type:str,image_type : str,status : str, additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Updates image management asset.
Requires:
im_assit_id as string
clone_type : either FULL_CLONE or INSTANT_CLONE
image_type : RDSH_APPS, RDSH_DESKTOP or VDI_DESKTOP"
status : AVAILABLE, DEPLOYING_VM, DEPLOYMENT_DONE, DELETED, DISABLED, FAILED, REPLICATING, RETRY_PENDING or SPECIALIZING_VM
vcenter_id
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_image_type = [ "RDSH_APPS", "RDSH_DESKTOP", "VDI_DESKTOP" ]
valid_status = [ "AVAILABLE", "DEPLOYING_VM", "DEPLOYMENT_DONE", "DELETED", "DISABLED", "FAILED", "REPLICATING", "RETRY_PENDING", "SPECIALIZING_VM" ]
valid_clone_type = [ "FULL_CLONE", "INSTANT_CLONE" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["additional_details"] = additional_details
if clone_type in valid_clone_type:
data["clone_type"] = clone_type
else:
raise Exception(f"Error: please provide a valid clone_type from these options: {valid_clone_type}")
if image_type in valid_image_type:
data["image_type"] = image_type
else:
raise Exception(f"Error: please provide a valid image_type from these options: {valid_image_type}")
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/config/v1/im-assets/{im_asset_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_im_asset(self, im_asset_id : str):
"""Deletes image management asset.
Available for Horizon 7.12 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/im-assets/{im_asset_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_im_tag(self,name : str,im_stream_id : str,im_version_id : str, additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Creates image management tag.
Requires all as string:
im_stream_id
im_version_id
name
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["im_stream_id"] = im_stream_id
data["im_version_id"] = im_version_id
data["name"] = name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/im-tags', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_im_tag(self,name : str,im_tag_id : str,im_version_id : str, additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Updates image management tag.
Requires all as string:
im_tag_id
im_version_id
name
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["im_version_id"] = im_version_id
data["name"] = name
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/config/v1/im-tags/{im_tag_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_im_tag(self, im_tag_id : str):
"""Deletes image management tag.
Available for Horizon 7.12 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/im-tags/{im_tag_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_im_stream(self,description : str,name : str, operating_system:str,publisher : str,source : str,status : str,
additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Creates image management stream.
Requires all as string:
description
name
operating_system : UNKNOWN, WINDOWS_XP, WINDOWS_VISTA, WINDOWS_7, WINDOWS_8, WINDOWS_10, WINDOWS_SERVER_2003,
WINDOWS_SERVER_2008, WINDOWS_SERVER_2008_R2, WINDOWS_SERVER_2012, WINDOWS_SERVER_2012_R2,
WINDOWS_SERVER_2016_OR_ABOVE, LINUX_OTHER, LINUX_SERVER_OTHER, LINUX_UBUNTU, LINUX_RHEL, LINUX_SUSE, LINUX_CENTOS
status : AVAILABLE, DELETED, DISABLED, FAILED, IN_PROGRESS, PARTIALLY_AVAILABLE, PENDING
publisher
source : MARKET_PLACE, UPLOADED, COPIED_FROM_STREAM, COPIED_FROM_VERSION
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_operating_system = [ "UNKNOWN", "WINDOWS_XP", "WINDOWS_VISTA", "WINDOWS_7", "WINDOWS_8", "WINDOWS_10", "WINDOWS_SERVER_2003",
"WINDOWS_SERVER_2008", "WINDOWS_SERVER_2008_R2", "WINDOWS_SERVER_2012", "WINDOWS_SERVER_2012_R2", "WINDOWS_SERVER_2016_OR_ABOVE",
"LINUX_OTHER", "LINUX_SERVER_OTHER", "LINUX_UBUNTU", "LINUX_RHEL", "LINUX_SUSE", "LINUX_CENTOS" ]
valid_status = [ "AVAILABLE", "DELETED", "DISABLED", "FAILED", "IN_PROGRESS", "PARTIALLY_AVAILABLE", "PENDING" ]
valid_source = [ "MARKET_PLACE", "UPLOADED", "COPIED_FROM_STREAM", "COPIED_FROM_VERSION" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["description"] = description
data["name"] = name
if operating_system in valid_operating_system:
data["operating_system"] = operating_system
else:
raise Exception(f"Error: please provide a valid operating_system from these options: {valid_operating_system}")
data["publisher"] = publisher
if source in valid_source:
data["source"] = source
else:
raise Exception(f"Error: please provide a valid source from these options: {valid_source}")
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/im-streams', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_im_stream(self,im_stream_id : str, description : str,name : str, operating_system:str,publisher : str,source : str,status : str,
additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Updates image management stream.
Requires all as string:
description
name
operating_system : UNKNOWN, WINDOWS_XP, WINDOWS_VISTA, WINDOWS_7, WINDOWS_8, WINDOWS_10, WINDOWS_SERVER_2003,
WINDOWS_SERVER_2008, WINDOWS_SERVER_2008_R2, WINDOWS_SERVER_2012, WINDOWS_SERVER_2012_R2,
WINDOWS_SERVER_2016_OR_ABOVE, LINUX_OTHER, LINUX_SERVER_OTHER, LINUX_UBUNTU, LINUX_RHEL, LINUX_SUSE, LINUX_CENTOS
status : AVAILABLE, DELETED, DISABLED, FAILED, IN_PROGRESS, PARTIALLY_AVAILABLE, PENDING
publisher
source : MARKET_PLACE, UPLOADED, COPIED_FROM_STREAM, COPIED_FROM_VERSION
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_operating_system = [ "UNKNOWN", "WINDOWS_XP", "WINDOWS_VISTA", "WINDOWS_7", "WINDOWS_8", "WINDOWS_10", "WINDOWS_SERVER_2003",
"WINDOWS_SERVER_2008", "WINDOWS_SERVER_2008_R2", "WINDOWS_SERVER_2012", "WINDOWS_SERVER_2012_R2", "WINDOWS_SERVER_2016_OR_ABOVE",
"LINUX_OTHER", "LINUX_SERVER_OTHER", "LINUX_UBUNTU", "LINUX_RHEL", "LINUX_SUSE", "LINUX_CENTOS" ]
valid_status = [ "AVAILABLE", "DELETED", "DISABLED", "FAILED", "IN_PROGRESS", "PARTIALLY_AVAILABLE", "PENDING" ]
valid_source = [ "MARKET_PLACE", "UPLOADED", "COPIED_FROM_STREAM", "COPIED_FROM_VERSION" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["description"] = description
data["name"] = name
if operating_system in valid_operating_system:
data["operating_system"] = operating_system
else:
raise Exception(f"Error: please provide a valid operating_system from these options: {valid_operating_system}")
data["publisher"] = publisher
if source in valid_source:
data["source"] = source
else:
raise Exception(f"Error: please provide a valid source from these options: {valid_source}")
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/config/v1/im-streams/{im_stream_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_im_stream(self, im_stream_id : str):
"""Deletes image management stream.
Available for Horizon 7.12 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/im-streams/{im_stream_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_im_version(self,description : str,name : str, im_stream_id : str,status : str, additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Creates image management version.
Requires all as string:
description
name
im_stream_id
status : AVAILABLE, DEPLOYING_VM, DEPLOYMENT_DONE, DELETED, DISABLED, FAILED, PARTIALLY_AVAILABLE, PUBLISHING, REPLICATING
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_status = [ "AVAILABLE", "DEPLOYING_VM", "DEPLOYMENT_DONE", "DELETED", "DISABLED", "FAILED", "PARTIALLY_AVAILABLE", "PUBLISHING", "REPLICATING" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["description"] = description
data["im_stream_id"] = im_stream_id
data["name"] = name
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/im-versions', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_im_version(self,description : str,name : str, im_version_id : str,status : str, additional_details_1:str = "", additional_details_2:str = "", additional_details_3:str = ""):
"""Updates] image management version.
Requires all as string:
description
name
im_stream_id
status : AVAILABLE, DEPLOYING_VM, DEPLOYMENT_DONE, DELETED, DISABLED, FAILED, PARTIALLY_AVAILABLE, PUBLISHING, REPLICATING
Optional:
additional_details_1
additional_details_2
additional_details_3
Available for Horizon 7.12 and later."""
valid_status = [ "AVAILABLE", "DEPLOYING_VM", "DEPLOYMENT_DONE", "DELETED", "DISABLED", "FAILED", "PARTIALLY_AVAILABLE", "PUBLISHING", "REPLICATING" ]
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
additional_details = {}
additional_details["additionalProp1"] = additional_details_1
additional_details["additionalProp2"] = additional_details_2
additional_details["additionalProp3"] = additional_details_3
data["description"] = description
data["name"] = name
if status in valid_status:
data["status"] = status
else:
raise Exception(f"Error: please provide a valid status from these options: {valid_status}")
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/config/v1/im-versions/{im_version_id}', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_im_version(self, im_version_id : str):
"""Deletes image management version.
Available for Horizon 7.12 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/im-versions/{im_version_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_federation_access_groups(self) -> list:
"""Lists all federation access groups.
Available for Horizon 8 2106 and later."""
response = requests.get(f'{self.url}/rest/config/v1/federation-access-groups', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_federation_access_group(self,id) -> dict:
"""Retrieves a federation access group.
Requires the id of an Instant Clone Admin account to be provided as id
Available for Horizon 8 2106 and later."""
response = requests.get(f'{self.url}/rest/config/v1/federation-access-groups/{id}', verify=False, headers=self.access_token)
if response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_federation_access_group(self, name: str, description: str):
"""Creates federation access group.
Requires name and description as string
Available for Horizon 8 2106 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {"name": name, "description": description,}
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/config/v1/federation-access-groups', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_federation_access_group(self,id: str):
"""Deletes a federation access group.
Requires id of a federation access group
Available for Horizon 8 2106 and later."""
response = requests.delete(f'{self.url}/rest/config/v1/federation-access-groups/{id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
class External:
def __init__(self, url: str, access_token: dict):
"""Default object for the External class for resources that are external to Horizon environment."""
self.url = url
self.access_token = access_token
def get_ad_domains(self) -> list:
"""Lists information related to AD Domains of the environment.
Available for Horizon 7.11 and later."""
response = requests.get(f'{self.url}/rest/external/v1/ad-domains', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_ad_domains_v3(self) -> list:
"""Lists information related to AD Domains of the environment.
Available for Horizon 8 2106 and later."""
response = requests.get(f'{self.url}/rest/external/v1/ad-domains', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_base_vms(self, vcenter_id : str,filter_incompatible_vms: bool="", datacenter_id:str="" ) -> list:
"""Lists all the VMs from a vCenter or a datacenter in that vCenter which may be suitable as snapshots for instant/linked clone desktop or farm creation.
Requires vcenter_id, optionally datacenter id and since Horizon 2012 filter_incompatible_vms was added (defaults to false)
Available for Horizon 7.12 and later and Horizon 8 2012 for filter_incompatible_vms."""
if (filter_incompatible_vms == True or filter_incompatible_vms == False) and datacenter_id != "":
response = requests.get(f'{self.url}/rest/external/v1/base-vms?datacenter_id={datacenter_id}&filter_incompatible_vms={filter_incompatible_vms}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
elif (filter_incompatible_vms != True or filter_incompatible_vms != False) and datacenter_id != "":
response = requests.get(f'{self.url}/rest/external/v1/base-vms?filter_incompatible_vms={filter_incompatible_vms}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
elif datacenter_id != "":
response = requests.get(f'{self.url}/rest/external/v1/base-vms?datacenter_id={datacenter_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/external/v1/base-vms?vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_base_snapshots(self, vcenter_id : str, base_vm_id:str ) -> list:
"""Lists all the VM snapshots from the vCenter for a given VM.
Requires vcenter_id and base_vm_id
Available for Horizon 8 2006."""
response = requests.get(f'{self.url}/rest/external/v1/base-snapshots?base_vm_id={base_vm_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_customization_specifications(self, vcenter_id : str) -> list:
"""Lists all the customization specifications from the vCenter.
Requires vcenter_id
Available for Horizon 8 2006."""
response = requests.get(f'{self.url}/rest/external/v1/customization-specifications?vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_datacenters(self, vcenter_id: str) -> list:
"""Lists all the datacenters of a vCenter.
Requires vcenter_id
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/external/v1/datacenters?vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_hosts_or_clusters(self, vcenter_id : str, datacenter_id:str) -> list:
"""Lists all the hosts or clusters of the datacenter.
Requires vcenter_id and datacenter id
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/external/v1/hosts-or-clusters?datacenter_id={datacenter_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_vm_templates(self, vcenter_id : str, datacenter_id:str="" ) -> list:
"""Lists all the VM templates from a vCenter or a datacenter for the given vCenter which may be suitable for full clone desktop pool creation.
Requires vcenter_id and datacenter id
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/external/v1/vm-templates?datacenter_id={datacenter_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_ad_users_or_groups(self, maxpagesize:int=100, filter:dict="", group_only:bool = "") -> list:
"""Lists AD users or groups information
If group_only is passed as True only groups are returned, if users_only is passed as False only users are returned. If both are passed a True an error will be raised.
Supports pagination and filtering
Available for Horizon 7.12 and later."""
def int_get_ad_users_or_groups(self, page:int, maxpagesize: int, filter:list="", group_only: bool="") ->list:
if filter != "" and (group_only == True or group_only == False):
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
url_filter = f"?filter={filter_url}&group_only={group_only}&page={page}&size={maxpagesize}"
elif filter == "" and (group_only == True or group_only == False):
url_filter = f"?group_only={group_only}&page={page}&size={maxpagesize}"
elif filter != "" and not (group_only == True or group_only == False):
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
url_filter = f"?filter={filter_url}&page={page}&size={maxpagesize}"
else:
url_filter = f"?page={page}&size={maxpagesize}"
response = requests.get(f'{self.url}/rest/external/v1/ad-users-or-groups{url_filter}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_ad_users_or_groups(self,page = page, maxpagesize= maxpagesize,filter = filter, group_only = group_only)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_ad_users_or_groups(self,page = page, maxpagesize= maxpagesize,filter = filter, group_only = group_only)
results += response.json()
return results
def get_ad_users_or_group(self, id) -> dict:
"""Get information related to AD User or Group.
Requires id of the user object
Available for Horizon 7.12 and later."""
response = requests.get(f'{self.url}/rest/external/v1/ad-users-or-groups/{id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_datastores(self, vcenter_id : str, host_or_cluster_id:str ) -> list:
"""Lists all the datastoress from the vCenter for the given host or cluster.
Requires host_or_cluster_id and vcenter_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/external/v1/datastores?host_or_cluster_id={host_or_cluster_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_datastore_clusters(self, vcenter_id : str, host_or_cluster_id:str ) -> list:
"""Lists all the datastore clusters from the vCenter for the given host or cluster.
Requires host_or_cluster_id and vcenter_id
Available for Horizon 8 2103 and later."""
response = requests.get(f'{self.url}/rest/external/v1/datastore-clusters?host_or_cluster_id={host_or_cluster_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_datastore_paths(self, vcenter_id : str, datastore_id:str ) -> list:
"""Lists all the folder paths within a Datastore from vCenter.
Requires datastore_id and vcenter_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/external/v1/datastore-paths?datastore_id={datastore_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_network_labels(self, vcenter_id : str, host_or_cluster_id:str, network_type:str = "" ) -> list:
"""Retrieves all network labels on the given host or cluster.
Requires host_or_cluster_id, vcenter_id and optionally a network type.
Valid options for network_type are: NETWORK, OPAQUE_NETWORK, DISTRUBUTED_VIRTUAL_PORT_GROUP
Available for Horizon 8 2006 and later."""
if network_type == "":
response = requests.get(f'{self.url}/rest/external/v1/network-labels?host_or_cluster_id={host_or_cluster_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
elif network_type == "NETWORK" or network_type == "OPAQUE_NETWORK" or network_type == "DISTRUBUTED_VIRTUAL_PORT_GROUP":
response = requests.get(f'{self.url}/rest/external/v1/network-labels?host_or_cluster_id={host_or_cluster_id}&network_type={network_type}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
else:
raise(f"{network_type} is not a valid network type try NETWORK, OPAQUE_NETWORK or DISTRUBUTED_VIRTUAL_PORT_GROUP")
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_resource_pools(self, vcenter_id : str, host_or_cluster_id:str) -> list:
"""Lists all the resource pools from the vCenter for the given host or cluster.
Requires host_or_cluster_id and vcenter_id.
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/external/v1/resource-pools?host_or_cluster_id={host_or_cluster_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_vm_folders(self, vcenter_id : str, datacenter_id:str) -> list:
"""Lists all the VM folders from the vCenter for the given datacenter.
Requires datacenter_id and vcenter_id.
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/external/v1/vm-folders?datacenter_id={datacenter_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_network_interface_cards(self, vcenter_id : str, base_snapshot_id:str = "", base_vm_id:str = "",vm_template_id:str = "" ) -> list:
"""Returns a list of network interface cards (NICs) suitable for configuration on a desktop pool/farm.
Requires vcenter_id and either vm_template_id or (base_vm_id and base_snapshot_id).
Available for Horizon 8 2006 and later."""
if base_snapshot_id != "" and base_vm_id != "" and vm_template_id != "":
raise("When VM template is specified, base VM and snapshot cannot be specified.")
elif base_snapshot_id != "" and base_vm_id != "" and vm_template_id == "":
response = requests.get(f'{self.url}/rest/external/v1/network-interface-cards?base_snapshot_id={base_snapshot_id}&base_vm_id={base_vm_id}&vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
elif base_snapshot_id == "" and base_vm_id == "" and vm_template_id != "":
response = requests.get(f'{self.url}/rest/external/v1/network-interface-cards?vcenter_id={vcenter_id}&vm_template_id={vm_template_id}', verify=False, headers=self.access_token)
else:
raise("Either VM template or (base VM with snapshot) are required for fetching network interface cards.")
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_virtual_machines(self, vcenter_id:str) -> list:
"""Lists all the VMs from a vCenter.
Requires datacenter_id and vcenter_id.
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/external/v1/virtual-machines?vcenter_id={vcenter_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def compute_datastore_requirement(self,desktop_or_farm_id: str, user_assignment : str, vcenter_id : str, pool_size : int, source : str, type : str, base_snapshot_id: str="",base_vm_id: str="", use_separate_replica_and_os_disk : bool=False, use_vsan : bool = False, vm_template_id : str = "") -> list:
"""Creates Instant Clone Domain Account
Requirements:
base_snapshot_id : str - Required when source is INSTANT_CLONE
base_vm_id : string - Required when source is INSTANT_CLONE
desktop_or_farm_id: string
pool_size : int32
source : string - Required to be either FULL_CLONE or INSTANT_CLONE
type : string - Required to be DESKTOP_POOL or FARM
use_separate_replica_and_os_disk : boolean - Ignored for FULL_CLONE or when vSAN is used, defaults to False
use_vsan : boolean - defaults to False
user_assignment : string - Required to be DEDICATED or FLOATING
vcenter_id : string
vm_template_id : string - Required when source is FULL_CLONE
Available for Horizon 8 2103 and later."""
if source !="FULL_CLONE" and source !="INSTANT_CLONE":
raise Exception(f"Error: source has to be either FULL_CLONE or INSTANT_CLONE")
if type !="DESKTOP_POOL" and type !="FARM":
raise Exception(f"Error: type has to be either DESKTOP_POOL or FARM")
if user_assignment !="DEDICATED" and user_assignment !="FLOATING":
raise Exception(f"Error: user_assignment has to be either DEDICATED or FLOATING")
if source == "FULL_CLONE" and vm_template_id == "":
raise Exception(f"Error: When type is FULL_CLONE vm_template_id is required ")
if source == "INSTANT_CLONE" and (base_vm_id == "" or base_snapshot_id == ""):
raise Exception(f"Error: When type is INSTANT_CLONE both base_vm_id and base_snapshot_id are required ")
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
if source == "INSTANT_CLONE":
data["base_snapshot_id"] = base_snapshot_id
data["base_vm_id"] = base_vm_id
data["id"] = desktop_or_farm_id
data["pool_size"] = pool_size
data["source"] = source
data["type"] = type
data["use_separate_replica_and_os_disk"] = use_separate_replica_and_os_disk
data["use_vsan"] = use_vsan
data["user_assignment"] = user_assignment
data["vcenter_id"] = vcenter_id
if type == "FULL_CLONE":
data["vm_template_id"] = vm_template_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/external/v1/datastores/action/compute-requirements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_auxiliary_account(self, domain_id: str, username: str, password: str):
"""Add auxiliary accounts to the untrusted domain
Requires domain_id, username and password as string
Available for Horizon 8 2106 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["auxiliary_accounts"] = []
auxiliary_account = {}
auxiliary_account["password"] = password
auxiliary_account["username"] = username
(data["auxiliary_accounts"]).append(auxiliary_account)
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/external/v1/ad-domains/{domain_id}/action/add-auxiliary-accounts', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_auxiliary_account(self, domain_id: str, auxiliary_account_ids: list):
"""deletes auxiliary accounts from the untrusted domain
Requires domain_id as string and auxiliary_account_ids as a list
Available for Horizon 8 2106 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["auxiliary_account_ids"] = auxiliary_account_ids
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/external/v1/ad-domains/{domain_id}/action/delete-auxiliary-accounts', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def update_auxiliary_account(self, auxiliary_account_id: str, password : str):
"""updates auxiliary accounts of the untrusted domain
Requires auxiliary_account_id and password as string
Available for Horizon 8 2106 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["auxiliary_accounts"] = []
auxiliary_account = {}
auxiliary_account["id"] = auxiliary_account_id
auxiliary_account["password"] = password
(data["auxiliary_accounts"]).append(auxiliary_account)
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/external/v1/ad-domains/action/update-auxiliary-accounts', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 409:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def get_audit_events(self, filter:dict="", maxpagesize:int=100) -> list:
"""Lists the audit events.
Requires nothing
Available for Horizon 8 2106 and later."""
def int_get_audit_events(self, page:int, maxpagesize: int, filter:dict="") ->list:
if filter !="":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"{filter_url}"
response = requests.get(f'{self.url}/rest/external/v1/audit-events?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/external/v1/audit-events?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_audit_events(self,page = page, maxpagesize= maxpagesize, filter= filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_audit_events(self,page = page, maxpagesize= maxpagesize, filter= filter)
results += response.json()
return results
class Entitlements:
def __init__(self, url: str, access_token: dict):
"""Default object for the Entitlements class for the entitlement of resources."""
self.url = url
self.access_token = access_token
def get_application_pools_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the entitlements for Application Pools in the environment.
Allows for filtering, either application_pool id can be used to filter on id key and or ad_user_or_group_ids can be filtered on.
Available for Horizon 8 2006 and later."""
def int_get_application_pools(self, page:int, maxpagesize: int, filter:dict="") ->list:
if filter != "":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"?filter={filter_url}"
response = requests.get(f'{self.url}/rest/entitlements/v1/application-pools{add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/entitlements/v1/application-pools?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_application_pools(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_application_pools(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_application_pool_entitlement(self, application_pool_id:str) -> list:
"""Returns the IDs of users or groups entitled to a given application pool
Requires applictaion_pool_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/entitlements/v1/application-pools/{application_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_application_pools_entitlements(self,application_pool_data:dict):
"""Creates an application pool.
Requires application_pool_data as a dict
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_data)
response = requests.post(f'{self.url}/rest/entitlements/v1/application-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_application_pools_entitlements(self,application_pool_data:dict):
"""Creates an application pool.
Requires application_pool_data as a dict
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(application_pool_data)
response = requests.delete(f'{self.url}/rest/entitlements/v1/application-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def get_desktop_pools_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the entitlements for desktop Pools in the environment.
Allows for filtering, either desktop_pool id can be used to filter on id key and or ad_user_or_group_ids can be filtered on.
Available for Horizon 8 2006 and later."""
def int_get_desktop_pools(self, page:int, maxpagesize: int, filter:dict="") ->list:
if filter != "":
filter_url = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
add_filter = f"?filter={filter_url}"
response = requests.get(f'{self.url}/rest/entitlements/v1/desktop-pools{add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/entitlements/v1/desktop-pools?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_desktop_pools(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_desktop_pools(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_desktop_pool_entitlement(self, desktop_pool_id:str) -> list:
"""Returns the IDs of users or groups entitled to a given desktop pool
Requires desktop_pool_id
Available for Horizon 8 2006 and later."""
response = requests.get(f'{self.url}/rest/entitlements/v1/desktop-pools/{desktop_pool_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_desktop_pools_entitlements(self,desktop_pools_data:list):
"""Create the bulk entitlements for a set of desktop pools.
Requires desktop_pools_data as a list
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(desktop_pools_data)
response = requests.post(f'{self.url}/rest/entitlements/v1/desktop-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def delete_desktop_pools_entitlements(self,desktop_pools_data:list):
"""Delete the bulk entitlements for a set of desktop pools.
Requires desktop_pools_data as a list.
Available for Horizon 8 2006 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(desktop_pools_data)
response = requests.delete(f'{self.url}/rest/entitlements/v1/desktop-pools', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.status_code
def get_global_desktop_entitlement(self, global_desktop_entitlement_id:str) -> dict:
"""Gets the user or group entitlements for a Global Desktop Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/entitlements/v1/global-desktop-entitlements/{global_desktop_entitlement_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_desktop_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the user or group entitlements for Global Desktop Entitlements in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2012 and later."""
def int_get_global_desktop_entitlements(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/entitlements/v1/global-desktop-entitlements?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/entitlements/v1/global-desktop-entitlements?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_global_desktop_entitlements(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_global_desktop_entitlements(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def new_global_desktop_entitlement(self, global_desktop_entitlement_data: list):
"""Create the bulk entitlements for a set of Global Desktop Entitlements.
Requires global_desktop_entitlement_data as a dict
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(global_desktop_entitlement_data)
response = requests.post(f'{self.url}/rest/entitlements/v1/global-desktop-entitlements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def delete_global_desktop_entitlement(self, global_desktop_entitlement_data: list):
"""Delete the bulk entitlements for a set of Global Desktop Entitlements.
Requires global_desktop_entitlement_data as a dict
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(global_desktop_entitlement_data)
response = requests.delete(f'{self.url}/rest/entitlements/v1/global-desktop-entitlements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_global_application_entitlement(self, global_application_entitlement_id:str) -> dict:
"""Gets the user or group entitlements for a Global Application Entitlement.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/entitlements/v1/global-application-entitlements/{global_application_entitlement_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_global_application_entitlements(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists the user or group entitlements for Global Application Entitlements in the environment.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2012 and later."""
def int_get_global_application_entitlements(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/entitlements/v1/global-application-entitlements?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/entitlements/v1/global-application-entitlements?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_get_global_application_entitlements(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_get_global_application_entitlements(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def new_global_application_entitlement(self, global_application_entitlement_data: list):
"""Create the bulk entitlements for a set of Global Application Entitlements
Requires global_application_entitlement_data as a dict
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(global_application_entitlement_data)
response = requests.post(f'{self.url}/rest/entitlements/v1/global-application-entitlements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def delete_global_application_entitlement(self, global_application_entitlement_data: list):
"""Delete the bulk entitlements for a set of Global Application Entitlements
Requires global_application_entitlement_data as a dict
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
json_data = json.dumps(global_application_entitlement_data)
response = requests.delete(f'{self.url}/rest/entitlements/v1/global-application-entitlements', verify=False, headers=headers, data=json_data)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {response}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
class Federation:
def __init__(self, url: str, access_token: dict):
"""Default object for the pools class where all Desktop Pool Actions will be performed."""
self.url = url
self.access_token = access_token
def get_cloud_pod_federation(self) -> dict:
"""Retrieves the pod federation details.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/cpa', verify=False, headers=self.access_token)
if response.status_code == 400:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_home_sites(self, maxpagesize:int=100, filter:dict="") -> list:
"""Lists all the home sites in the pod federation.
For information on filtering see https://vdc-download.vmware.com/vmwb-repository/dcr-public/f92cce4b-9762-4ed0-acbd-f1d0591bd739/235dc19c-dabd-43f2-8d38-8a7a333e914e/HorizonServerRESTPaginationAndFilterGuide.doc
Available for Horizon 8 2012 and later."""
def int_Get_home_sites(self, page:int, maxpagesize: int, filter:list="") ->list:
if filter != "":
add_filter = urllib.parse.quote(json.dumps(filter,separators=(', ', ':')))
response = requests.get(f'{self.url}/rest/federation/v1/home-sites?filter={add_filter}&page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
else:
response = requests.get(f'{self.url}/rest/federation/v1/home-sites?page={page}&size={maxpagesize}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response
if maxpagesize > 1000:
maxpagesize = 1000
page = 1
response = int_Get_home_sites(self,page = page, maxpagesize= maxpagesize,filter = filter)
results = response.json()
while 'HAS_MORE_RECORDS' in response.headers:
page += 1
response = int_Get_home_sites(self,page = page, maxpagesize= maxpagesize, filter = filter)
results += response.json()
return results
def get_sites(self) -> list:
"""Lists all the sites in the pod federation.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/sites', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_site(self, site_id:str) -> dict:
"""Retrives a given site.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/sites/{site_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def update_cloud_pod_federation(self, name:str):
"""Updates a Pod Federation
Requires a new name of the cpa as a string
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["name"] = name
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/federation/v1/cpa', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_home_site(self, home_site_id:str) -> dict:
"""Retrieves a given home site in the pod federation.
Requires a home_site_id as a string
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/home-sites/1/{home_site_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_site(self, name:str, description:str):
"""creates a site.
Requires the name and description as strings
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["description"] = description
data["name"] = name
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/federation/v1/sites', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 201:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def update_site(self,site_id:str ,name:str, description:str):
"""Updates a site.
Requires site_id, the name and description as strings
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["description"] = description
data["name"] = name
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/federation/v1/sites/{site_id}', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def delete_site(self, site_id:str):
"""Retrives a given site.
Available for Horizon 8 2012 and later."""
response = requests.delete(f'{self.url}/rest/federation/v1/sites/{site_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_pods(self) -> list:
"""Lists all the pods in the pod federation.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/pods', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_pod(self, pod_id:str) -> dict:
"""Retrieves a given pod from the pod federation.
Requires pod_id as a string
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/pods/{pod_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def update_pod(self,pod_id:str, description:str, site_id:str ,name:str, cloud_managed:bool=""):
"""Updates the given pod in the pod federation.
Requires pod_id, site_id, the name and description as strings, cloud_managed needs to be a bool
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
if cloud_managed != "":
data["cloud_managed"] = cloud_managed
if description!="":
data["description"] = description
data["name"] = name
data["site_id"] = site_id
json_data = json.dumps(data)
response = requests.put(f'{self.url}/rest/federation/v1/pods/{pod_id}', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def get_pod_endpoints(self, pod_id:str) -> list:
"""Lists all the pod endpoints for the given pod.
Requires pod_id as a string
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/pods/{pod_id}/endpoints', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_pod_endpoint(self, pod_id:str, endpoint_id:str) -> dict:
"""Lists all the pod endpoints for the given pod.
Requires pod_id and endpoint_id as a string
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/pods/{pod_id}/endpoints/{endpoint_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_tasks(self) -> list:
"""Lists all the CPA tasks in the pod federation.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/cpa/tasks', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_task(self, task_id:str) -> dict:
"""Retrieves the information for a given task.
Available for Horizon 8 2012 and later."""
response = requests.get(f'{self.url}/rest/federation/v1/cpa/tasks/{task_id}', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def eject_pod(self, pod_id:str) :
"""Removes a pod from Cloud Pod Federation.
Requires pod_id as a string
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["pod_id"] = pod_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/eject', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
def join_cpa(self, remote_pod_address:str, username:str, password:str) -> dict:
""" Join Cloud Pod Federation.
Requires remote_pod_address (fqdn), username (domain\\username) and password as str
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["password"] = password
data["remote_pod_address"] = remote_pod_address
data["username"] = username
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/join', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def unjoin_cpa(self) -> dict:
"""Unjoin from Cloud Pod Federation.
Available for Horizon 8 2012 and later."""
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/unjoin', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def initialize_cpa(self) -> dict:
"""Initialize Cloud Pod Federation.
Available for Horizon 8 2012 and later."""
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/initialize', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def uninitialize_cpa(self) -> dict:
"""Initialize Cloud Pod Federation.
Available for Horizon 8 2012 and later."""
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/uninitialize', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def unjoin_cpa(self) -> dict:
"""Initialize Cloud Pod Federation.
Available for Horizon 8 2012 and later."""
response = requests.post(f'{self.url}/rest/federation/v1/cpa/action/unjoin', verify=False, headers=self.access_token)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 200:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def new_home_site(self, ad_user_or_group_id:str, global_application_entitlement_id:str, global_desktop_entitlement_id:str, site_id:str) -> list:
"""Creates the given home site in the pod federation.
Requires ad_user_or_group_id, global_application_entitlement_id, global_desktop_entitlement_id, site_id as strings
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["ad_user_or_group_id"] = ad_user_or_group_id
data["global_application_entitlement_id"] = global_application_entitlement_id
data["global_desktop_entitlement_id"] = global_desktop_entitlement_id
data["site_id"] = ad_user_or_group_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/federation/v1/home-sites', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def delete_home_sites(self, homesite_ids:list) -> list:
"""Creates the given home site in the pod federation.
Requires ad_user_or_group_id, global_application_entitlement_id, global_desktop_entitlement_id, site_id as strings
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
data["homesite_ids"] = homesite_ids
json_data = json.dumps(data)
response = requests.delete(f'{self.url}/rest/federation/v1/home-sites', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json()
def get_user_home_site(self, user_id:str, global_application_entitlement_id:str="", global_desktop_entitlement_id:str="") -> list:
"""Creates the given home site in the pod federation.
Requires global_application_entitlement_id, global_desktop_entitlement_id, user_id as strings
Available for Horizon 8 2012 and later."""
headers = self.access_token
headers["Content-Type"] = 'application/json'
data = {}
if global_application_entitlement_id !="":
data["global_application_entitlement_id"] = global_application_entitlement_id
if global_desktop_entitlement_id !="":
data["global_desktop_entitlement_id"] = global_desktop_entitlement_id
data["user_id"] = user_id
json_data = json.dumps(data)
response = requests.post(f'{self.url}/rest/federation/v1/home-sites', verify=False, headers=headers, data = json_data)
if response.status_code == 400:
if "error_messages" in response.json():
error_message = (response.json())["error_messages"]
else:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
if response.status_code == 404:
error_message = (response.json())["error_message"]
raise Exception(f"Error {response.status_code}: {error_message}")
elif response.status_code == 403:
raise Exception(f"Error {response.status_code}: {response.reason}")
elif response.status_code != 204:
raise Exception(f"Error {response.status_code}: {response.reason}")
else:
try:
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise "Error: " + str(e)
else:
return response.json() |
9d7b81ee12b841bb27da083f75557d3ab46ee79e | 0x90shell/ipwn | /nmapscrape.py | 1,690 | 3.609375 | 4 | #!/usr/bin/env python
#
# This script simply parses the scans/sS.gnmap and scans/sU.gnmap files
# and places any open ports into a text file with the respective IP address
# in it. So for example, you should end up with a scans directory
# containing files such as 80.txt, 443.txt, 53.tct, etc.
# These files will contain the IP addresses that have that port open.
#
# Author: Alton Johnson
# Contact: alton.jx@gmail.com
# Updated: 04-06-2013
#
import re,os
from sys import argv
def help():
print "\n " + "-" * 52
print " Nmap Parser v1.5, Alton Johnson (alton.jx@gmail.com) "
print " " + "-" * 52
print "\n Usage: %s <gnmap file>" % argv[0]
print
exit()
def start(argv):
if len(argv) < 1:
help()
if not os.path.exists('open-ports'):
os.makedirs('open-ports')
target_file = open(argv[-1])
targett_file = target_file.read().split('\n')
for line in targett_file:
ip_address = line[line.find(":")+2:line.find("(")-1]
pattern = '([0-9]+)/open/(tcp|udp)/'
find_pattern = re.findall(pattern, line)
tcpwrapped_pattern = '([0-9]+)/open/tcp//tcpwrapped'
find_tcpwrapped = re.findall(tcpwrapped_pattern, line)
if find_pattern:
for i in find_pattern:
if i in find_tcpwrapped:
continue
tcp_file = open('open-ports/%s.txt' % i[0],'a')
tcp_file.write("%s\n" % ip_address)
tcp_file.close()
target_file.close()
print "Done. Check the \"open-ports\" folder for results."
if __name__ == "__main__":
try:
start(argv[1:])
except KeyboardInterrupt:
print "\nExiting. Closed by user (ctrl-c)."
except Exception, err:
print err
|
c9b1f05f480762fca13773ef228b0b92b90fc1a4 | Xancett/RandomPython | /mutable.py | 576 | 3.796875 | 4 | def my_number(something):
something += 10
print('Value inside function: ', something)
def my_word(something):
something += ' rocks'
print('Value inside function: ', something)
def my_list(list):
list.append('four')
print('Value inside function: ', list)
# Immutable types
width = 20
word = 'Python'
my_number(width)
print('Value outside function: ', width)
my_word(word)
print('Value outside function: ', word)
# Mutable types
someList = ['one', 'two', 'three']
my_list(someList)
print('Value outside function: ', someList) |
1a4daeb46fdb6fe583ff490bbc04f2791b8aa3bb | vezril/IEEEXtreme | /6.0/honey.py | 679 | 3.5625 | 4 | #!/usr/bin/python2.6
coord = raw_input()
(x1,y1,x2,y2) = coord.split(" ")
x1 = int(x1)
x2 = int(x2)
y1 = int(y1)
y2 = int(y2)
total = 0
while(True):
x0 = x2 - x1
y0 = y2 - y1
if(x0 == 0):
total = total + 2*y0
break
elif(y0 == 0):
if(y0 == 1):
total = total + 2
break
else:
total = total + 2*x0 - 1
break
if(x0 > 0):
x1 = x1 + 1
else:
x1 = x1 - 1
print "(" + str(y1) + "," + str(x1) + ")"
if(y0 > 0):
y1 = y1 + 1
else:
y1 = y1 - 1
total = total + 2
print "(" + str(y1) + "," + str(x1) + ")"
print total*10
|
7f265a5d9d58692a329156c456872eba784683b3 | AusBOM/serverless-tile-poc | /colour_map.py | 2,793 | 3.9375 | 4 | """Functions for generating a custom colour map."""
import numpy as np
import spectra
def make_colour_map(colours, indexes=None, size=256, gradient=True):
"""Make a colour map for a list of colours aligned to indexes.
Parameters
----------
colours : list of (spectra color objects or strings)
The list can contain spectra color objects or strings containing namded
colors or hexcodes.
indexes : list of ints
The index placements to tell when to move from one colour to the next
size : int
The size of the colour map.
gradient : bool
Whether to trasition between colours as a gradient (True) or jump
between at the indexes. (False)
Returns
-------
numpy ndarray(size,3) of float
The derived colour map.
"""
if not indexes:
# If indexes is not set, return an even continuous distribution.
colour_array = spectra.range(colours, size)
# Convert of Color objects to 2D numpy array of rgb and return
return np.asarray([c.rgb for c in colour_array])*255
# Otherwise, align the colour map to the indexes
# Find the colours between the first and second index.
run_size = indexes[1] - indexes[0] + 1
if gradient:
colour_run = spectra.range([colours[0], colours[1]], run_size)
colour_map = np.asarray([c.rgb for c in colour_run])*255
else:
colour_map = np.tile(np.asarray(spectra.html(colours[0]).rgb), (run_size, 1))*255
# Find the remaining colours values and concatenate into one array.
for run in range(1, len(indexes) - 1):
run_size = indexes[run+1] - indexes[run] + 1
if gradient:
colour_run = spectra.range([colours[run], colours[run+1]], run_size)
crt = np.asarray([c.rgb for c in colour_run])*255
else:
crt = np.tile(np.asarray(spectra.html(colours[run]).rgb), (run_size, 1))*255
# Note: To avoid overlap we cut off the last value from the current colour map
colour_map = np.concatenate((colour_map[:-1, :], crt), axis=0)
return colour_map
def split_colours(colours_list, colours_required):
"""Takes a list of colours and returns the list with required number of
colours instead.
Parameters
----------
colours_list : list of type 'string' or type spectra.color object.
The list of colours to create the range.
colours_required : int
The number of colours to be put in the returned list.
Returns
-------
list of type 'string'
A list with the appropriated number of colours created from the range
given by the colours_list.
"""
colour_range = spectra.range(colours_list, colours_required)
return [colour.hexcode for colour in colour_range]
|
fa1a3cd6afed7abee94ce088086531a65fb99d58 | Dian82/Assignments | /AdvancedComputerProgramming/ps1/ps1c.py | 982 | 4 | 4 | # Chen Hongzheng 17341015
# chenhzh37@mail2.sysu.edu.cn
# Part C: Finding the right amount to save away
# Initialization
semi_annual_raise = 0.07
return_rate = 0.04
portion_down_payment = 0.25
total_cost = 1000000
downpay_cost = total_cost*portion_down_payment
annual_salary = int(input("Enter the starting salary: "))
def cal(rate):
salary = annual_salary
current_savings = 0
for i in range(1,37):
current_savings += current_savings*return_rate/12 + salary/12*rate
if (i % 6 == 0):
salary *= (1+semi_annual_raise)
return current_savings
# Binary search
step = 0
l, r = 0, 10000
while (l + 1 < r):
step += 1
mid = (l+r)//2
savings = cal(mid/10000)
# print("{},{},{}".format(l,r,mid))
if (savings < downpay_cost-100):
l = mid
elif (savings > downpay_cost+100):
r = mid
else:
break
# Output
if (l + 1 < r):
print("Best savings rate: {}".format(mid/10000))
print("Steps in bisection search: {}".format(step))
else:
print("It is not possible to pay the down payment in three years.") |
daa9a2c783a467737d7370edd83947425e8c4214 | alex-cres/ConnectFourAI | /TestingBoard.py | 1,404 | 3.546875 | 4 | import ConnectGame as CG
class TestingBoard:
def __init__(self, number, testMatrix):
game = CG.ConnectGame()
result = game.initBoard(testMatrix[3])
if game.isGameOver():
if result[0] != testMatrix[0] or result[1] != testMatrix[1] or \
"".join(str(i) for i in result[2]) != testMatrix[2]:
print("Test #", str(number), "failed - ",
result, " - ", testMatrix)
else:
print("Test #", str(number), "passed - ",
result, " - ", testMatrix)
else:
if(testMatrix[0] == 0):
print("Test #", str(number), "passed - ",
result, " - ", testMatrix)
else:
print("Test #", str(number), "failed - ",
result, " - ", testMatrix)
if __name__ == "__main__":
testingMatrixes = [
# winner - 0/1/2,turn 1-based(if winner 0, put 0),
# remaining string positions, test string
# [1,7,"","0011223"],
# [1,7,"34455","001122334455"],
# [1,7,"","1122334"],
# [1,7,"","2233445"],
# [1,7,"","3344556"],
# [0,0,"","001122"],
[0, 0, "", "2435666543332100011134556654321000"]
]
for index, item in enumerate(testingMatrixes):
TestingBoard(index, item)
|
963db3a75f19b6a77f931acf321294ef05beebfd | league-python-student/level0-module1-nanonate32 | /_03_if_else/_1_unbirthday/Unbirthday.py | 445 | 3.90625 | 4 | from tkinter import Tk, messagebox, simpledialog
if __name__ == '__main__':
window = Tk()
window.withdraw()
birthday = simpledialog.askstring("", "When is your birthday? Respond using the format of month/day")
if birthday == "8/17":
messagebox.showinfo(title = None, message = "Happy birthday to you!")
else:
messagebox.showinfo(title = None, message = "Have a very merry unbirthday!")
window.mainloop() |
2eab9695831854c707f97784d59f3408787c45cb | SouthDrago/python-work | /basicPrac/functionPractices.py | 2,980 | 4.15625 | 4 | """
function can be defined as mulit arguments with *args
"""
from math import sqrt
from math import pi
city_prices = {'Charlotte': 183, 'Tampa': 220, 'Pittsburgh': 222, 'Los Angeles': 475}
singleday = 40
def shut_down(s):
arg = s.lower()
if arg=="yes":
return "Shutting down..."
elif arg=="no":
return "Shutdown aborted!"
else:
return "Sorry, I didn\'t understand you."
def distance_from_zero(distance):
input_type = type(distance)
if input_type is int or input_type is float:
return abs(distance)
else:
return "Not an integer or float!"
def area_of_circle(radius):
input_type = type(radius)
if input_type is int or input_type is float:
return pi*(radius**2)
else:
return "not a valid input!"
def hotel_cost(nights):
if type(nights) is int:
return nights*140
else:
return "Error"
def plane_ride_cost(city):
if type(city) is unicode:
return city_prices.get(city,0)
else:
return "Error"
def rental_car_cost(days):
if type(days) is int:
total = days*singleday
if days>=7:
return total-50
elif days>=3:
return total-20
else:
return total
else:
return "Error"
def trip_cost(city,days,spending_money):
ridercost = plane_ride_cost(city)
if ridercost=="Error":
return "not a valid input for city"
else:
hotelcost=hotel_cost(days)
if hotelcost=="Error":
return "not a valid input for days"
else:
return rental_car_cost(days)+ridercost+hotelcost+spending_money
def hotel_cost(nights):
return nights * 140
def add_monthly_interest(balance):
return balance * (1 + (0.15 / 12))
def make_payment(payment, balance):
new_balance = balance-payment
new_balance = add_monthly_interest(new_balance)
return "You still owe: " + str(new_balance)
print trip_cost("Los Angeles",5,600)
bill = hotel_cost(5)
print make_payment(100,bill)
print area_of_circle(5.0)
print shut_down("Nop")
print sqrt(13689)
print distance_from_zero(-10.0)
#Arbitrary number of arguments
m = 5
n = 13
def add_function(*args):
total = 0
for number in args:
total+=number
return total
print add_function(m,n)
"""
Anonymous Functions
Only we don't need to actually give the function a name;
it does its work and returns a value without one.
That's why the function the lambda creates is an anonymous function
pass the lambda to filter, filter uses the lambda to determine what to filter,
and the second argument is the list it does the filtering on
"""
squares=[x**2 for x in range(1,11)]
print filter(lambda x:(x>30 and x<70),squares)
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda c:(c!='X' and c!='x'),garbled)
print message
f = lambda Y,M,E,U,O:(1*U+10*O+100*Y)==(1*E+10*M)**2
print f(1,2,3,4,5) |
fd867fa8b204338ff8f7442c5b98e6e120303b44 | RichardSibi/friendly-guacamole | /WebscrapingIMDB.py | 452 | 3.59375 | 4 | from bs4 import BeautifulSoup
import requests
source = requests.get('http://www.imdb.com/search/title?release_date=" + year + “,” + year + “&title_type=feature')
soup = BeautifulSoup(source.content,'lxml')
i = 0
print("List of most popular movies for October 2021")
print()
for movie_sec in soup.find_all('div', class_ = 'lister-item-content'):
heading = movie_sec.h3.a.text
i += 1
print('{}) Movie: {}'.format(i,heading))
print() |
d4fa9a47a46b4a0190314d8e904fa38aa1e3b20b | JanMagne/GameOfLife | /gol.py | 3,173 | 4.0625 | 4 | """
Python 3.9.6 implementation of Conway's Game of Life, using Pygame to display.
The rules of GoL are as follow
1. Any live cell with two or three live neighbours survives.
2. Any dead cell with three live neighbours becomes a live cell.
3. All other live cells die in the next generation. Similarly, all other dead cells stay dead.
"""
import pygame, random
width = 1000
height = 1000
resolution = (width, height)
black = (0,0,0)
white = (255,255,255)
block_size = 20
num_blocks_x = width//block_size
num_blocks_y = height//block_size
def initialize_pygame_and_screen():
pygame.init()
#pygame.display.set_icon(pygame.image.load("logo.png"))
global screen
screen = pygame.display.set_mode(size=resolution)
pygame.display.set_caption("Game of Life")
if pygame.display.get_init():
print("Pygame display initialized OK")
def countNeighbors(i, j, matrix):
total = 0
# edges
if i == 0 or i == num_blocks_x-1 or j == 0 or j == num_blocks_y-1 :
return 2 #with 2 neighbors the cell is left as is
else:
for x in range(-1,2):
for y in range(-1,2):
if (x == 0 and y == 0):
continue
if matrix[i+x][j+y] == 1:
total = total + 1
return total
def updateMatrix(matrix):
new = createMatrix(num_blocks_x, num_blocks_y)
old = matrix.copy()
for i in range(num_blocks_x):
for j in range(num_blocks_y):
numNeighbors = countNeighbors(i , j, old)
if numNeighbors == 3:
new[i][j] = 1
elif matrix[i][j] == 1 and numNeighbors == 2:
new[i][j] = 1
else:
new[i][j] = 0
return new
def drawMatrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
x = i*block_size
y = j*block_size
if matrix[i][j]:
pygame.draw.polygon(screen, black, [(x,y),(x+block_size, y),(x+block_size, y+block_size),(x, y+block_size)])
else:
pygame.draw.polygon(screen, white, [(x,y),(x+block_size, y),(x+block_size, y+block_size),(x, y+block_size)])
def createMatrix(x, y, live=0):
""" Create a matrix of cells all set to 0 """
matrix = [[0]*num_blocks_x for i in range(num_blocks_y)]
for i in range(num_blocks_x):
for j in range(num_blocks_y):
if i == 0 or j == 0 or i == num_blocks_x-1 or j == num_blocks_y-1:
matrix[i][j] = 0
elif live == 0:
matrix[i][j] = 0
elif random.randint(0,100) < live:
matrix[i][j] = 1
else:
matrix[i][j] = 0
return matrix
def mouseAction(cells):
tmp = pygame.mouse.get_pressed()
isPressedLeft = tmp[0]
isPressedRight = tmp[2]
x, y = pygame.mouse.get_pos()
i = x//block_size
j = y//block_size
if isPressedLeft:
cells[i][j] = 1
if isPressedRight:
cells[i][j] = 0
return cells
def main():
initialize_pygame_and_screen()
clock = pygame.time.Clock()
cells = createMatrix(num_blocks_x, num_blocks_y)
while 1:
if pygame.key.get_pressed()[pygame.K_RIGHT]:
pygame.time.wait(200)
cells = updateMatrix(cells)
screen.fill(white)
cells = mouseAction(cells)
drawMatrix(cells)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
pygame.display.flip()
print("Mainloop done, quitting now")
quit()
if __name__ == '__main__':
main() |
a1ea04da42b892a0284152a2920e1ca7f441225b | jklemm/curso-python | /curso-2/exercicio_02.py | 179 | 3.8125 | 4 |
# entrada de dados
numero_obtido = input('Digite um número: ')
# processamento
mensagem = 'O número informado foi {}'.format(numero_obtido)
# saída de dados
print(mensagem)
|
a7a27230b25565d12f6a35e761af5e320713e26b | sriramb2000/memory | /src/main.py | 1,474 | 4 | 4 | from logic.game import *
if __name__ == "__main__":
# 2 - 4 for now
num_players = int(input("How many players?"))
while num_players > 4 or num_players < 2:
num_players = int(input("Please enter a number of players between 2 and 4: "))
# Should be even number >= 2*numplayers
num_cards = int(input("How many cards?"))
while num_cards < 2*num_players or num_cards > 52 or num_cards%2 == 1:
num_cards = int(input("Please enter an even number of cards greater or equal to twice the number of players and less than or equal to 52:"))
# request player names
playr_names = []
for i in range(num_players):
playr_names.append(input("Enter Player {}'s name: ".format(i+1)))
game = Game(num_players, num_cards, playr_names)
cur_player = 0
while not game.is_over():
game.display_game()
print("It's {}'s turn".format(playr_names[cur_player]))
#get valid input from player
choice = int(input("Which card do you pick? ")) - 1
while not game.is_valid_move(choice):
choice = int(input("Please pick a valid card: ")) - 1
#execute the move
res = game.take_turn(cur_player, choice)
if res == -1:
print("Bad luck. Maybe next time.")
cur_player += 1
if cur_player >= num_players:
cur_player = 0
game.display_game()
print("The winner is/are {}".format(game.get_winner()))
|
99649c93efbc6bd77eccb58fcdfa710e12c36ed9 | SubhamPanigrahi/Python_Programming | /area_triangle.py | 330 | 4.25 | 4 | # program to find the area of a triangle
import math # importing math module
def area(x,y,z):
s = (x + y + z)/2
ar = math.sqrt(s*(s-x)*(s-y)*(s-z)) # this is the formula to find area
return ar
a = int(input("Enter a side: "))
b = int(input("Enter a side: "))
c = int(input("Enter a side: "))
print(area(a,b,c))
|
1ccaa08b9ce85461c71e5684d194b4fbb1278b7b | cu-swe4s-fall-2019/hash-tables-alisoncleonard | /test_hash_functions.py | 1,106 | 3.578125 | 4 | """ Unit test file for hash_functions.py module
"""
import unittest
import hash_functions
class TestHashFunctions(unittest.TestCase):
def test_ascii_constant_key(self):
k = 107
e = 101
y = 121
ascii_total = k + e + y
N = 20
self.assertEqual(hash_functions.h_ascii('key', 20), ascii_total % N)
def test_ascii_key_not_string(self):
key = 8
N = 20
self.assertRaises(TypeError, hash_functions.h_ascii(key, N))
def test_rolling_constant_key(self):
k = 107 * 53**0
e = 101 * 53**1
y = 121 * 53**2
s = (k + e + y) % (2**64)
N = 20
p = hash_functions.h_rolling('key', 20, p=53, m=2**64)
q = s % N
self.assertEqual(p, q)
def test_rolling_key_not_string(self):
key = 17
N = 20
self.assertRaises(TypeError, hash_functions.h_rolling(key, N))
def test_python_key_not_string(self):
key = 4
N = 20
self.assertRaises(TypeError, hash_functions.h_python(key, N))
if __name__ == '__main__':
unittest.main()
|
a37efbcded2d121d8fd9429372a618d6933838c5 | john-adamsss/my_first_rep | /python_assign_2.py | 313 | 4.03125 | 4 | while True:
age = input("Are you a cigarette addict older than 75 years old? (Yes/No) : ")
if age == "Yes":
age = True
break
elif age == "No":
age = False
print(age)
break
else:
print("Please enter Yes/No only!")
continue
print(age) |
2170269fddd261043c676e1131b4e4a1f7556661 | bitnahian/info1110_s2_2019 | /helpdesk/special_sum2.py | 376 | 3.609375 | 4 | a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
d = int(input("Enter d: "))
e = int(input("Enter e: "))
nums = [a, b, c, d, e]
# Set up your counter
i = 0
sum_val = 0
while i < len(nums): # Standard idiom for looping over a list
# Do something
if nums[i] == 7:
i += 2
continue
sum_val += nums[i]
i+=1
|
21d2db86e29731860258223fac979d42c0a60500 | Zahed75/PythonCodePractice | /List_tuples.py | 627 | 4 | 4 | #List are mutable we can create edit list remove item etc
import copy
L_one=[1,2,3,4,5,6]
L_two=[6,47,9,2,3,5,9,10,13,12,15]
print(L_one)
"""
L_one.append("That thing i wanna say im sorry")
print(L_one)
L_two.sort()
print(L_two)
"""
L_two.pop()
print(L_two)
#copy function
L_three=copy.copy(L_one)
print(L_three)
L_three.remove(5)
print(L_three)
"""
Tuple are immutable user cannot the chage any obeject values
"""
name=('Zahed','mariam','Shihab','Afifa','Alisha')
print(name)
for x in name:
print(x)
test_tuple=(1,2,3,4,5,6,7,8,9,10)
print(id(test_tuple))
test_tuple('python',2,3) #immutable
print(test_tuple) |
d5d778155975f6745e5ad9ff11f4514d93eaf0a3 | KayDeVC/Python-CeV | /MUNDO1/Ex011_Tinta.py | 286 | 3.71875 | 4 | print('=====QUANTO DE TINTA?=====')
alt = float(input('Qual a altura da parede?'))
lar = float(input('Qual a largura da parede?'))
area = alt*lar
print('A área da parede é de {:.2f}m²!'.format(area))
print('Serão necessários {} litros de tinta para pintar a parede'.format(area/2)) |
8f176823a4b9f9e79101917c32188ad7cf79d9c0 | linhaidong/linux_program | /container_ssl/python_test/pytool-master/datastruct/finding-the-largest-or-smallest-N-items.py | 1,005 | 3.75 | 4 | # coding=utf-8
"""
查找最大或最小的N个元素
当N较小时,使用heapq:`nlargest()` & `nsmallest()`
当N较大时,先排序在切片:sorted(items)[:N]
当N为1时,使用`max()`,`min()`
:copyright: (c) 2015 by fangpeng.
:license: MIT, see LICENSE for more details.
"""
__date__ = '1/4/16'
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print heapq.nlargest(3, nums) # 查找最大的三个元素,正序 [42, 37, 23]
print heapq.nsmallest(3, nums) # 查找最小的三个元素,正序 [-4, 1, 2]
# 查找最大和最小
print min(nums), max(nums) # -4 42
# 将集合数据进行堆排序
heapq.heapify(nums)
print nums # [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
books = [
{"book": "Python Cookbook", 'price': 112},
{"book": "Redis In Action", 'price': 72},
{"book": "Fluent Python", 'price': 182},
{"book": "Code Complete", 'price': 148}
]
print heapq.nlargest(2, books, lambda x: x['price'])
|
c496349d47ffe4489e92753343490bd041e5ddca | martijngastkemper/timeflip-client-python | /timed_input.py | 1,645 | 3.984375 | 4 | import asyncio
import sys
async def timed_input(prompt, timeout=0):
"""Wait for input from the user
Note that user input is not available until the user pressed the enter or
return key.
Arguments:
prompt - text that is used to prompt the users response
timeout - the number of seconds to wait for input
Raises:
An asyncio.futures.TimeoutError is raised if the user does not provide
input within the specified timeout period.
Returns:
A string containing the users response
"""
# Write the prompt to stdout
print(prompt, flush=True)
loop = asyncio.get_event_loop()
queue = asyncio.Queue()
# The response callback will receive the users input and put it onto the
# queue in an independent task.
def response():
loop.create_task(queue.put(sys.stdin.readline()))
# Create a reader so that the response callback is invoked if the user
# provides input on stdin.
loop.add_reader(sys.stdin.fileno(), response)
try:
# Wait for an item to be placed on the queue. The only way this can
# happen is if the reader callback is invoked.
return (await asyncio.wait_for(queue.get(), timeout=timeout)).rstrip("\n")
except asyncio.TimeoutError:
# Make sure that any output to stdout or stderr that happens following
# this coroutine, happens on a new line.
sys.stdout.write('Too late!\n')
sys.stdout.flush()
finally:
# Whatever happens, we should remove the reader so that the callback
# never gets called.
loop.remove_reader(sys.stdin.fileno())
|
7fd318ff20ceff098aec23fd045fa819c540628e | HiDann0207/guess-num | /guess-num.py | 489 | 3.671875 | 4 | import random
start = input("請決定隨機數字範圍開始值:")
end = input ("請決定隨機數字範圍結束值:")
start = int(start)
end = int(end)
r = random.randint(start, end)
count = 0
while True:
count += 1 # count = count + 1
number = input('請輸入數字: ')
number = int(number)
if number == r:
print('猜了', count, "次,終於對了!")
break
elif number > r:
print('太大了喔~')
else:
print('再大一點!')
print('你已經猜', count, "次囉") |
0f78db9b2eae11e2009ff4b533ce22fead2bc45e | KEClaytor/Euler | /Euler2.py | 559 | 3.859375 | 4 | # Sum the even values of the Fibonacci sequence
# Consider only terms < 4*10^6
# Brute force method
if __name__ == "__main__":
# fmax = 90 # should give 44
fmax = 4000000
fibsum = 0
# The starting values
# Note that the third is always even
fa = 1
fb = 1
fc = 2
# print "Even terms in the Fib sequence are:", fa, fb, fc
while (fc < fmax):
fibsum += fc
fa = fc + fb
fb = fa + fc
fc = fa + fb
# print fa, fb, fc
print "The sum of fibonacci numbers <", fmax, "is:", fibsum
|
b1ec5ae38fd48986ffa6965e70f95c463db4b6e1 | zack4114/Amazon-Questions | /PrintNodesWithNoSibling.py | 758 | 4.09375 | 4 | # Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent.
# In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling.
class Tree(object):
def __init__(self,x):
self.data = x
self.left = None
self.right = None
def child(self,lx,rx):
if lx is not None:
self.left = Tree(lx)
if rx is not None:
self.right = Tree(rx)
def findNodes(root):
if root is None:
return
if root.left is None and root.right is not None:
print(root.right.data)
elif root.left is not None and root.right is None:
print(root.left.data)
findNodes(root.left)
findNodes(root.right)
root = Tree(1)
root.child(2,None)
root.left.child(None,4)
findNodes(root)
|
f5c76d332a693a126689b75f36a486c7c719dd54 | cianmcateer/Data_Final_CA | /part2.py | 465 | 3.515625 | 4 | from pymongo import MongoClient
def extract_json():
try:
"""Connect to mongod"""
client = MongoClient('localhost')
except:
print("Could not connect to mongo server")
"""Set database and collection we are going to extract from"""
db = client.final_data
students = db.students
"""Return all documents in students collection"""
return students.find({})
students = extract_json()
for s in students:
print(s)
|
33993968f8279b4b433485b0330ac826cca3d24d | gary-hsu/ProA-Python | /ProA Python Exercises and Challenges/Exercise 3 - String concatenation/code.py | 586 | 4.5 | 4 | # In this section, we will combine multiple strings into a single string. From this point on, I will no longer be providing the print statements.
example_string_1 = "EE58245"
example_string_2 = "EE58310"
example_string_3 = "EE58315"
# 1. Take all three strings and combine them into a single string, separating each string with a period.
# Name this new string combined_string. Use any method you prefer (using multiple plusses, .format method, f-strings)
# After you successfully complete the section, copy and paste the output of your print function into the quiz |
7b27cdb941007f198d86360d9d4d223886e442e8 | supby/algo_train | /reverseLetter.py | 2,106 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
def reverseWord(arr, start_i, end_i):
i = start_i
j = end_i
while i < j:
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
i += 1
j -= 1
def isSpaceArr(arr):
for ch in arr:
if ch != ' ':
return False
return True
def isNullOrEmpty(arr,i):
return arr[i] == '' or arr[i] == ' '
def reverseWords(arr):
arr_len = len(arr)
if arr_len == 0 or arr_len == 1 or isSpaceArr(arr):
return arr
start_word_index = 0
for i in range(arr_len):
if isNullOrEmpty(arr, i) and isNullOrEmpty(arr, start_word_index):
continue
if not isNullOrEmpty(arr, i) and isNullOrEmpty(arr, start_word_index):
start_word_index = i
if i == arr_len - 1 and not isNullOrEmpty(arr, i):
reverseWord(arr, start_word_index, i)
if isNullOrEmpty(arr,i) and not isNullOrEmpty(arr, start_word_index):
reverseWord(arr, start_word_index, i - 1)
start_word_index = i
return arr
for line in sys.stdin:
reversedArr = reverseWords([ch for ch in line])
print(''.join(reversedArr))
# Unit tests
def isArraysEqual(expected, actual):
if len(expected) != len(actual):
return False
for i in range(len(expected)):
if expected[i] != actual[i] or (expected[i].isupper() and not actual[i].isupper()) or (not expected[i].isupper() and actual[i].isupper()):
return False
return True
print(isArraysEqual(['I',' ','e','v','o','l',' ','y','f','i','x','a','T'],reverseWords(['I',' ','l','o','v','e',' ','T','a','x','i','f','y'])))
print(isArraysEqual(['I','','e','v','o','l',' ','y','f','i','x','a','T'],reverseWords(['I','','l','o','v','e',' ','T','a','x','i','f','y'])))
print(isArraysEqual(['','','I','','e','v','o','l','','','','y','f','i','x','a','T',''],reverseWords(['','','I','','l','o','v','e','','','','T','a','x','i','f','y',''])))
print(reverseWords(['','','I','','l','o','v','e','','','','T','a','x','i','f','y','']))
|
f3f12024b48c74eefcec2a94847639fd8bb391d0 | Shivampanwar/algo-ds | /Recursion/Replace Character Recursively.py | 314 | 3.609375 | 4 | import re
def replaceChar(inval, old, new):
if inval == '':
return ''
if inval[0] == old:
return new + replaceChar(inval[1:], old, new)
return inval[0] + replaceChar(inval[1:], old, new)
print replaceChar('abac', 'a', 'x')
s = "abbac"
replaced = re.sub('a', 'x', s)
print replaced
|
f9fd1561f833f6a402b149b40b1d0014c8ad460a | tmwitczak/iad-1 | /src/NeuralGasAlgorithm.py | 15,789 | 3.625 | 4 | # /////////////////////////////////////////////////////////////////// Imports #
import random
import statistics
from typing import List, Tuple
import math
import numpy
from matplotlib import pyplot
from src.file_reading import ClusteringData, DataMode, Vector, vector_from_list
# ////////////////////////////////////////////////////// Neural gas algorithm #
def neural_gas(
data_set: ClusteringData,
n: int,
*,
iterations: int = 10,
animation_rate: float = 0.001,
x_axis_vector_index: int = 0,
y_axis_vector_index: int = 1,
mode: DataMode = DataMode.DEFAULT) \
-> None:
""" Compute self-organising map using neural gas algorithm.
Parameters
----------
animation_rate : float
# TODO
data_set : ClusteringData
Data set for finding clusters.
n : int
Number of neurons in neural gas self-organising map.
iterations
Number of times the algorithm will be executed, the result with the
lowest quantisation error will be chosen.
x_axis_vector_index : int
Index of vector element to plot on x axis.
y_axis_vector_index : int
Index of vector element to plot on y axis.
mode : DataMode
Select whether data is normalised or standardised
"""
# ----------------------------------------------------------------------- #
# Choose appropriate data mode
vectors: Tuple[Vector, ...] = get_vectors_from_data_set(data_set, mode)
# Perform a given number of iterations of neural gas algorithm
# and choose the result with the lowest quantisation error
initial_neurons: List[Tuple[int, ...]] = []
quantisation_errors: List[float] = []
print('[ Neural Gas Network ]')
for i in range(iterations):
print_status_bar('> Iterations', i + 1, iterations)
# Select initial neurons as n random vectors from data set
initial_neurons.append(
pick_random_neurons(n, vectors))
# Perform neural gas algorithm and save quantisation error
quantisation_errors.append(
neural_gas_iteration(vectors, initial_neurons[i],
data_set.classes, data_set.parameter_names))
initial_neurons_with_lowest_error: Tuple[int, ...] \
= initial_neurons[quantisation_errors.index(min(quantisation_errors))]
# Draw animation for the best iteration
neural_gas_iteration(vectors, initial_neurons_with_lowest_error,
data_set.classes, data_set.parameter_names,
animate = True, animation_rate = animation_rate,
x_axis_vector_index = x_axis_vector_index,
y_axis_vector_index = y_axis_vector_index)
# /////////////////////////////////////////////////////////////////////////// #
def neural_gas_iteration(
vectors: Tuple[Vector, ...],
initial_neurons: Tuple[int, ...],
classes, # TODO
parameter_names, # TODO
*,
animate: bool = False,
animation_rate: float = 0.001,
x_axis_vector_index: int = 0,
y_axis_vector_index: int = 1) \
-> float:
""" TODO
"""
# ----------------------------------------------------------------------- #
# ....................................... Additional variables and settings
# Main loop control
should_iterate: bool = True
clusters = []
# Create and set up plot
if animate:
# Define keyboard support while plotting the graph
def on_key_down(event):
# Close current figure
if event.key == 'c':
nonlocal should_iterate
should_iterate = False
pyplot.close(pyplot.gcf())
# Save plot to file
elif event.key == 's':
pyplot.savefig('plot_neural gas.png')
hide_matplotlib_toolbar()
set_matplotlib_fontsize(16)
fig, ax = pyplot.subplots()
toggle_matplotlib_fullscreen()
fig.canvas.mpl_connect('key_press_event', on_key_down)
# Pick initial neurons ............................................. STEP 0
neurons: List[Vector] = [vectors[i] for i in initial_neurons]
# Select initial constants ......................................... STEP 0
maximum_iterations: int = 64
initial_radius: float = euclidean_distance(numpy.min(vectors, axis = 0),
numpy.max(vectors, axis = 0))
initial_rate: float = 0.05
# Perform a given number of iterations
for current_iteration in range(maximum_iterations):
if should_iterate:
# Calculate proper parameters for this iteration
neighbourhood_radius: float \
= calculate_neighbourhood_radius(current_iteration,
maximum_iterations,
initial_radius)
learning_rate: float \
= calculate_learning_rate(current_iteration,
maximum_iterations,
initial_rate)
best_matching_units: List[int] = []
# Randomly select an input vector .......................... STEP 1
for current_vector in get_random_shuffled_range(len(vectors)):
# For given vector, select Best Matching Unit .......... STEP 2
best_matching_unit: int \
= find_best_matching_unit(vectors[current_vector],
neurons)
best_matching_units.append(best_matching_unit)
# Get neurons within neighbourhood of BMU .............. STEP 3
bmu_neighbourhood: Tuple[int, ...] \
= get_best_matching_unit_neighbourhood(
neurons[best_matching_unit],
neighbourhood_radius,
neurons)
# Update neuron weights within the neighbourhood ....... STEP 4
for i in bmu_neighbourhood:
neurons[i] = neurons[i] \
+ learning_rate * calculate_neighbourhood_function(
neighbourhood_radius,
neurons[best_matching_unit],
neurons[i]) \
* (vectors[current_vector] - neurons[i])
# Check for dead neurons ................................... STEP 5
for i in range(len(neurons)):
unique, counts = numpy.unique(neurons, axis = 0,
return_counts = True)
if len(unique) < len(neurons):
if numpy.array_equal(neurons[i], unique[numpy.where(
counts == numpy.max(counts))[0][0]]):
neurons[i] = vectors[random.randint(0, len(neurons))]
# for u in unique:
# if euclidean_distance(neurons[i], u) < 0.0001:
# neurons[i] = vectors[random.randint(0, len(neurons))]
if i not in best_matching_units:
neurons[i] = vectors[random.randint(0, len(neurons))]
clusters = assign_data_to_nearest_clusters(vectors, neurons)
if animate:
draw_neural_gas(vectors, classes,
parameter_names,
x_axis_vector_index, y_axis_vector_index,
len(neurons),
neurons, clusters,
current_iteration)
pyplot.pause(animation_rate)
# centroids = calculate_centers_of_clusters(data, k, clusters)
# for centroid in previous_centroids:
# if numpy.array_equal(centroid, centroids):
# should_iterate = False
# break
# previous_centroids.append(centroids)
if animate:
pyplot.show()
#Compute quantisation error for all clusters
cluster_errors: List[float] = []
for n in range(len(neurons)):
vectors_in_nth_cluster = []
for x in range(len(clusters)):
if clusters[x] == n:
vectors_in_nth_cluster.append(vectors[x])
cluster_errors.append(numpy.std(vector_from_list(
vectors_in_nth_cluster)))
return sum(cluster_errors)
def get_best_matching_unit_neighbourhood(
best_matching_unit: Vector,
radius: float,
neurons: Tuple[Vector, ...]) \
-> Tuple[int, ...]:
neighbourhood: List[int] = []
for i in range(len(neurons)):
if euclidean_distance(best_matching_unit, neurons[i]) <= radius:
neighbourhood.append(i)
return tuple(neighbourhood)
def calculate_neighbourhood_radius(
current_iteration: int,
maximum_iterations: int,
initial_radius: float) \
-> float:
return sigma(initial_radius, current_iteration,
maximum_iterations / math.log(initial_radius))
def calculate_learning_rate(
current_iteration: int,
maximum_iterations: int,
initial_rate: float) \
-> float:
return sigma(initial_rate, current_iteration, maximum_iterations)
def calculate_neighbourhood_function(
t: int) \
-> float:
return numpy.e**(-((distance**2) / (2 * radius**2)))
def sigma(
o: float,
t: int,
l: float) \
-> float:
return o * numpy.e**(-(t / l))
def find_best_matching_unit(
vector: Vector,
neurons: Tuple[Vector, ...]) \
-> int:
distances: Tuple[float, ...] = tuple(
[euclidean_distance(neuron, vector)
for neuron in neurons])
return distances.index(min(distances))
def get_random_shuffled_range(
n: int) \
-> List[int]:
return random.sample(range(n), k = n)
# /////////////////////////////////////////////////////////////////////////// #
def get_vectors_from_data_set(
data_set: ClusteringData,
mode: DataMode = DataMode.DEFAULT) \
-> Tuple[Vector]:
""" Select appropriate mode of data from data set
"""
# ----------------------------------------------------------------------- #
if mode == DataMode.NORMALISED:
return data_set.data_normalised
elif mode == DataMode.STANDARDISED:
return data_set.data_standardised
else:
return data_set.data
# /////////////////////////////////////////////////////////////////////////// #
def get_column(
two_dimensional_list: List[List],
n: int) \
-> List:
""" Return n-th column of two dimensional list.
Parameters
----------
two_dimensional_list : List[List]
Two dimensional list of which the column should be returned.
n : int
Number of column to return.
Returns
-------
List
N-th column of provided two dimensional list.
"""
return [row[n] for row in two_dimensional_list]
# /////////////////////////////////////////////////////////////////////////// #
def pick_random_neurons(
n: int,
vectors: Tuple[Vector, ...]) \
-> Tuple[int, ...]:
""" Return indices of n random vectors
"""
return tuple(get_random_shuffled_range(len(vectors))[0:n])
# /////////////////////////////////////////////////////////////////////////// #
def euclidean_distance(
p: Vector,
q: Vector) \
-> float:
""" Compute Euclidean distance between p and q vectors
"""
return numpy.linalg.norm(p - q)
# /////////////////////////////////////////////////////////////////////////// #
def assign_data_to_nearest_clusters(
data: Tuple[Vector, ...],
centroids: Tuple[Vector, ...]) \
-> Tuple[int]:
clusters: List[int] = []
for vector in data:
lengths: Tuple[float] \
= tuple([euclidean_distance(vector, centroid)
for centroid in centroids])
clusters.append(lengths.index(min(lengths)))
return tuple(clusters)
# /////////////////////////////////////////////////////////////////////////// #
def draw_neural_gas(data, classes, names, n, m, k, centroids, clusters,
iteration_number):
# Get and clear current axes
ax = pyplot.gca()
ax.clear()
clustered_data = [[] for i in range(k)]
for i in range(len(data)):
clustered_data[clusters[i]].append([data[i][n], data[i][m]])
color_map = pyplot.get_cmap('rainbow')(numpy.linspace(0, 1, k))
markers: List[str] = ['o', 's', 'p', 'P', '*', 'D']
x = [[[] for j in range(len(set(classes)))] for i in range(k)]
y = [[[] for j in range(len(set(classes)))] for i in range(k)]
stats = [[0 for j in range(len(set(classes)))] for i in range(k)]
for i, vector in enumerate(data):
for j, cl in enumerate(set(classes)):
if classes[i] == cl:
x[clusters[i]][j].append(vector[n])
y[clusters[i]][j].append(vector[m])
stats[clusters[i]][j] += 1
for i in range(k):
for j, cl in enumerate(set(classes)):
ax.plot(x[i][j], y[i][j], markers[j % 6], color = color_map[i],
markersize = 6)
winning_class = [stats[i].index(max(stats[i])) for i in range(k)]
result = round(
statistics.mean([stats[i][winning_class[i]] / classes.count(
list(set(classes))[winning_class[i]]) for i in
range(k)]) * 100, 2)
for i in range(len(centroids)):
ax.plot(centroids[i][n],
centroids[i][m],
'^', color = color_map[i],
markersize = 18, markeredgewidth = 1.5,
markeredgecolor = 'k')
# Set axis parameters
ax.set(title = 'Zadanie 1 - Wykresy (Metoda Gazu Neuronowego)\nIteracja: '
+ str(iteration_number) + '\nSkuteczność: ' + str(
result)
+ '%',
xlabel = names[n],
ylabel = names[m])
# /////////////////////////////////////////////////////////////////////////// #
def calculate_centers_of_clusters(data, k, clusters) \
-> Tuple[Vector]:
centers: List[Vector] = []
clustered_data = [[] for i in range(k)]
for i in range(len(data)):
clustered_data[clusters[i]].append(data[i])
for i in range(k):
if clustered_data[i]:
centers.append(numpy.mean(clustered_data[i], axis = 0))
else:
centers.append(pick_random_centroids(data, k)[0])
return tuple(centers)
# /////////////////////////////////////////////////////////////////////////// #
def print_status_bar(
title: str,
a: int,
b: int,
n: int = 10) \
-> None:
print('\r', title, ': |', '=' * int((a / b) * n),
'-' if a != b else '',
' ' * (n - int((a / b) * n) - 1),
'| (', a, ' / ', b, ')',
sep = '', end = '', flush = True)
# /////////////////////////////////////////////////////////////////////////// #
def toggle_matplotlib_fullscreen():
pyplot.get_current_fig_manager().full_screen_toggle()
# /////////////////////////////////////////////////////////////////////////// #
def hide_matplotlib_toolbar():
pyplot.rcParams['toolbar'] = 'None'
# /////////////////////////////////////////////////////////////////////////// #
def set_matplotlib_fontsize(
size: int) \
-> None:
pyplot.rcParams.update({'font.size': size})
# /////////////////////////////////////////////////////////////////////////// #
|
fb1576aa961d8323fbbcfa1966a7994a49e76e9f | celestiel4562/github_exercise | /python課堂練習/1090608/01.開啟讀取csv檔案.py | 875 | 3.5 | 4 | """
import csv
fn=
with open("sample.csv",encoding="utf-8 sig") as csvFile: #開啟csv
csvReader=csv.reader(csvFile) #讀取csv建立reader物件
listReport=list(csvReader) #將資料轉成list(串列)
print(listReport)
"""
"""
#當csv檔案的編碼為UTF-8
import csv
fn=r"C:\Users\ASUS\Desktop\PYTHON\課堂練習\1090608\opendata106N0101.csv"
#fn="C:\\Users\\ASUS\\Desktop\\PYTHON\\課堂練習\\1090608\\opendata106N0101.csv"
#fn="C:/Users/ASUS/Desktop/PYTHON/課堂練習/1090608/opendata106N0101.csv"
with open(fn,encoding="utf-8 sig") as csv_file:
csv_reader=csv.reader(csv_file)
csvlist=list(csv_reader)
print(csvlist)
"""
"""
#當csv檔案的編碼為ANSI
fn=r"C:\Users\ASUS\Desktop\PYTHON\課堂練習\1090608\sample_ansi.csv"
with open(fn) as csvFile:
csvReader=csv.reader(csvFile)
listReport=list(csvReader)
print(listReport)
""" |
649619e67d24edb23908dd1763aa751139c766b3 | Shree24/acadview | /assignment14.py | 822 | 3.71875 | 4 | # QUESTION 1
f=open("abc","r")
a=(f.readlines()) # read lines of a file
a.reverse()
n=int(input("enter no. of lines"))
for i in range(0,n):
print(a[i])
f.close
# END
# QUESTION 2
d="python"
f=open("abc","r") # COUNT FREQUENCY OF WORDS IN FILE
b=f.read()
c=b.split()
e=b.count(d)
print(e)
#END
# QUESTION 3
f=open("abc","r")
q=(f.readlines()) # COPY CONTENTS OF A FILE
t=open("cd","a")
t.writelines(q)
# END
# QUESTION 4
with open("abc")as f,open("cd")as f1:
for line1,line2 in zip(f,f1):
print(line1+line2)
# END
# QUESTION 5
import random
afile=open("Random.txt","w")
for i in range(int(input("how many random numbers?:"))):
line=str(random.randint(1,10))
afile.write(line)
print(line)
afile.close()
|
d0f39c9b1707d72eef7b939840781558bd15d426 | euanstirling/udemy_2021_complete_bootcamp | /my_work_python_2021/section_3_objects_and_data_structures/objects_and_data_structures.py | 1,260 | 4.3125 | 4 |
#! OBJECTS AND DATA STRUCTURES
# * Assigning a variable name
# * use lower case and avoid keywords like list and str (editor will highlight a key word if used)
# * You can reasign variables to different data types
my_dogs = 2
my_dogs = ["sammy", "frankie"]
#! You need to be aware of type()
# a = 5
# a = 10
# a = a + a
# print(a)
# print(type(a))
# * Assign varaibles and apply logic
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)
# * Because strings are ordered sequences it means we can use indexing and slicing to grab sub-sections of the string. We use [] to refer to index location
# * You can also use reverse indexing (last letter would be -1)
# * Slicing - grab a subsection of multiple characters
# * [start:stop:stop]
# * start is a numerical index for the slice start
# * stop is the index you go up to but not include
# * step is the size of the jump you take
print('this is also a string')
print("I'm going on a run")
print("hello world one")
print("hellow world two")
print("hello \nworld") # * \n formats onto next line
# * \t formats a tab into the string \n\t is new line and a tab
print("hello \n\tworld")
# * Lenght of a string (includes all characters including spaces)
print(len("I 'am"))
|
88477493f6568540fef7267ce5eccb0b355e04ef | whsqkaak/CodingTrainingStudy | /stackqueue/printer.py | 628 | 3.734375 | 4 | from collections import deque
def solution(priorities, location):
answer = 0
deque_priorities = deque(priorities)
while len(deque_priorities) > 0:
max_priority = max(deque_priorities)
j = deque_priorities.popleft()
location -= 1
if j < max_priority:
deque_priorities.append(j)
if location < 0:
location = len(deque_priorities) - 1
else:
answer += 1
if location < 0:
return answer
return answer
if __name__ == "__main__":
print(solution([2,1,3,2], 2)) |
94dc9619ebdfb5326d30507b6890964630329da2 | terpator/study | /Функции. Часть 1/dop_domashka_2.py | 1,132 | 4.25 | 4 | """
Число-палиндром с обеих сторон (справа налево и слева направо) читается
одинаково. Самое большое число-палиндром, полученное умножением двух
двузначных чисел: 9009 = 91 × 99. Найдите самый большой палиндром, полученный
умножением двух трехзначных чисел. Выведите значение этого палиндрома и то,
произведением каких чисел он является.
"""
def palin():
palindrom = 0
for x in range(100, 1000):
for y in range(100, 1000):
tmp = str(x * y)
if tmp == tmp[::-1]:
if int(tmp) > palindrom:
palindrom = int(tmp)
x_itog = x
y_itog = y
somelist = [palindrom, x_itog, y_itog]
return somelist
somelist = palin()
print("Палиндром равен", somelist[0])
print("Множители: ", somelist[1], somelist[2])
|
84102e5ea4a6f57eb784f964a8d52207d969a126 | Bharqgav/Qsamp | /Assignment Python/Even Indexes.py | 251 | 4.09375 | 4 | #Please write a program which accepts a string from
#console and print the characters that have even indexes.
import sys
a = raw_input("Enter a string ")
even = a[0]
b = 2
for b in range(2,len(a)):
if b%2 == 0:
even = even+a[b]
print even
|
8c84cbe6ab0ecd8d34d7f9d4459016e3a23678f4 | YuliaFeldman/Mathematical-Logic | /predicates/semantics_test.py | 4,945 | 3.71875 | 4 | # (c) This file is part of the course
# Mathematical Logic through Programming
# by Gonczarowski and Nisan.
# File name: predicates/semantics_test.py
"""Tests for the predicates.semantics module."""
from predicates.syntax import *
from predicates.semantics import *
def test_evaluate_term(debug=False):
model = Model({'0', '1'}, {'c': '1'}, {},
{'plus': {('0', '0'): '0', ('0', '1'): '1', ('1', '1'): '0',
('1', '0'): '1'}})
if debug:
print('In the model', model)
for s,expected_value in [['c', '1'], ['plus(c,c)', '0'],
['plus(c,plus(c,c))', '1']]:
term = Term.parse(s)
value = model.evaluate_term(term)
if debug:
print('The value of', term, 'is', value)
assert value == expected_value
assignment = {'x': '1', 'y': '0'}
for s,expected_value in [['x', '1'], ['plus(x,c)', '0'],
['plus(x,y)', '1']]:
term = Term.parse(s)
value = model.evaluate_term(term, assignment)
if debug:
print('The value of', term, 'with assignment x=1 y=0 is', value)
assert value == expected_value
def test_evaluate_formula(debug=False):
model = Model({'0', '1', '2'}, {'0': '0'}, {'Pz': {('0',)}},
{'p1': {('0',): '1', ('1',): '2', ('2',): '0'}})
if debug:
print('In the model', model)
for s,assignment,expected_value in [
('Pz(0)',{},True), ('0=p1(0)', {}, False),
('Pz(p1(x))', {'x': '2'}, True), ('(p1(0)=0|0=p1(0))', {}, False),
('Ax[Ey[p1(y)=x]]', {}, True)]:
formula = Formula.parse(s)
value = model.evaluate_formula(formula, assignment)
if debug:
print('The value of', formula, 'with assignment', assignment, 'is',
value)
assert value == expected_value
universe = {0,1,2}
pairs = {(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)}
all_formula = Formula.parse('Ax[Ay[R(x,y)]]')
exists_formula = Formula.parse('Ex[Ey[~R(x,y)]]')
model = Model(universe, {}, {'R': pairs})
if debug:
print('In the model', model)
value = model.evaluate_formula(all_formula)
if debug:
print('The value of', all_formula, 'is', value)
assert value
value = model.evaluate_formula(exists_formula)
if debug:
print('The value of', exists_formula, 'is', value)
assert not value
for exclude in pairs:
model = Model(universe, {}, {'R': (pairs-{exclude})})
if debug:
print('In the model', model)
value = model.evaluate_formula(all_formula)
if debug:
print('The value of', all_formula, 'is', value)
assert not value
value = model.evaluate_formula(exists_formula)
if debug:
print('The value of', exists_formula, 'is', value)
assert value
def test_is_model_of(debug=False):
pairs = {('a', 'a'), ('a', 'b'), ('b', 'a')}
model = Model({'a', 'b'}, {'bob': 'a'}, {'Friends': pairs})
f0 = Formula.parse('Friends(bob,bob)')
f1 = Formula.parse('Friends(bob,y)')
f2 = Formula.parse('Friends(x,bob)')
f3 = Formula.parse('Friends(x,y)')
if debug:
print('The model', model, '...')
for formulas,expected_result in [
({f1}, True), ({f2},True), ({f1, f2}, True), ({f3}, False),
({f1,f2,f3}, False), ({f0,f3}, False)]:
result = model.is_model_of(frozenset(formulas))
if debug:
print('... is said', '' if result else 'not', 'to satisfy',
formulas)
assert result == expected_result
formula = Formula.parse('(F(z,a)->z=b)')
model = Model({'a', 'b'}, {'a': 'a', 'b': 'b'},
{'F': {('a', 'a'), ('b', 'b')}})
if debug:
print('The model', model, '...')
result = model.is_model_of(frozenset({formula}))
if debug:
print('... is said', '' if result else 'not', 'to satisfy', formula)
assert not result
universe = {0,1,2}
pairs = {(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)}
formula = Formula.parse('R(x,y)')
model = Model(universe, {}, {'R': pairs})
if debug:
print('The model', model, '...')
result = model.is_model_of(frozenset({formula}))
if debug:
print('... is said', '' if result else 'not', 'to satisfy', formula)
assert result
for exclude in pairs:
model = Model(universe, {}, {'R': (pairs-{exclude})})
if debug:
print('The model', model, '...')
result = model.is_model_of(frozenset({formula}))
if debug:
print('... is said', '' if result else 'not', 'to satisfy', formula)
assert not result
def test_ex7(debug=False):
test_evaluate_term(debug)
test_evaluate_formula(debug)
test_is_model_of(debug)
def test_all(debug=False):
test_ex7(debug)
|
4c1867d3871178ac6f950d47472aad1921d53254 | vinaykumar7686/Algorithms | /Algorithms/Searching/Linear_Searching.py | 741 | 3.984375 | 4 | # Time Complexity: O(n)
class Linear_Searching:
def __init__(self):
self.num=0
self.arr=[]
def accept(self):
n= int (input("Enter the size of array: "))
print('Enter the Array Elements')
while n!=0:
n-=1
self.arr.append(int(input()))
self.num=int(input("Enter the number to be searched: "))
def l_search(self):
num=self.num
arr=self.arr
res=-1
for i,j in enumerate(arr):
if j==num:
res=i
if res==-1:
print('Not Found')
else:
print(f'Number Found at Index {res}')
if __name__ == "__main__":
ls=Linear_Searching()
ls.accept()
ls.l_search()
|
8ea704d521ced6591cc62573dcd8c62161e6f8d1 | vicch/leetcode | /0100-0199/0125-valid-palindrome/0125-valid-palindrome-1.py | 451 | 3.578125 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# Filter out non-alphanumeric characters and lowercase all characters
s = "".join(c.lower() for c in s if c.isalnum())
l = len(s)
for i in range(l // 2):
# Compare char pairs from head and tail
if s[i] != s[l-i-1]:
return False
return True
|
fd6078e4dd76d3ad954006d545c63a36da1e0963 | anirudhRowjee/pyray | /vector.py | 3,032 | 4.28125 | 4 | """
Vector Object
Author: Anirudh Rowjee
Data:
1. X, Y and Z Co-ordinates
2. Magnitude - square root of (X^2 + Y^2 + Z^2)
3. Normalize/Direction - Unit Vector in Direction of Vector
Operations
1. Dot Product with Other Vector
2. Addition with other vector
3. Subtraction with other vectors
4. Scalar Multiplication
5. Scalar division
"""
import math
class Vector:
"""
Implementation of Vector Object
"""
def getMagnitude(self):
"""
return the magnitude of the vector
"""
return math.sqrt((self.x ** 2) + (self.y ** 2) + (self.z ** 2))
def getDirection(self):
"""
return the normalized / unit vector of the current vector
"""
return list(map(lambda x: x / self.magnitude, (self.x, self.y, self.z)))
def __init__(self, x=0.0, y=0.0, z=0.0, *args, **kwargs):
"""
constructor method for Vector Object
@param x: float => x co-ordinate
@param y: float => y co-ordinate
@param z: float => z co-ordinate
"""
if x == None or y == None or z == None:
raise TypeError("Inputs cannot be None.")
self.x = x
self.y = y
self.z = z
self.magnitude = self.getMagnitude()
self.direction = self.getDirection()
def __str__(self):
return f"({self.x}, {self.y}, {self.z})"
def dot(self, other):
"""
dot product of this vector and the other one
"""
return sum((self.x * other.x, self.y * other.y, self.z * other.z))
def __eq__(self, other):
"""
check for equality of two vectors
"""
return all((self.x == other.x, self.y == other.y, self.z == other.z))
def __add__(self, other):
"""
scalar addition of two vectors
"""
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
"""
scalar subtraction of two vectors
"""
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
"""
scalar multiplication of a vector
"""
if isinstance(other, (int, float)):
# this is expected as we want to do scalar multiplication
return Vector(self.x * other, self.y * other, self.z * other)
else:
# we wanted an int or a float, so we raise a TypeError
raise TypeError("Vectors can only be multiplied with numbers")
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
"""
scalar division of a vector
"""
if isinstance(other, (int, float)):
# this is expected as we want to do scalar multiplication
return Vector(self.x / other, self.y / other, self.z / other)
else:
# we wanted an int or a float, so we raise a TypeError
raise TypeError("Vectors can only be multiplied with numbers")
|
df1baaaf7ffdb2bf5de4ac4522a33964ab84d6c9 | madhavmurthy93/python-practice | /arrays/quick_sort.py | 1,191 | 3.859375 | 4 | def quicksort(a, left, right):
if (left < right):
medianof3pivot(a, left, right)
pivot = partition(a, left, right - 1)
quicksort(a, left, pivot - 1)
quicksort(a, pivot + 1, right)
def partition(a, left, right):
pivot = a[right]
i = left
j = right - 1
while(i < j):
while (a[i] < pivot):
i += 1
while(a[j] > pivot):
j -= 1
if (i < j):
temp = a[i]
a[i] = a[j]
a[j] = temp
i += 1
j -= 1
else:
break
a[right] = a[i]
a[i] = pivot
return i
def medianof3pivot(a, left, right):
mid = (left + right) / 2
if (a[mid] < a[left]):
temp = a[left]
a[left] = a[mid]
a[mid] = temp
if (a[right] < a[left]):
temp = a[left]
a[left] = a[right]
a[right] = temp
if (a[right] < a[mid]):
temp = a[mid]
a[mid] = a[right]
a[right] = temp
temp = a[mid]
a[mid] = a[right - 1]
a[right - 1] = temp
def main():
a = [3, 5, 2, 1, 9, 8, 6, 7]
quicksort(a, 0, len(a) - 1)
print a
if __name__ == '__main__':
main()
|
dc3f4e6235ddd4569e5d8eb9e337375d4cafc61a | Sangeethakarthikeyan/CS-2 | /dataset_nsw.py | 607 | 4.15625 | 4 | import sys
#prompt the user for a file name
fname=input('Enter a file name: ')
# open the file or print a message if the file doesnt exist
try:
fhand=open(fname)
except:
print('File cannot be opened',fname)
sys.exit()
# Loop for operating on each line of the file
total=0
for line in fhand:
field=line.split('|') #splitting into different fields with | as a separator
if field[1]=='Central': # If second field is central
number=int(field[2]) # assign the third field to number
total=total+number # To find the total
print('Total approvals in Central district of the year 2016: ', total)
|
8aad5500d47c2af7c05737958af279bed59ca04c | Agent215/ScraperOnFlask | /testScrape.py | 1,400 | 3.625 | 4 |
#Abraham Schultz
#This is the test script for a proposed webscraper
#The webscraper will try and scrape course requirements for temple CIS
# get the request module and name it as uReq for future use
from urllib.request import urlopen
#get the beautifulSoup module and name as soup
from bs4 import BeautifulSoup as soup
def testScrape():
returnList = []
my_url ="https://bulletin.temple.edu/undergraduate/science-technology/computer-information-science/computer-science-bs/#requirementstext"
#opening up connection and grabbing the page
uClient = urlopen(my_url)
# read page html content to variable
page_html = uClient.read()
#close page connection
uClient.close()
# html parsing
page_soup = soup(page_html,"html.parser")
# grabs each course requirment. does not grab the
# or requirements. will do later
containers = page_soup.findAll("tr",{"class":"even"})
# for now just grab one course
# we will create a loop later that grabs all
contain = containers[20]
crn = contain.td.div.a["title"]
name = contain.next.next.next.next.next.next
#print out the course number!
print(crn)
#this is stupid for now but shows you what we could do
#prints out the name of the course
print(name)
returnList.append(crn)
returnList.append(name)
return returnList
print (len(containers))
if __name__ == "__main__":
print(testScrape()) |
53115dfcd1ebfab20035ccfc14a7ce107dd26c98 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEU3_Architecture_GP/src/day2/04-fileio03.py | 1,041 | 3.53125 | 4 | # lets parse some numbers
# argv and argc take in command line args
import sys
if len(sys.argv) != 2:
print("usage: 03-fileio02.py filename")
sys.exit(1)
try:
with open(sys.argv[1]) as f:
for line in f:
# split line before and after comment symbol
comment_split = line.split("#")
# extract our number
<<<<<<< HEAD
num = comment_split[0].strip() # trim whitespace
if num == '':
continue # ignore blank lines
=======
num = comment_split[0].strip() # trim whitespace
if num == "":
continue # ignore blank lines
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# convert our binary string to a number
x = int(num, 2)
# print the x in bin and dec
print(f"{x:08b}: {x:d}")
except FileNotFoundError:
print(f"{sys.argv[0]}: {sys.argv[1]} not found")
<<<<<<< HEAD
sys.exit(2)
=======
sys.exit(2)
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
|
3d02623057d8eccc316f42239e36b0587767d6a4 | Prashant414/python | /qn 43.py | 358 | 4.40625 | 4 | # # Write a program to find the factorial value of any number entered through the keyboard.
# def fact (n):
# if n==0 or n==1:
# return 1
# else:
# return n*fact(n-1)
# n=int(input("value of n"))
# fact(n)
# print(fact(n))
#
n=3
fact=1
for i in range(n,0,-1):
if n==0:
fact=fact*1
else:
fact=fact*i
print(fact) |
e0bf75533ca259480827cc08b32f9a12d9383185 | sarveswara-rao/Object-oriented-programming-in-python | /first_class.py | 395 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 06:49:14 2019
@author: sarveswara rao
"""
# to create a class, we have to use the class keyword
class Dog:
# constructer for the class
def __init__(self, name, age):
self.name = name
self.age = age
# instantiating the class to create a oz object
oz = Dog("chunnu", 6)
print(oz)
print(f"{oz.name} is {oz.age} year(s) old.") |
2ef807c0fcb6d13ed4bfc3fbb66f4806beb3d145 | onsare/oop | /oop.py | 1,791 | 4.40625 | 4 |
#methods
class Book(object):
"""Methods are basically functions within
a class. The first definition of a method
has to be a reference "self" to the instance
of the class
"""
def __init__(self, name):
self.name = name
#constructor
"""
The __init__ keyword acts as a constructor in python
Though strictly speaking python does not have its own
explicit constructor method like other languages like C++
"""
def __init__(self, name):
self.name = name
#Destructor
"""
what holds true for python constructor is also true for destructors
the keyword __del__ is used in place of a destructor
"""
class Book(object):
def __init__(self,name):
self.name = name
def __del__(self):
print "Destructor initiated"
# Inheritance
class Book(object):
def __init__(self, name , genre, author):
self.name = name
self.genre = genre
self.author = author
class The_NoteBook(Book):
"""The_NoteBook class inherits all the Books property
such that, Everything that the Book class has, is contained
in the The_Notebook class
"""
def __init__(self, arg):
self.arg = arg
#Data Abstraction and Encapsulation
class Book(object):
"""By initializing the book class objects with
double underscore, we are simpy making the clas
inaccessible from outside the method.
class Encapsulation(object):
def __init__(self, a, b, c):
self.public = a
self.__private = b
self.__protected = c
"""
def __init__(self, name , genre, author):
self.name = name
self.__genre = genre
self._author = author
class The_NoteBook(Book):
"""The_NoteBook class inherits all the Books property
such that, Everything that the Book class has, is contained
in the The_Notebook class
"""
def __init__(self, arg):
self.arg = arg
|
b862f7b11e1b928dc7edc00b93fca472dad44d7c | sharmarkara/Data-structure-Programs | /2 Matrix Programs/2 Spiral matrix.py | 1,586 | 4.375 | 4 | def spiralMatrixPrint(row, col, arr):
# Defining the boundaries of the matrix.
top = 0
bottom = row-1
left = 0
right = col - 1
# Defining the direction in which the array is to be traversed.
dir = 0
while (top <= bottom and left <=right):
if dir ==0:
for i in range(left,right+1): # moving left->right
print (arr[top][i], end=" ")
# Since we have traversed the whole first
# row, move down to the next row.
top +=1
dir = 1
elif dir ==1:
for i in range(top,bottom+1): # moving top->bottom
print (arr[i][right], end=" ")
# Since we have traversed the whole last
# column, move down to the previous column.
right -=1
dir = 2
elif dir ==2:
for i in range(right,left-1,-1): # moving right->left
print (arr[bottom][i], end=" ")
# Since we have traversed the whole last
# row, move down to the previous row.
bottom -=1
dir = 3
elif dir ==3:
for i in range(bottom,top-1,-1): # moving bottom->top
print (arr[i][left], end=" ")
# Since we have traversed the whole first
# column, move down to the next column.
left +=1
dir = 0
array = [[1,2,3,4],
[12,13,14,5],
[11,16,15,6],
[10,9,8,7]]
spiralMatrixPrint(4, 4, array) |
ce8f97238f56c2460f6c5510f4dea0c1b425d17a | ramtiwary/week_1 | /Matplotlib _Piechart.py | 1,616 | 4.09375 | 4 | #1.create a pie chart of the popularity of programming Languages.
import matplotlib.pyplot as plt
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
explode = (0.1,0,0,0,0,0)
plt.pie(Popularity, explode=explode, labels=languages,colors=colors,
autopct='%1.1f%%',shadow=True,startangle=140)
plt.axis('equal')
plt.show()
#2.create a pie chart with a title of the popularity of programming Languages
#import matplotlib.pyplot as plt
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
explode = (0.1,0,0,0,0,0)
plt.pie(Popularity, explode=explode, labels=languages,colors=colors,
autopct='%1.1f%%',shadow=True,startangle=140)
plt.axis('equal')
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2018 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5})
plt.show()
#3.a pie chart of gold medal achievements of five most successful countries in 2016 Summer Olympics.
# Read the data from a csv file
import pandas as pd
df = pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = [0.1,0,0,0,0]
plt.pie(medal_data, lables=country_data, explode = explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in 2016 Summer Olympics")
plt.show() |
99fe4e60a3b8a73b5abc82e2c77e00219328b88d | tedyeung/Python- | /python_cc/dic.py | 476 | 3.71875 | 4 | # Dictiaries
users = {
'first_name': 'Slvko',
'last_name': 'Popovic',
'age': 35,
'city': 'Pompano Beach'
}
print (users['first_name'])
print (users['last_name'])
print (users['age'])
print (users['city'])
print (users)
# loop
print('************ LOOP ************************************')
for key, user in users.items():
print('\nKey:' + key )
print('Value: ' + str(user))
print('***********************************************************')
|
c622c7e72d798aac098135f4bfea1ee8b25ec048 | shehryarbajwa/Algorithms--Datastructures | /algoexpert/hatchways/adjacency_list.py | 4,811 | 3.65625 | 4 | import unittest
class Graph:
def __init__(self, vertices, is_directed=False):
self.vertices = vertices
self.adjacency_list = {}
self.is_directed = is_directed
for v in vertices:
self.adjacency_list[v] = []
def add_edge(self, source, destination):
self.adjacency_list[source].append(destination)
if not self.is_directed:
self.adjacency_list[destination].append(source)
def contains(self, source, destination):
for v in self.adjacency_list[source]:
if v == destination:
return True
return False
def remove_edge(self, source, destination):
self.adjacency_list[source].remove(destination)
if not self.is_directed:
self.adjacency_list[destination].remove(source)
def print_adjacency_list(self):
for node in self.adjacency_list:
print(node, ' -> ', self.adjacency_list[node])
def degree(self, vertex):
degree = len(self.adjacency_list[vertex])
return degree
def BFS(self, root):
visited = []
queue = [root]
while queue:
current = queue.pop(0)
if current not in visited:
visited.append(current)
neighbours = self.adjacency_list[current]
for neighbour in neighbours:
queue.append(neighbour)
return visited
def DFS(self, root, visited):
visited.append(root)
for v in self.adjacency_list[root]:
if v not in visited:
self.DFS(v, visited)
return visited
def is_cyclic_util(self, index, vertex, visited, parentNode):
visited[index] = vertex
for i, vertice in enumerate(self.adjacency_list[vertex]):
if vertice not in visited:
if self.is_cyclic_util(i, vertice, visited, vertex):
return True
elif parentNode != i:
return True
return False
def is_cyclic(self, start):
colors = { node: "WHITE" for node in self.adjacency_list}
colors[start] = "GRAY"
def find_cycle(graph, start):
colors = { node : "WHITE" for node in graph }
print(colors)
# colors[start] = "GRAY"
# stack = [(None, start)] # store edge, but at this point we have not visited one
# while stack:
# (prev, node) = stack.pop() # get stored edge
# for neighbor in graph[node]:
# if neighbor == prev:
# pass # don't travel back along the same edge we came from
# elif colors[neighbor] == "GRAY":
# return True
# else: # can't be anything else than WHITE...
# colors[neighbor] = "GRAY"
# stack.append((node, neighbor)) # push edge on stack
# return False
nodes = ["A","B","C","D","E"]
graph = Graph(nodes, True)
graph.add_edge('A', 'B')
graph.add_edge('A', 'C')
graph.add_edge('A', 'E')
graph.add_edge('B', 'E')
graph.add_edge('B', 'A')
graph.add_edge('C', 'A')
graph.add_edge('C', 'D')
graph.add_edge('D', 'C')
graph.add_edge('E', 'A')
graph.add_edge('E', 'B')
graph.print_adjacency_list()
print(graph.is_cyclic())
# class Tests(unittest.TestCase):
# def test_case_1(self):
# nodes = ["A","B","C","D","E"]
# graph = Graph(nodes, True)
# graph.add_edge('A', 'B')
# graph.add_edge('B', 'C')
# graph.add_edge('C', 'D')
# graph.add_edge('E', 'D')
# graph.add_edge('E', 'A')
# self.assertEqual(graph.BFS('A'),['A', 'B', 'C', 'D'])
# self.assertEqual(graph.contains('A','E'), False)
# self.assertEqual(graph.contains('A','B'), True)
# def test_case_2(self):
# nodes = ["A","B","C","D","E"]
# graph = Graph(nodes, True)
# graph.add_edge('A', 'B')
# graph.add_edge('B', 'C')
# graph.add_edge('C', 'D')
# graph.add_edge('E', 'D')
# graph.add_edge('E', 'A')
# self.assertEqual(graph.degree('E'),2)
# def test_case_3(self):
# nodes = ["A","B","C","D","E"]
# graph = Graph(nodes, True)
# graph.add_edge('A', 'B')
# graph.add_edge('B', 'C')
# graph.add_edge('C', 'D')
# graph.add_edge('E', 'D')
# graph.add_edge('E', 'A')
# self.assertEqual(graph.degree('A'),1)
# def test_case_4(self):
# nodes = ["A","B","C","D","E"]
# graph = Graph(nodes, False)
# graph.add_edge('A', 'B')
# graph.add_edge('B', 'C')
# graph.add_edge('C', 'D')
# graph.add_edge('E', 'D')
# graph.add_edge('E', 'A')
# self.assertEqual(graph.degree('A'),2)
# if __name__ == '__main__':
# unittest.main()
|
86f99b22e8c667d88ec683d830bc7d65d4758600 | SouzaCadu/guppe | /Secao_10_Expressoes_Lambdas_Funcoes_Integradas/10_66_Sorted.py | 2,091 | 4.4375 | 4 | """
Sorted
Não é igual ao atributo sort() que só funciona em listas.
Sorted funciona com qualquer iterável. Não altera o elemento original,
retorna um novo objeto
Exemplos
"""
numeros = [9, 8, 7, 3, 4, 1, 0, 11, 10, 12, 5, 6, 2]
print(numeros)
print(sorted(numeros))
print(tuple(sorted(numeros)))
print(set(sorted(numeros)))
print(numeros)
print(sorted(numeros, reverse=True))
usuarios = [
{"usuário": "lucas", "tweets": ["Eu adoro bolos", "Eu adoro pizzas"]},
{"usuário": "carla", "tweets": ["Eu adoro meu cachorro", "Eu amo filmes de terror"]},
{"usuário": "teixeira", "tweets": []},
{"usuário": "jj_watt", "tweets": ["Go Texans!!!"]},
{"usuário": "trump_01", "tweets": ["Make America Great Again"]},
{"usuário": "turco_loco", "tweets": ["por mais esporte nas ruas", "Por mais pistas de skate"]},
{"usuário": "osama", "tweets": ["Make my way at home learning to fly", "Holiday in Camboja!!!", "Going to California!!"]},
{"usuário": "puttin_78912", "tweets": ["Vodka rules"]},
{"usuário": "xin_jin_ping", "tweets": ["I gonna take my horse to the Old Town Road", "Doom 2"]},
{"usuário": "andrew_ng", "tweets": [], "tema": []},
{"usuário": "ze_dirceu", "tweets": [], "tema": []},
{"usuário": "flordelis_09123", "tweets": [], "tema": []},
{"usuário": "dalai_lama1233", "tweets": [], "tema": []}
]
print(sorted(usuarios, key=len, reverse=True))
print(sorted(usuarios, key=lambda usuario: usuario["usuário"]))
print(sorted(usuarios, key=lambda usuario: len(usuario["tweets"])))
musicas = [
{"título": "Creeping Death", "repetições": 12},
{"título": "American Jesus", "repetições": 15},
{"título": "Before I Forget", "repetições": 20},
{"título": "Aces High", "repetições": 45},
{"título": "N. I. B.", "repetições": 32},
{"título": "Black Sabbath", "repetições": 28},
{"título": "Jailbreak", "repetições": 37}
]
print(sorted(musicas, key=lambda musica: musica["repetições"]))
print(sorted(musicas, key=lambda musica: musica["repetições"], reverse=True))
|
4dd3a1016033727b6de1ea9bd2a012cb2ee6f078 | Nick-Mason/Combet-Tracker | /LargeCombat.py | 1,104 | 3.609375 | 4 | import random
#"Trial change"
rollAgain = "n"
while 1:
if rollAgain == "n":
#name = raw_input("Enter Name: ")
number = input("Number of Creatures in Attack Group: ")
numAtk = input("Enter Number of Attacks per Unit: ")
diceNum = input("Enter Number of Dice: ")
diceSize = input("Enter Dice Size: ")
toHit = input("Enter to Hit: ")
toDmg = input("Enter Bonus to Damage: ")
ac = input("Enter the AC of the target: ")
tot = 0
for x in range(number):
for i in range(numAtk):
roll = random.randint(1, 20) + toHit
if roll >= ac:
dmg = 0
if roll == (20 + toHit):
for i in range(diceNum * 2):
dmg += random.randint(1, diceSize)
else:
for j in range(diceNum):
dmg = dmg + random.randint(1, diceSize)
dmg = dmg + toDmg
tot = tot + dmg
print ("\nTotal Damage: %d" % tot)
rollAgain = raw_input("\nRoll Again with same Creature [y/n]") |
579c38a1e78624249eeff446ac9c0d644ffe3220 | sidharth14/python | /dict_test3.py | 808 | 3.953125 | 4 | # Exercise 3: Write a program to read through a mail log, build a histogram using a dictionary
# to count how many messages have come from each email address, and print the dictionary.
inp = input('Enter the file name: ')
try:
opn = open(inp)
except:
print(inp,'file not found')
exit()
dic2=dict()
for line in opn:
words = line.split()
for word in words:
if words[0] != 'From' or words[0]==' ':continue
elif words[1] not in dic2:
dic2[words[1]] = 1
else:
dic2[words[1]] = dic2[words[1]] + 1
print(dic2)
# Exercise 4: Add code to the above program to figure out who has the most messages in the file.
maxi = 0
maxik = ''
for ele in dic2:
if dic2[ele] > maxi:
maxi=dic2[ele]
maxik = ele
print(maxi,maxik)
|
5d1fd37e094f03d635d7d06cf50e78beb73ff594 | aromaljosephkm/Smart_Speed_Governor | /ultrasonic.py | 506 | 3.5625 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO_TRIGGER = 7
GPIO_ECHO = 12
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.0001)
GPIO.output(GPIO_TRIGGER, False)
while GPIO.input(GPIO_ECHO) == False:
start = time.time()
while GPIO.input(GPIO_ECHO) == True:
stop = time.time()
elapsed = stop - start
distance = elapsed * 0.000058
print("Distance : {} cm".format(distance)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.