repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
openstack/proliantutils
proliantutils/ilo/ribcl.py
RIBCLOperations._update_nic_data_from_nic_info_based_on_model
def _update_nic_data_from_nic_info_based_on_model(self, nic_dict, item, port, mac): """This method updates with port number and corresponding mac :param nic_dict: dictionary contains port number and corresponding mac :param item: dictionary containing nic details :param port: Port number :param mac: mac-address """ if 'G7' in self.model: nic_dict[port] = mac else: location = item['LOCATION']['VALUE'] if location == 'Embedded': nic_dict[port] = mac
python
def _update_nic_data_from_nic_info_based_on_model(self, nic_dict, item, port, mac): """This method updates with port number and corresponding mac :param nic_dict: dictionary contains port number and corresponding mac :param item: dictionary containing nic details :param port: Port number :param mac: mac-address """ if 'G7' in self.model: nic_dict[port] = mac else: location = item['LOCATION']['VALUE'] if location == 'Embedded': nic_dict[port] = mac
[ "def", "_update_nic_data_from_nic_info_based_on_model", "(", "self", ",", "nic_dict", ",", "item", ",", "port", ",", "mac", ")", ":", "if", "'G7'", "in", "self", ".", "model", ":", "nic_dict", "[", "port", "]", "=", "mac", "else", ":", "location", "=", "...
This method updates with port number and corresponding mac :param nic_dict: dictionary contains port number and corresponding mac :param item: dictionary containing nic details :param port: Port number :param mac: mac-address
[ "This", "method", "updates", "with", "port", "number", "and", "corresponding", "mac" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ribcl.py#L1170-L1184
train
41,700
openstack/proliantutils
proliantutils/rest/v1.py
RestConnectorBase._get_response_body_from_gzipped_content
def _get_response_body_from_gzipped_content(self, url, response): """Get the response body from gzipped content Try to decode as gzip (we should check the headers for Content-Encoding=gzip) if response.headers['content-encoding'] == "gzip": ... :param url: the url for which response was sent :type url: str :param response: response content object, probably gzipped :type response: object :returns: returns response body :raises IloError: if the content is **not** gzipped """ try: gzipper = gzip.GzipFile(fileobj=six.BytesIO(response.text)) LOG.debug(self._("Received compressed response for " "url %(url)s."), {'url': url}) uncompressed_string = (gzipper.read().decode('UTF-8')) response_body = json.loads(uncompressed_string) except Exception as e: LOG.debug( self._("Error occurred while decompressing body. " "Got invalid response '%(response)s' for " "url %(url)s: %(error)s"), {'url': url, 'response': response.text, 'error': e}) raise exception.IloError(e) return response_body
python
def _get_response_body_from_gzipped_content(self, url, response): """Get the response body from gzipped content Try to decode as gzip (we should check the headers for Content-Encoding=gzip) if response.headers['content-encoding'] == "gzip": ... :param url: the url for which response was sent :type url: str :param response: response content object, probably gzipped :type response: object :returns: returns response body :raises IloError: if the content is **not** gzipped """ try: gzipper = gzip.GzipFile(fileobj=six.BytesIO(response.text)) LOG.debug(self._("Received compressed response for " "url %(url)s."), {'url': url}) uncompressed_string = (gzipper.read().decode('UTF-8')) response_body = json.loads(uncompressed_string) except Exception as e: LOG.debug( self._("Error occurred while decompressing body. " "Got invalid response '%(response)s' for " "url %(url)s: %(error)s"), {'url': url, 'response': response.text, 'error': e}) raise exception.IloError(e) return response_body
[ "def", "_get_response_body_from_gzipped_content", "(", "self", ",", "url", ",", "response", ")", ":", "try", ":", "gzipper", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "six", ".", "BytesIO", "(", "response", ".", "text", ")", ")", "LOG", ".", "de...
Get the response body from gzipped content Try to decode as gzip (we should check the headers for Content-Encoding=gzip) if response.headers['content-encoding'] == "gzip": ... :param url: the url for which response was sent :type url: str :param response: response content object, probably gzipped :type response: object :returns: returns response body :raises IloError: if the content is **not** gzipped
[ "Get", "the", "response", "body", "from", "gzipped", "content" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/rest/v1.py#L62-L94
train
41,701
openstack/proliantutils
proliantutils/rest/v1.py
RestConnectorBase._rest_patch
def _rest_patch(self, suburi, request_headers, request_body): """REST PATCH operation. HTTP response codes could be 500, 404, 202 etc. """ return self._rest_op('PATCH', suburi, request_headers, request_body)
python
def _rest_patch(self, suburi, request_headers, request_body): """REST PATCH operation. HTTP response codes could be 500, 404, 202 etc. """ return self._rest_op('PATCH', suburi, request_headers, request_body)
[ "def", "_rest_patch", "(", "self", ",", "suburi", ",", "request_headers", ",", "request_body", ")", ":", "return", "self", ".", "_rest_op", "(", "'PATCH'", ",", "suburi", ",", "request_headers", ",", "request_body", ")" ]
REST PATCH operation. HTTP response codes could be 500, 404, 202 etc.
[ "REST", "PATCH", "operation", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/rest/v1.py#L233-L238
train
41,702
openstack/proliantutils
proliantutils/rest/v1.py
RestConnectorBase._rest_put
def _rest_put(self, suburi, request_headers, request_body): """REST PUT operation. HTTP response codes could be 500, 404, 202 etc. """ return self._rest_op('PUT', suburi, request_headers, request_body)
python
def _rest_put(self, suburi, request_headers, request_body): """REST PUT operation. HTTP response codes could be 500, 404, 202 etc. """ return self._rest_op('PUT', suburi, request_headers, request_body)
[ "def", "_rest_put", "(", "self", ",", "suburi", ",", "request_headers", ",", "request_body", ")", ":", "return", "self", ".", "_rest_op", "(", "'PUT'", ",", "suburi", ",", "request_headers", ",", "request_body", ")" ]
REST PUT operation. HTTP response codes could be 500, 404, 202 etc.
[ "REST", "PUT", "operation", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/rest/v1.py#L240-L245
train
41,703
openstack/proliantutils
proliantutils/rest/v1.py
RestConnectorBase._rest_post
def _rest_post(self, suburi, request_headers, request_body): """REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty. """ return self._rest_op('POST', suburi, request_headers, request_body)
python
def _rest_post(self, suburi, request_headers, request_body): """REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty. """ return self._rest_op('POST', suburi, request_headers, request_body)
[ "def", "_rest_post", "(", "self", ",", "suburi", ",", "request_headers", ",", "request_body", ")", ":", "return", "self", ".", "_rest_op", "(", "'POST'", ",", "suburi", ",", "request_headers", ",", "request_body", ")" ]
REST POST operation. The response body after the operation could be the new resource, or ExtendedError, or it could be empty.
[ "REST", "POST", "operation", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/rest/v1.py#L247-L253
train
41,704
NuGrid/NuGridPy
nugridpy/h5T.py
Files.red_dim
def red_dim(self, array): """ This function reduces the dimensions of an array until it is no longer of length 1. """ while isinstance(array, list) == True or \ isinstance(array, np.ndarray) == True: try: if len(array) == 1: array = array[0] else: break except: break return array
python
def red_dim(self, array): """ This function reduces the dimensions of an array until it is no longer of length 1. """ while isinstance(array, list) == True or \ isinstance(array, np.ndarray) == True: try: if len(array) == 1: array = array[0] else: break except: break return array
[ "def", "red_dim", "(", "self", ",", "array", ")", ":", "while", "isinstance", "(", "array", ",", "list", ")", "==", "True", "or", "isinstance", "(", "array", ",", "np", ".", "ndarray", ")", "==", "True", ":", "try", ":", "if", "len", "(", "array", ...
This function reduces the dimensions of an array until it is no longer of length 1.
[ "This", "function", "reduces", "the", "dimensions", "of", "an", "array", "until", "it", "is", "no", "longer", "of", "length", "1", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/h5T.py#L993-L1009
train
41,705
NuGrid/NuGridPy
nugridpy/data_plot.py
_padding_model_number
def _padding_model_number(number, max_num): ''' This method returns a zero-front padded string It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is meant to work for reasonable integers (maybe less than 10^6). Parameters ---------- number : integer number that the string should represent. max_num : integer max number of cycle list, implies how many 0s have be padded ''' cnum = str(number) clen = len(cnum) cmax = int(log10(max_num)) + 1 return (cmax - clen)*'0' + cnum
python
def _padding_model_number(number, max_num): ''' This method returns a zero-front padded string It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is meant to work for reasonable integers (maybe less than 10^6). Parameters ---------- number : integer number that the string should represent. max_num : integer max number of cycle list, implies how many 0s have be padded ''' cnum = str(number) clen = len(cnum) cmax = int(log10(max_num)) + 1 return (cmax - clen)*'0' + cnum
[ "def", "_padding_model_number", "(", "number", ",", "max_num", ")", ":", "cnum", "=", "str", "(", "number", ")", "clen", "=", "len", "(", "cnum", ")", "cmax", "=", "int", "(", "log10", "(", "max_num", ")", ")", "+", "1", "return", "(", "cmax", "-",...
This method returns a zero-front padded string It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is meant to work for reasonable integers (maybe less than 10^6). Parameters ---------- number : integer number that the string should represent. max_num : integer max number of cycle list, implies how many 0s have be padded
[ "This", "method", "returns", "a", "zero", "-", "front", "padded", "string" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L61-L82
train
41,706
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot._sparse
def _sparse(self, x, y, sparse): """ Method that removes every non sparse th element. For example: if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. Parameters ---------- x : list list of x values, of length j. y : list list of y values, of length j. sparse : integer Argument that skips every so many data points. """ tmpX=[] tmpY=[] for i in range(len(x)): if sparse == 1: return x,y if (i%sparse)==0: tmpX.append(x[i]) tmpY.append(y[i]) return tmpX, tmpY
python
def _sparse(self, x, y, sparse): """ Method that removes every non sparse th element. For example: if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. Parameters ---------- x : list list of x values, of length j. y : list list of y values, of length j. sparse : integer Argument that skips every so many data points. """ tmpX=[] tmpY=[] for i in range(len(x)): if sparse == 1: return x,y if (i%sparse)==0: tmpX.append(x[i]) tmpY.append(y[i]) return tmpX, tmpY
[ "def", "_sparse", "(", "self", ",", "x", ",", "y", ",", "sparse", ")", ":", "tmpX", "=", "[", "]", "tmpY", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "x", ")", ")", ":", "if", "sparse", "==", "1", ":", "return", "x", ",", ...
Method that removes every non sparse th element. For example: if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. Parameters ---------- x : list list of x values, of length j. y : list list of y values, of length j. sparse : integer Argument that skips every so many data points.
[ "Method", "that", "removes", "every", "non", "sparse", "th", "element", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L193-L220
train
41,707
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot.plotMulti
def plotMulti(self, atrix, atriy, cyclist, title, path='/', legend=None, labelx=None, labely=None, logx=False, logy=False, base=10, sparse=1, pdf=False, limits=None): ''' Method for plotting multiple plots and saving it to multiple pngs or PDFs. Parameters ---------- atrix : string The name of the attribute you want on the x axis. atriy : string The name of the attribute you want on the Y axis. cyclist : list List of cycles that you would like plotted. title : string The title of the graph and the name of the file. path : string, optional The file path. The default is '/' Legend : list or intager, optional A list of legends for each of your cycles, or one legend for all of the cycles. The default is None. labelx : string, optional The label on the X axis. The default is None. labely : string, optional The label on the Y axis. The default is None. logx : boolean, optional A boolean of whether the user wants the x axis logarithmically. The default is False. logy : boolean, optional A boolean of whether the user wants the Y axis logarithmically. The default is False. base : integer, optional The base of the logarithm. The default is 10. sparse : integer, optional Argument that skips every so many data points. For example if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. The default is 1. pdf : boolean, optional A boolean of if the image should be saved to a pdf file. xMin, xMax, yMin, YMax: plot coordinates. The default is False. limits : list, optional The length four list of the x and y limits. The order of the list is xmin, xmax, ymin, ymax. The default is None. ''' if str(legend.__class__)!="<type 'list'>":# Determines the legend is a list legendList=False else: legendList=True if legendList and len(cyclist) !=len(legend): #if it is a list, make sure there is an entry for each cycle print('Please input a proper legend, with correct length, aborting plot') return None for i in range(len(cyclist)): if legendList: self.plot(atrix,atriy,cyclist[i],'ndump',legend[i],labelx,labely,base=base,sparse=sparse, \ logx=logx,logy=logy,show=False,limits=limits) else: self.plot(atrix,atriy,cyclist[i],'ndump',legend,labelx,labely,base=base,sparse=sparse, \ logx=logx,logy=logy,show=False,limits=limits) pl.title(title) if not pdf: currentDir = os.getcwd() os.chdir(path) pl.savefig(title+str(cyclist[i])+'.png', dpi=400) os.chdir(currentDir) else: currentDir = os.getcwd() os.chdir(path) pl.savefig(title+str(cyclist[i])+'.pdf', dpi=400) os.chdir(currentDir) pl.clf() return None
python
def plotMulti(self, atrix, atriy, cyclist, title, path='/', legend=None, labelx=None, labely=None, logx=False, logy=False, base=10, sparse=1, pdf=False, limits=None): ''' Method for plotting multiple plots and saving it to multiple pngs or PDFs. Parameters ---------- atrix : string The name of the attribute you want on the x axis. atriy : string The name of the attribute you want on the Y axis. cyclist : list List of cycles that you would like plotted. title : string The title of the graph and the name of the file. path : string, optional The file path. The default is '/' Legend : list or intager, optional A list of legends for each of your cycles, or one legend for all of the cycles. The default is None. labelx : string, optional The label on the X axis. The default is None. labely : string, optional The label on the Y axis. The default is None. logx : boolean, optional A boolean of whether the user wants the x axis logarithmically. The default is False. logy : boolean, optional A boolean of whether the user wants the Y axis logarithmically. The default is False. base : integer, optional The base of the logarithm. The default is 10. sparse : integer, optional Argument that skips every so many data points. For example if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. The default is 1. pdf : boolean, optional A boolean of if the image should be saved to a pdf file. xMin, xMax, yMin, YMax: plot coordinates. The default is False. limits : list, optional The length four list of the x and y limits. The order of the list is xmin, xmax, ymin, ymax. The default is None. ''' if str(legend.__class__)!="<type 'list'>":# Determines the legend is a list legendList=False else: legendList=True if legendList and len(cyclist) !=len(legend): #if it is a list, make sure there is an entry for each cycle print('Please input a proper legend, with correct length, aborting plot') return None for i in range(len(cyclist)): if legendList: self.plot(atrix,atriy,cyclist[i],'ndump',legend[i],labelx,labely,base=base,sparse=sparse, \ logx=logx,logy=logy,show=False,limits=limits) else: self.plot(atrix,atriy,cyclist[i],'ndump',legend,labelx,labely,base=base,sparse=sparse, \ logx=logx,logy=logy,show=False,limits=limits) pl.title(title) if not pdf: currentDir = os.getcwd() os.chdir(path) pl.savefig(title+str(cyclist[i])+'.png', dpi=400) os.chdir(currentDir) else: currentDir = os.getcwd() os.chdir(path) pl.savefig(title+str(cyclist[i])+'.pdf', dpi=400) os.chdir(currentDir) pl.clf() return None
[ "def", "plotMulti", "(", "self", ",", "atrix", ",", "atriy", ",", "cyclist", ",", "title", ",", "path", "=", "'/'", ",", "legend", "=", "None", ",", "labelx", "=", "None", ",", "labely", "=", "None", ",", "logx", "=", "False", ",", "logy", "=", "...
Method for plotting multiple plots and saving it to multiple pngs or PDFs. Parameters ---------- atrix : string The name of the attribute you want on the x axis. atriy : string The name of the attribute you want on the Y axis. cyclist : list List of cycles that you would like plotted. title : string The title of the graph and the name of the file. path : string, optional The file path. The default is '/' Legend : list or intager, optional A list of legends for each of your cycles, or one legend for all of the cycles. The default is None. labelx : string, optional The label on the X axis. The default is None. labely : string, optional The label on the Y axis. The default is None. logx : boolean, optional A boolean of whether the user wants the x axis logarithmically. The default is False. logy : boolean, optional A boolean of whether the user wants the Y axis logarithmically. The default is False. base : integer, optional The base of the logarithm. The default is 10. sparse : integer, optional Argument that skips every so many data points. For example if this argument was 5, This method would plot the 0th, 5th, 10th ... elements. The default is 1. pdf : boolean, optional A boolean of if the image should be saved to a pdf file. xMin, xMax, yMin, YMax: plot coordinates. The default is False. limits : list, optional The length four list of the x and y limits. The order of the list is xmin, xmax, ymin, ymax. The default is None.
[ "Method", "for", "plotting", "multiple", "plots", "and", "saving", "it", "to", "multiple", "pngs", "or", "PDFs", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L222-L298
train
41,708
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot.iso_abundMulti
def iso_abundMulti(self, cyclist, stable=False, amass_range=None, mass_range=None, ylim=[0,0], ref=-1, decayed=False, include_title=False, title=None, pdf=False, color_plot=True, grid=False, point_set=1): ''' Method that plots figures and saves those figures to a .png file. Plots a figure for each cycle in the argument cycle. Can be called via iso_abund method by passing a list to cycle. Parameters ---------- cycllist : list The cycles of interest. This method will do a plot for each cycle and save them to a file. stable : boolean, optional A boolean of whether to filter out the unstables. The defaults is False. amass_range : list, optional A 1x2 array containing the lower and upper atomic mass range. If None plot entire available atomic mass range. The default is None. mass_range : list, optional A 1x2 array containing the lower and upper mass range. If this is an instance of abu_vector this will only plot isotopes that have an atominc mass within this range. This will throw an error if this range does not make sense ie [45,2]. If None, it will plot over the entire range. The defaults is None. ylim : list, optional A 1x2 array containing the lower and upper Y limits. If it is [0,0], then ylim will be determined automatically. The default is [0,0]. ref : integer or list, optional reference cycle. If it is not -1, this method will plot the abundences of cycle devided by the cycle of the same instance given in the ref variable. If ref is a list it will be interpreted to have two elements: ref=['dir/of/ref/run',cycle] which uses a refernece cycle from another run. If any abundence in the reference cycle is zero, it will replace it with 1e-99. The default is -1. decayed : boolean, optional If True plot decayed distributions, else plot life distribution. The default is False. include_title : boolean, optional Include a title with the plot. The default is False. title : string, optional A title to include with the plot. The default is None. pdf : boolean, optional Save image as a [pdf/png]. The default is False. color_plot : boolean, optional Color dots and lines [True/False]. The default is True. grid : boolean, optional print grid. The default is False. point_set : integer, optional Set to 0, 1 or 2 to select one of three point sets, useful for multiple abundances or ratios in one plot. The defalult is 1. ''' max_num = max(cyclist) for i in range(len(cyclist)): self.iso_abund(cyclist[i],stable,amass_range,mass_range,ylim,ref,\ decayed=decayed,show=False,color_plot=color_plot,grid=False,\ point_set=1,include_title=include_title) if title !=None: pl.title(title) else: name='IsoAbund' number_str=_padding_model_number(cyclist[i],max_num) if not pdf: pl.savefig(name+number_str+'.png', dpi=200) else: pl.savefig(name+number_str+'.pdf', dpi=200) pl.clf() return None
python
def iso_abundMulti(self, cyclist, stable=False, amass_range=None, mass_range=None, ylim=[0,0], ref=-1, decayed=False, include_title=False, title=None, pdf=False, color_plot=True, grid=False, point_set=1): ''' Method that plots figures and saves those figures to a .png file. Plots a figure for each cycle in the argument cycle. Can be called via iso_abund method by passing a list to cycle. Parameters ---------- cycllist : list The cycles of interest. This method will do a plot for each cycle and save them to a file. stable : boolean, optional A boolean of whether to filter out the unstables. The defaults is False. amass_range : list, optional A 1x2 array containing the lower and upper atomic mass range. If None plot entire available atomic mass range. The default is None. mass_range : list, optional A 1x2 array containing the lower and upper mass range. If this is an instance of abu_vector this will only plot isotopes that have an atominc mass within this range. This will throw an error if this range does not make sense ie [45,2]. If None, it will plot over the entire range. The defaults is None. ylim : list, optional A 1x2 array containing the lower and upper Y limits. If it is [0,0], then ylim will be determined automatically. The default is [0,0]. ref : integer or list, optional reference cycle. If it is not -1, this method will plot the abundences of cycle devided by the cycle of the same instance given in the ref variable. If ref is a list it will be interpreted to have two elements: ref=['dir/of/ref/run',cycle] which uses a refernece cycle from another run. If any abundence in the reference cycle is zero, it will replace it with 1e-99. The default is -1. decayed : boolean, optional If True plot decayed distributions, else plot life distribution. The default is False. include_title : boolean, optional Include a title with the plot. The default is False. title : string, optional A title to include with the plot. The default is None. pdf : boolean, optional Save image as a [pdf/png]. The default is False. color_plot : boolean, optional Color dots and lines [True/False]. The default is True. grid : boolean, optional print grid. The default is False. point_set : integer, optional Set to 0, 1 or 2 to select one of three point sets, useful for multiple abundances or ratios in one plot. The defalult is 1. ''' max_num = max(cyclist) for i in range(len(cyclist)): self.iso_abund(cyclist[i],stable,amass_range,mass_range,ylim,ref,\ decayed=decayed,show=False,color_plot=color_plot,grid=False,\ point_set=1,include_title=include_title) if title !=None: pl.title(title) else: name='IsoAbund' number_str=_padding_model_number(cyclist[i],max_num) if not pdf: pl.savefig(name+number_str+'.png', dpi=200) else: pl.savefig(name+number_str+'.pdf', dpi=200) pl.clf() return None
[ "def", "iso_abundMulti", "(", "self", ",", "cyclist", ",", "stable", "=", "False", ",", "amass_range", "=", "None", ",", "mass_range", "=", "None", ",", "ylim", "=", "[", "0", ",", "0", "]", ",", "ref", "=", "-", "1", ",", "decayed", "=", "False", ...
Method that plots figures and saves those figures to a .png file. Plots a figure for each cycle in the argument cycle. Can be called via iso_abund method by passing a list to cycle. Parameters ---------- cycllist : list The cycles of interest. This method will do a plot for each cycle and save them to a file. stable : boolean, optional A boolean of whether to filter out the unstables. The defaults is False. amass_range : list, optional A 1x2 array containing the lower and upper atomic mass range. If None plot entire available atomic mass range. The default is None. mass_range : list, optional A 1x2 array containing the lower and upper mass range. If this is an instance of abu_vector this will only plot isotopes that have an atominc mass within this range. This will throw an error if this range does not make sense ie [45,2]. If None, it will plot over the entire range. The defaults is None. ylim : list, optional A 1x2 array containing the lower and upper Y limits. If it is [0,0], then ylim will be determined automatically. The default is [0,0]. ref : integer or list, optional reference cycle. If it is not -1, this method will plot the abundences of cycle devided by the cycle of the same instance given in the ref variable. If ref is a list it will be interpreted to have two elements: ref=['dir/of/ref/run',cycle] which uses a refernece cycle from another run. If any abundence in the reference cycle is zero, it will replace it with 1e-99. The default is -1. decayed : boolean, optional If True plot decayed distributions, else plot life distribution. The default is False. include_title : boolean, optional Include a title with the plot. The default is False. title : string, optional A title to include with the plot. The default is None. pdf : boolean, optional Save image as a [pdf/png]. The default is False. color_plot : boolean, optional Color dots and lines [True/False]. The default is True. grid : boolean, optional print grid. The default is False. point_set : integer, optional Set to 0, 1 or 2 to select one of three point sets, useful for multiple abundances or ratios in one plot. The defalult is 1.
[ "Method", "that", "plots", "figures", "and", "saves", "those", "figures", "to", "a", ".", "png", "file", ".", "Plots", "a", "figure", "for", "each", "cycle", "in", "the", "argument", "cycle", ".", "Can", "be", "called", "via", "iso_abund", "method", "by"...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L3230-L3306
train
41,709
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot._do_title_string
def _do_title_string(self,title_items,cycle): ''' Create title string Private method that creates a title string for a cycle plot out of a list of title_items that are cycle attributes and can be obtained with self.get Parameters ---------- title_items : list A list of cycle attributes. cycle : scalar The cycle for which the title string should be created. Returns ------- title_string: string Title string that can be used to decorate plot. ''' title_string=[] form_str='%4.1F' for item in title_items: num=self.get(item,fname=cycle) if num > 999 or num < 0.1: num=log10(num) prefix='log ' else: prefix='' title_string.append(prefix+item+'='+form_str%num) tt='' for thing in title_string: tt = tt+thing+", " return tt.rstrip(', ')
python
def _do_title_string(self,title_items,cycle): ''' Create title string Private method that creates a title string for a cycle plot out of a list of title_items that are cycle attributes and can be obtained with self.get Parameters ---------- title_items : list A list of cycle attributes. cycle : scalar The cycle for which the title string should be created. Returns ------- title_string: string Title string that can be used to decorate plot. ''' title_string=[] form_str='%4.1F' for item in title_items: num=self.get(item,fname=cycle) if num > 999 or num < 0.1: num=log10(num) prefix='log ' else: prefix='' title_string.append(prefix+item+'='+form_str%num) tt='' for thing in title_string: tt = tt+thing+", " return tt.rstrip(', ')
[ "def", "_do_title_string", "(", "self", ",", "title_items", ",", "cycle", ")", ":", "title_string", "=", "[", "]", "form_str", "=", "'%4.1F'", "for", "item", "in", "title_items", ":", "num", "=", "self", ".", "get", "(", "item", ",", "fname", "=", "cyc...
Create title string Private method that creates a title string for a cycle plot out of a list of title_items that are cycle attributes and can be obtained with self.get Parameters ---------- title_items : list A list of cycle attributes. cycle : scalar The cycle for which the title string should be created. Returns ------- title_string: string Title string that can be used to decorate plot.
[ "Create", "title", "string" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L4234-L4270
train
41,710
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot.plotprofMulti
def plotprofMulti(self, ini, end, delta, what_specie, xlim1, xlim2, ylim1, ylim2, symbol=None): ''' create a movie with mass fractions vs mass coordinate between xlim1 and xlim2, ylim1 and ylim2. Only works with instances of se. Parameters ---------- ini : integer Initial model i.e. cycle. end : integer Final model i.e. cycle. delta : integer Sparsity factor of the frames. what_specie : list Array with species in the plot. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : list, optional Array indicating which symbol you want to use. Must be of the same len of what_specie array. The default is None. ''' plotType=self._classTest() if plotType=='se': for i in range(ini,end+1,delta): step = int(i) #print step if symbol==None: symbol_dummy = '-' for j in range(len(what_specie)): self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy) else: for j in range(len(what_specie)): symbol_dummy = symbol[j] self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy) # filename = str('%03d' % step)+'_test.png' pl.savefig(filename, dpi=400) print('wrote file ', filename) # pl.clf() else: print('This method is not supported for '+str(self.__class__)) return
python
def plotprofMulti(self, ini, end, delta, what_specie, xlim1, xlim2, ylim1, ylim2, symbol=None): ''' create a movie with mass fractions vs mass coordinate between xlim1 and xlim2, ylim1 and ylim2. Only works with instances of se. Parameters ---------- ini : integer Initial model i.e. cycle. end : integer Final model i.e. cycle. delta : integer Sparsity factor of the frames. what_specie : list Array with species in the plot. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : list, optional Array indicating which symbol you want to use. Must be of the same len of what_specie array. The default is None. ''' plotType=self._classTest() if plotType=='se': for i in range(ini,end+1,delta): step = int(i) #print step if symbol==None: symbol_dummy = '-' for j in range(len(what_specie)): self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy) else: for j in range(len(what_specie)): symbol_dummy = symbol[j] self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy) # filename = str('%03d' % step)+'_test.png' pl.savefig(filename, dpi=400) print('wrote file ', filename) # pl.clf() else: print('This method is not supported for '+str(self.__class__)) return
[ "def", "plotprofMulti", "(", "self", ",", "ini", ",", "end", ",", "delta", ",", "what_specie", ",", "xlim1", ",", "xlim2", ",", "ylim1", ",", "ylim2", ",", "symbol", "=", "None", ")", ":", "plotType", "=", "self", ".", "_classTest", "(", ")", "if", ...
create a movie with mass fractions vs mass coordinate between xlim1 and xlim2, ylim1 and ylim2. Only works with instances of se. Parameters ---------- ini : integer Initial model i.e. cycle. end : integer Final model i.e. cycle. delta : integer Sparsity factor of the frames. what_specie : list Array with species in the plot. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : list, optional Array indicating which symbol you want to use. Must be of the same len of what_specie array. The default is None.
[ "create", "a", "movie", "with", "mass", "fractions", "vs", "mass", "coordinate", "between", "xlim1", "and", "xlim2", "ylim1", "and", "ylim2", ".", "Only", "works", "with", "instances", "of", "se", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L4272-L4322
train
41,711
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot.plot_prof_1
def plot_prof_1(self, species, keystring, xlim1, xlim2, ylim1, ylim2, symbol=None, show=False): ''' Plot one species for cycle between xlim1 and xlim2 Only works with instances of se and mesa _profile. Parameters ---------- species : list Which species to plot. keystring : string or integer Label that appears in the plot or in the case of se, a cycle. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : string, optional Which symbol you want to use. If None symbol is set to '-'. The default is None. show : boolean, optional Show the ploted graph. The default is False. ''' plotType=self._classTest() if plotType=='se': #tot_mass=self.se.get(keystring,'total_mass') tot_mass=self.se.get('mini') age=self.se.get(keystring,'age') mass=self.se.get(keystring,'mass') Xspecies=self.se.get(keystring,'iso_massf',species) mod=keystring elif plotType=='mesa_profile': tot_mass=self.header_attr['star_mass'] age=self.header_attr['star_age'] mass=self.get('mass') mod=self.header_attr['model_number'] Xspecies=self.get(species) else: print('This method is not supported for '+str(self.__class__)) return if symbol == None: symbol = '-' x,y=self._logarithm(Xspecies,mass,True,False,10) #print x pl.plot(y,x,symbol,label=str(species)) pl.xlim(xlim1,xlim2) pl.ylim(ylim1,ylim2) pl.legend() pl.xlabel('$Mass$ $coordinate$', fontsize=20) pl.ylabel('$X_{i}$', fontsize=20) #pl.title('Mass='+str(tot_mass)+', Time='+str(age)+' years, cycle='+str(mod)) pl.title('Mass='+str(tot_mass)+', cycle='+str(mod)) if show: pl.show()
python
def plot_prof_1(self, species, keystring, xlim1, xlim2, ylim1, ylim2, symbol=None, show=False): ''' Plot one species for cycle between xlim1 and xlim2 Only works with instances of se and mesa _profile. Parameters ---------- species : list Which species to plot. keystring : string or integer Label that appears in the plot or in the case of se, a cycle. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : string, optional Which symbol you want to use. If None symbol is set to '-'. The default is None. show : boolean, optional Show the ploted graph. The default is False. ''' plotType=self._classTest() if plotType=='se': #tot_mass=self.se.get(keystring,'total_mass') tot_mass=self.se.get('mini') age=self.se.get(keystring,'age') mass=self.se.get(keystring,'mass') Xspecies=self.se.get(keystring,'iso_massf',species) mod=keystring elif plotType=='mesa_profile': tot_mass=self.header_attr['star_mass'] age=self.header_attr['star_age'] mass=self.get('mass') mod=self.header_attr['model_number'] Xspecies=self.get(species) else: print('This method is not supported for '+str(self.__class__)) return if symbol == None: symbol = '-' x,y=self._logarithm(Xspecies,mass,True,False,10) #print x pl.plot(y,x,symbol,label=str(species)) pl.xlim(xlim1,xlim2) pl.ylim(ylim1,ylim2) pl.legend() pl.xlabel('$Mass$ $coordinate$', fontsize=20) pl.ylabel('$X_{i}$', fontsize=20) #pl.title('Mass='+str(tot_mass)+', Time='+str(age)+' years, cycle='+str(mod)) pl.title('Mass='+str(tot_mass)+', cycle='+str(mod)) if show: pl.show()
[ "def", "plot_prof_1", "(", "self", ",", "species", ",", "keystring", ",", "xlim1", ",", "xlim2", ",", "ylim1", ",", "ylim2", ",", "symbol", "=", "None", ",", "show", "=", "False", ")", ":", "plotType", "=", "self", ".", "_classTest", "(", ")", "if", ...
Plot one species for cycle between xlim1 and xlim2 Only works with instances of se and mesa _profile. Parameters ---------- species : list Which species to plot. keystring : string or integer Label that appears in the plot or in the case of se, a cycle. xlim1, xlim2 : integer or float Mass coordinate range. ylim1, ylim2 : integer or float Mass fraction coordinate range. symbol : string, optional Which symbol you want to use. If None symbol is set to '-'. The default is None. show : boolean, optional Show the ploted graph. The default is False.
[ "Plot", "one", "species", "for", "cycle", "between", "xlim1", "and", "xlim2", "Only", "works", "with", "instances", "of", "se", "and", "mesa", "_profile", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L4534-L4592
train
41,712
NuGrid/NuGridPy
nugridpy/data_plot.py
DataPlot.density_profile
def density_profile(self,ixaxis='mass',ifig=None,colour=None,label=None,fname=None): ''' Plot density as a function of either mass coordiate or radius. Parameters ---------- ixaxis : string 'mass' or 'radius' The default value is 'mass' ifig : integer or string The figure label The default value is None colour : string What colour the line should be The default value is None label : string Label for the line The default value is None fname : integer What cycle to plot from (if SE output) The default value is None ''' pT=self._classTest() # Class-specific things: if pT is 'mesa_profile': x = self.get(ixaxis) if ixaxis is 'radius': x = x*ast.rsun_cm y = self.get('logRho') elif pT is 'se': if fname is None: raise IOError("Please provide the cycle number fname") x = self.se.get(fname,ixaxis) y = np.log10(self.se.get(fname,'rho')) else: raise IOError("Sorry. the density_profile method is not available \ for this class") # Plot-specific things: if ixaxis is 'radius': x = np.log10(x) xlab='$\log_{10}(r\,/\,{\\rm cm})$' else: xlab='${\\rm Mass}\,/\,M_\odot$' if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: pl.plot(x,y,color=colour,label=label) else: pl.plot(x,y,label=label) pl.legend(loc='best').draw_frame(False) else: if colour is not None: pl.plot(x,y,color=colour) else: pl.plot(x,y) pl.xlabel(xlab) pl.ylabel('$\log_{10}(\\rho\,/\,{\\rm g\,cm}^{-3})$')
python
def density_profile(self,ixaxis='mass',ifig=None,colour=None,label=None,fname=None): ''' Plot density as a function of either mass coordiate or radius. Parameters ---------- ixaxis : string 'mass' or 'radius' The default value is 'mass' ifig : integer or string The figure label The default value is None colour : string What colour the line should be The default value is None label : string Label for the line The default value is None fname : integer What cycle to plot from (if SE output) The default value is None ''' pT=self._classTest() # Class-specific things: if pT is 'mesa_profile': x = self.get(ixaxis) if ixaxis is 'radius': x = x*ast.rsun_cm y = self.get('logRho') elif pT is 'se': if fname is None: raise IOError("Please provide the cycle number fname") x = self.se.get(fname,ixaxis) y = np.log10(self.se.get(fname,'rho')) else: raise IOError("Sorry. the density_profile method is not available \ for this class") # Plot-specific things: if ixaxis is 'radius': x = np.log10(x) xlab='$\log_{10}(r\,/\,{\\rm cm})$' else: xlab='${\\rm Mass}\,/\,M_\odot$' if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: pl.plot(x,y,color=colour,label=label) else: pl.plot(x,y,label=label) pl.legend(loc='best').draw_frame(False) else: if colour is not None: pl.plot(x,y,color=colour) else: pl.plot(x,y) pl.xlabel(xlab) pl.ylabel('$\log_{10}(\\rho\,/\,{\\rm g\,cm}^{-3})$')
[ "def", "density_profile", "(", "self", ",", "ixaxis", "=", "'mass'", ",", "ifig", "=", "None", ",", "colour", "=", "None", ",", "label", "=", "None", ",", "fname", "=", "None", ")", ":", "pT", "=", "self", ".", "_classTest", "(", ")", "# Class-specif...
Plot density as a function of either mass coordiate or radius. Parameters ---------- ixaxis : string 'mass' or 'radius' The default value is 'mass' ifig : integer or string The figure label The default value is None colour : string What colour the line should be The default value is None label : string Label for the line The default value is None fname : integer What cycle to plot from (if SE output) The default value is None
[ "Plot", "density", "as", "a", "function", "of", "either", "mass", "coordiate", "or", "radius", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L4594-L4656
train
41,713
openstack/proliantutils
proliantutils/redfish/main.py
HPESushy.get_system
def get_system(self, identity): """Given the identity return a HPESystem object :param identity: The identity of the System resource :returns: The System object """ return system.HPESystem(self._conn, identity, redfish_version=self.redfish_version)
python
def get_system(self, identity): """Given the identity return a HPESystem object :param identity: The identity of the System resource :returns: The System object """ return system.HPESystem(self._conn, identity, redfish_version=self.redfish_version)
[ "def", "get_system", "(", "self", ",", "identity", ")", ":", "return", "system", ".", "HPESystem", "(", "self", ".", "_conn", ",", "identity", ",", "redfish_version", "=", "self", ".", "redfish_version", ")" ]
Given the identity return a HPESystem object :param identity: The identity of the System resource :returns: The System object
[ "Given", "the", "identity", "return", "a", "HPESystem", "object" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/main.py#L66-L73
train
41,714
openstack/proliantutils
proliantutils/redfish/main.py
HPESushy.get_manager
def get_manager(self, identity): """Given the identity return a HPEManager object :param identity: The identity of the Manager resource :returns: The Manager object """ return manager.HPEManager(self._conn, identity, redfish_version=self.redfish_version)
python
def get_manager(self, identity): """Given the identity return a HPEManager object :param identity: The identity of the Manager resource :returns: The Manager object """ return manager.HPEManager(self._conn, identity, redfish_version=self.redfish_version)
[ "def", "get_manager", "(", "self", ",", "identity", ")", ":", "return", "manager", ".", "HPEManager", "(", "self", ".", "_conn", ",", "identity", ",", "redfish_version", "=", "self", ".", "redfish_version", ")" ]
Given the identity return a HPEManager object :param identity: The identity of the Manager resource :returns: The Manager object
[ "Given", "the", "identity", "return", "a", "HPEManager", "object" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/main.py#L78-L85
train
41,715
openstack/proliantutils
proliantutils/redfish/main.py
HPESushy.get_update_service
def get_update_service(self): """Return a HPEUpdateService object :returns: The UpdateService object """ update_service_url = utils.get_subresource_path_by(self, 'UpdateService') return (update_service. HPEUpdateService(self._conn, update_service_url, redfish_version=self.redfish_version))
python
def get_update_service(self): """Return a HPEUpdateService object :returns: The UpdateService object """ update_service_url = utils.get_subresource_path_by(self, 'UpdateService') return (update_service. HPEUpdateService(self._conn, update_service_url, redfish_version=self.redfish_version))
[ "def", "get_update_service", "(", "self", ")", ":", "update_service_url", "=", "utils", ".", "get_subresource_path_by", "(", "self", ",", "'UpdateService'", ")", "return", "(", "update_service", ".", "HPEUpdateService", "(", "self", ".", "_conn", ",", "update_serv...
Return a HPEUpdateService object :returns: The UpdateService object
[ "Return", "a", "HPEUpdateService", "object" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/main.py#L87-L96
train
41,716
openstack/proliantutils
proliantutils/redfish/main.py
HPESushy.get_account_service
def get_account_service(self): """Return a HPEAccountService object""" account_service_url = utils.get_subresource_path_by(self, 'AccountService') return (account_service. HPEAccountService(self._conn, account_service_url, redfish_version=self.redfish_version))
python
def get_account_service(self): """Return a HPEAccountService object""" account_service_url = utils.get_subresource_path_by(self, 'AccountService') return (account_service. HPEAccountService(self._conn, account_service_url, redfish_version=self.redfish_version))
[ "def", "get_account_service", "(", "self", ")", ":", "account_service_url", "=", "utils", ".", "get_subresource_path_by", "(", "self", ",", "'AccountService'", ")", "return", "(", "account_service", ".", "HPEAccountService", "(", "self", ".", "_conn", ",", "accoun...
Return a HPEAccountService object
[ "Return", "a", "HPEAccountService", "object" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/main.py#L98-L105
train
41,717
openstack/proliantutils
proliantutils/sum/sum_controller.py
_execute_sum
def _execute_sum(sum_file_path, mount_point, components=None): """Executes the SUM based firmware update command. This method executes the SUM based firmware update command to update the components specified, if not, it performs update on all the firmware components on th server. :param sum_file_path: A string with the path to the SUM binary to be executed :param components: A list of components to be updated. If it is None, all the firmware components are updated. :param mount_point: Location in which SPP iso is mounted. :returns: A string with the statistics of the updated/failed components. :raises: SUMOperationError, when the SUM based firmware update operation on the node fails. """ cmd = ' --c ' + ' --c '.join(components) if components else '' try: if SUM_LOCATION in sum_file_path: location = os.path.join(mount_point, 'packages') # NOTE: 'launch_sum.sh' binary is part of SPP ISO and it is # available in the SPP mount point (eg:'/mount/launch_sum.sh'). # 'launch_sum.sh' binary calls the 'smartupdate' binary by passing # the arguments. processutils.execute('./launch_sum.sh', '--s', '--romonly', '--use_location', location, cmd, cwd=mount_point) else: processutils.execute(sum_file_path, '--s', '--romonly', cmd) except processutils.ProcessExecutionError as e: result = _parse_sum_ouput(e.exit_code) if result: return result else: raise exception.SUMOperationError(reason=str(e))
python
def _execute_sum(sum_file_path, mount_point, components=None): """Executes the SUM based firmware update command. This method executes the SUM based firmware update command to update the components specified, if not, it performs update on all the firmware components on th server. :param sum_file_path: A string with the path to the SUM binary to be executed :param components: A list of components to be updated. If it is None, all the firmware components are updated. :param mount_point: Location in which SPP iso is mounted. :returns: A string with the statistics of the updated/failed components. :raises: SUMOperationError, when the SUM based firmware update operation on the node fails. """ cmd = ' --c ' + ' --c '.join(components) if components else '' try: if SUM_LOCATION in sum_file_path: location = os.path.join(mount_point, 'packages') # NOTE: 'launch_sum.sh' binary is part of SPP ISO and it is # available in the SPP mount point (eg:'/mount/launch_sum.sh'). # 'launch_sum.sh' binary calls the 'smartupdate' binary by passing # the arguments. processutils.execute('./launch_sum.sh', '--s', '--romonly', '--use_location', location, cmd, cwd=mount_point) else: processutils.execute(sum_file_path, '--s', '--romonly', cmd) except processutils.ProcessExecutionError as e: result = _parse_sum_ouput(e.exit_code) if result: return result else: raise exception.SUMOperationError(reason=str(e))
[ "def", "_execute_sum", "(", "sum_file_path", ",", "mount_point", ",", "components", "=", "None", ")", ":", "cmd", "=", "' --c '", "+", "' --c '", ".", "join", "(", "components", ")", "if", "components", "else", "''", "try", ":", "if", "SUM_LOCATION", "in",...
Executes the SUM based firmware update command. This method executes the SUM based firmware update command to update the components specified, if not, it performs update on all the firmware components on th server. :param sum_file_path: A string with the path to the SUM binary to be executed :param components: A list of components to be updated. If it is None, all the firmware components are updated. :param mount_point: Location in which SPP iso is mounted. :returns: A string with the statistics of the updated/failed components. :raises: SUMOperationError, when the SUM based firmware update operation on the node fails.
[ "Executes", "the", "SUM", "based", "firmware", "update", "command", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/sum/sum_controller.py#L55-L91
train
41,718
openstack/proliantutils
proliantutils/sum/sum_controller.py
_get_log_file_data_as_encoded_content
def _get_log_file_data_as_encoded_content(): """Gzip and base64 encode files and BytesIO buffers. This method gets the log files created by SUM based firmware update and tar zip the files. :returns: A gzipped and base64 encoded string as text. """ with io.BytesIO() as fp: with tarfile.open(fileobj=fp, mode='w:gz') as tar: for f in OUTPUT_FILES: if os.path.isfile(f): tar.add(f) fp.seek(0) return base64.encode_as_bytes(fp.getvalue())
python
def _get_log_file_data_as_encoded_content(): """Gzip and base64 encode files and BytesIO buffers. This method gets the log files created by SUM based firmware update and tar zip the files. :returns: A gzipped and base64 encoded string as text. """ with io.BytesIO() as fp: with tarfile.open(fileobj=fp, mode='w:gz') as tar: for f in OUTPUT_FILES: if os.path.isfile(f): tar.add(f) fp.seek(0) return base64.encode_as_bytes(fp.getvalue())
[ "def", "_get_log_file_data_as_encoded_content", "(", ")", ":", "with", "io", ".", "BytesIO", "(", ")", "as", "fp", ":", "with", "tarfile", ".", "open", "(", "fileobj", "=", "fp", ",", "mode", "=", "'w:gz'", ")", "as", "tar", ":", "for", "f", "in", "O...
Gzip and base64 encode files and BytesIO buffers. This method gets the log files created by SUM based firmware update and tar zip the files. :returns: A gzipped and base64 encoded string as text.
[ "Gzip", "and", "base64", "encode", "files", "and", "BytesIO", "buffers", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/sum/sum_controller.py#L94-L108
train
41,719
openstack/proliantutils
proliantutils/sum/sum_controller.py
_parse_sum_ouput
def _parse_sum_ouput(exit_code): """Parse the SUM output log file. This method parses through the SUM log file in the default location to return the SUM update status. Sample return string: "Summary: The installation of the component failed. Status of updated components: Total: 5 Success: 4 Failed: 1" :param exit_code: A integer returned by the SUM after command execution. :returns: A string with the statistics of the updated/failed components and 'None' when the exit_code is not 0, 1, 3 or 253. """ if exit_code == 3: return "Summary: %s" % EXIT_CODE_TO_STRING.get(exit_code) if exit_code in (0, 1, 253): if os.path.exists(OUTPUT_FILES[0]): with open(OUTPUT_FILES[0], 'r') as f: output_data = f.read() ret_data = output_data[(output_data.find('Deployed Components:') + len('Deployed Components:')): output_data.find('Exit status:')] failed = 0 success = 0 for line in re.split('\n\n', ret_data): if line: if 'Success' not in line: failed += 1 else: success += 1 return { 'Summary': ( "%(return_string)s Status of updated components: Total: " "%(total)s Success: %(success)s Failed: %(failed)s." % {'return_string': EXIT_CODE_TO_STRING.get(exit_code), 'total': (success + failed), 'success': success, 'failed': failed}), 'Log Data': _get_log_file_data_as_encoded_content() } return "UPDATE STATUS: UNKNOWN"
python
def _parse_sum_ouput(exit_code): """Parse the SUM output log file. This method parses through the SUM log file in the default location to return the SUM update status. Sample return string: "Summary: The installation of the component failed. Status of updated components: Total: 5 Success: 4 Failed: 1" :param exit_code: A integer returned by the SUM after command execution. :returns: A string with the statistics of the updated/failed components and 'None' when the exit_code is not 0, 1, 3 or 253. """ if exit_code == 3: return "Summary: %s" % EXIT_CODE_TO_STRING.get(exit_code) if exit_code in (0, 1, 253): if os.path.exists(OUTPUT_FILES[0]): with open(OUTPUT_FILES[0], 'r') as f: output_data = f.read() ret_data = output_data[(output_data.find('Deployed Components:') + len('Deployed Components:')): output_data.find('Exit status:')] failed = 0 success = 0 for line in re.split('\n\n', ret_data): if line: if 'Success' not in line: failed += 1 else: success += 1 return { 'Summary': ( "%(return_string)s Status of updated components: Total: " "%(total)s Success: %(success)s Failed: %(failed)s." % {'return_string': EXIT_CODE_TO_STRING.get(exit_code), 'total': (success + failed), 'success': success, 'failed': failed}), 'Log Data': _get_log_file_data_as_encoded_content() } return "UPDATE STATUS: UNKNOWN"
[ "def", "_parse_sum_ouput", "(", "exit_code", ")", ":", "if", "exit_code", "==", "3", ":", "return", "\"Summary: %s\"", "%", "EXIT_CODE_TO_STRING", ".", "get", "(", "exit_code", ")", "if", "exit_code", "in", "(", "0", ",", "1", ",", "253", ")", ":", "if",...
Parse the SUM output log file. This method parses through the SUM log file in the default location to return the SUM update status. Sample return string: "Summary: The installation of the component failed. Status of updated components: Total: 5 Success: 4 Failed: 1" :param exit_code: A integer returned by the SUM after command execution. :returns: A string with the statistics of the updated/failed components and 'None' when the exit_code is not 0, 1, 3 or 253.
[ "Parse", "the", "SUM", "output", "log", "file", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/sum/sum_controller.py#L111-L156
train
41,720
openstack/proliantutils
proliantutils/sum/sum_controller.py
update_firmware
def update_firmware(node): """Performs SUM based firmware update on the node. This method performs SUM firmware update by mounting the SPP ISO on the node. It performs firmware update on all or some of the firmware components. :param node: A node object of type dict. :returns: Operation Status string. :raises: SUMOperationError, when the vmedia device is not found or when the mount operation fails or when the image validation fails. :raises: IloConnectionError, when the iLO connection fails. :raises: IloError, when vmedia eject or insert operation fails. """ sum_update_iso = node['clean_step']['args'].get('url') # Validates the http image reference for SUM update ISO. try: utils.validate_href(sum_update_iso) except exception.ImageRefValidationFailed as e: raise exception.SUMOperationError(reason=e) # Ejects the CDROM device in the iLO and inserts the SUM update ISO # to the CDROM device. info = node.get('driver_info') ilo_object = client.IloClient(info.get('ilo_address'), info.get('ilo_username'), info.get('ilo_password')) ilo_object.eject_virtual_media('CDROM') ilo_object.insert_virtual_media(sum_update_iso, 'CDROM') # Waits for the OS to detect the disk and update the label file. SPP ISO # is identified by matching its label. time.sleep(WAIT_TIME_DISK_LABEL_TO_BE_VISIBLE) vmedia_device_dir = "/dev/disk/by-label/" for file in os.listdir(vmedia_device_dir): if fnmatch.fnmatch(file, 'SPP*'): vmedia_device_file = os.path.join(vmedia_device_dir, file) if not os.path.exists(vmedia_device_file): msg = "Unable to find the virtual media device for SUM" raise exception.SUMOperationError(reason=msg) # Validates the SPP ISO image for any file corruption using the checksum # of the ISO file. expected_checksum = node['clean_step']['args'].get('checksum') try: utils.verify_image_checksum(vmedia_device_file, expected_checksum) except exception.ImageRefValidationFailed as e: raise exception.SUMOperationError(reason=e) # Mounts SPP ISO on a temporary directory. vmedia_mount_point = tempfile.mkdtemp() try: try: processutils.execute("mount", vmedia_device_file, vmedia_mount_point) except processutils.ProcessExecutionError as e: msg = ("Unable to mount virtual media device %(device)s: " "%(error)s" % {'device': vmedia_device_file, 'error': e}) raise exception.SUMOperationError(reason=msg) # Executes the SUM based firmware update by passing the 'smartupdate' # executable path if exists else 'hpsum' executable path and the # components specified (if any). sum_file_path = os.path.join(vmedia_mount_point, SUM_LOCATION) if not os.path.exists(sum_file_path): sum_file_path = os.path.join(vmedia_mount_point, HPSUM_LOCATION) components = node['clean_step']['args'].get('components') result = _execute_sum(sum_file_path, vmedia_mount_point, components=components) processutils.trycmd("umount", vmedia_mount_point) finally: shutil.rmtree(vmedia_mount_point, ignore_errors=True) return result
python
def update_firmware(node): """Performs SUM based firmware update on the node. This method performs SUM firmware update by mounting the SPP ISO on the node. It performs firmware update on all or some of the firmware components. :param node: A node object of type dict. :returns: Operation Status string. :raises: SUMOperationError, when the vmedia device is not found or when the mount operation fails or when the image validation fails. :raises: IloConnectionError, when the iLO connection fails. :raises: IloError, when vmedia eject or insert operation fails. """ sum_update_iso = node['clean_step']['args'].get('url') # Validates the http image reference for SUM update ISO. try: utils.validate_href(sum_update_iso) except exception.ImageRefValidationFailed as e: raise exception.SUMOperationError(reason=e) # Ejects the CDROM device in the iLO and inserts the SUM update ISO # to the CDROM device. info = node.get('driver_info') ilo_object = client.IloClient(info.get('ilo_address'), info.get('ilo_username'), info.get('ilo_password')) ilo_object.eject_virtual_media('CDROM') ilo_object.insert_virtual_media(sum_update_iso, 'CDROM') # Waits for the OS to detect the disk and update the label file. SPP ISO # is identified by matching its label. time.sleep(WAIT_TIME_DISK_LABEL_TO_BE_VISIBLE) vmedia_device_dir = "/dev/disk/by-label/" for file in os.listdir(vmedia_device_dir): if fnmatch.fnmatch(file, 'SPP*'): vmedia_device_file = os.path.join(vmedia_device_dir, file) if not os.path.exists(vmedia_device_file): msg = "Unable to find the virtual media device for SUM" raise exception.SUMOperationError(reason=msg) # Validates the SPP ISO image for any file corruption using the checksum # of the ISO file. expected_checksum = node['clean_step']['args'].get('checksum') try: utils.verify_image_checksum(vmedia_device_file, expected_checksum) except exception.ImageRefValidationFailed as e: raise exception.SUMOperationError(reason=e) # Mounts SPP ISO on a temporary directory. vmedia_mount_point = tempfile.mkdtemp() try: try: processutils.execute("mount", vmedia_device_file, vmedia_mount_point) except processutils.ProcessExecutionError as e: msg = ("Unable to mount virtual media device %(device)s: " "%(error)s" % {'device': vmedia_device_file, 'error': e}) raise exception.SUMOperationError(reason=msg) # Executes the SUM based firmware update by passing the 'smartupdate' # executable path if exists else 'hpsum' executable path and the # components specified (if any). sum_file_path = os.path.join(vmedia_mount_point, SUM_LOCATION) if not os.path.exists(sum_file_path): sum_file_path = os.path.join(vmedia_mount_point, HPSUM_LOCATION) components = node['clean_step']['args'].get('components') result = _execute_sum(sum_file_path, vmedia_mount_point, components=components) processutils.trycmd("umount", vmedia_mount_point) finally: shutil.rmtree(vmedia_mount_point, ignore_errors=True) return result
[ "def", "update_firmware", "(", "node", ")", ":", "sum_update_iso", "=", "node", "[", "'clean_step'", "]", "[", "'args'", "]", ".", "get", "(", "'url'", ")", "# Validates the http image reference for SUM update ISO.", "try", ":", "utils", ".", "validate_href", "(",...
Performs SUM based firmware update on the node. This method performs SUM firmware update by mounting the SPP ISO on the node. It performs firmware update on all or some of the firmware components. :param node: A node object of type dict. :returns: Operation Status string. :raises: SUMOperationError, when the vmedia device is not found or when the mount operation fails or when the image validation fails. :raises: IloConnectionError, when the iLO connection fails. :raises: IloError, when vmedia eject or insert operation fails.
[ "Performs", "SUM", "based", "firmware", "update", "on", "the", "node", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/sum/sum_controller.py#L159-L237
train
41,721
gvalkov/python-ansimarkup
ansimarkup/markup.py
AnsiMarkup.parse
def parse(self, text): '''Return a string with markup tags converted to ansi-escape sequences.''' tags, results = [], [] text = self.re_tag.sub(lambda m: self.sub_tag(m, tags, results), text) if self.strict and tags: markup = "%s%s%s" % (self.tag_sep[0], tags.pop(0), self.tag_sep[1]) raise MismatchedTag('opening tag "%s" has no corresponding closing tag' % markup) if self.always_reset: if not text.endswith(Style.RESET_ALL): text += Style.RESET_ALL return text
python
def parse(self, text): '''Return a string with markup tags converted to ansi-escape sequences.''' tags, results = [], [] text = self.re_tag.sub(lambda m: self.sub_tag(m, tags, results), text) if self.strict and tags: markup = "%s%s%s" % (self.tag_sep[0], tags.pop(0), self.tag_sep[1]) raise MismatchedTag('opening tag "%s" has no corresponding closing tag' % markup) if self.always_reset: if not text.endswith(Style.RESET_ALL): text += Style.RESET_ALL return text
[ "def", "parse", "(", "self", ",", "text", ")", ":", "tags", ",", "results", "=", "[", "]", ",", "[", "]", "text", "=", "self", ".", "re_tag", ".", "sub", "(", "lambda", "m", ":", "self", ".", "sub_tag", "(", "m", ",", "tags", ",", "results", ...
Return a string with markup tags converted to ansi-escape sequences.
[ "Return", "a", "string", "with", "markup", "tags", "converted", "to", "ansi", "-", "escape", "sequences", "." ]
92611bec49e8fdfaea0c77d63b758d8643398fdf
https://github.com/gvalkov/python-ansimarkup/blob/92611bec49e8fdfaea0c77d63b758d8643398fdf/ansimarkup/markup.py#L50-L64
train
41,722
gvalkov/python-ansimarkup
ansimarkup/markup.py
AnsiMarkup.strip
def strip(self, text): '''Return string with markup tags removed.''' tags, results = [], [] return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text)
python
def strip(self, text): '''Return string with markup tags removed.''' tags, results = [], [] return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text)
[ "def", "strip", "(", "self", ",", "text", ")", ":", "tags", ",", "results", "=", "[", "]", ",", "[", "]", "return", "self", ".", "re_tag", ".", "sub", "(", "lambda", "m", ":", "self", ".", "clear_tag", "(", "m", ",", "tags", ",", "results", ")"...
Return string with markup tags removed.
[ "Return", "string", "with", "markup", "tags", "removed", "." ]
92611bec49e8fdfaea0c77d63b758d8643398fdf
https://github.com/gvalkov/python-ansimarkup/blob/92611bec49e8fdfaea0c77d63b758d8643398fdf/ansimarkup/markup.py#L71-L74
train
41,723
openstack/proliantutils
proliantutils/utils.py
process_firmware_image
def process_firmware_image(compact_firmware_file, ilo_object): """Processes the firmware file. Processing the firmware file entails extracting the firmware file from its compact format. Along with the raw (extracted) firmware file, this method also sends out information of whether or not the extracted firmware file a) needs to be uploaded to http store b) is extracted in reality or the file was already in raw format :param compact_firmware_file: firmware file to extract from :param ilo_object: ilo client object (ribcl/ris object) :raises: InvalidInputError, for unsupported file types or raw firmware file not found from compact format. :raises: ImageExtractionFailed, for extraction related issues :returns: core(raw) firmware file :returns: to_upload, boolean to indicate whether to upload or not :returns: is_extracted, boolean to indicate firmware image is actually extracted or not. """ fw_img_extractor = firmware_controller.get_fw_extractor( compact_firmware_file) LOG.debug('Extracting firmware file: %s ...', compact_firmware_file) raw_fw_file_path, is_extracted = fw_img_extractor.extract() # Note(deray): Need to check if this processing is for RIS or RIBCL # based systems. For Gen9 machines (RIS based) the firmware file needs # to be on a http store, and hence requires the upload to happen for the # firmware file. to_upload = False m = re.search('Gen(\d+)', ilo_object.model) if int(m.group(1)) > 8: to_upload = True LOG.debug('Extracting firmware file: %s ... done', compact_firmware_file) msg = ('Firmware file %(fw_file)s is %(msg)s. Need hosting (on an http ' 'store): %(yes_or_no)s' % {'fw_file': compact_firmware_file, 'msg': ('extracted. Extracted file: %s' % raw_fw_file_path if is_extracted else 'already in raw format'), 'yes_or_no': 'Yes' if to_upload else 'No'}) LOG.info(msg) return raw_fw_file_path, to_upload, is_extracted
python
def process_firmware_image(compact_firmware_file, ilo_object): """Processes the firmware file. Processing the firmware file entails extracting the firmware file from its compact format. Along with the raw (extracted) firmware file, this method also sends out information of whether or not the extracted firmware file a) needs to be uploaded to http store b) is extracted in reality or the file was already in raw format :param compact_firmware_file: firmware file to extract from :param ilo_object: ilo client object (ribcl/ris object) :raises: InvalidInputError, for unsupported file types or raw firmware file not found from compact format. :raises: ImageExtractionFailed, for extraction related issues :returns: core(raw) firmware file :returns: to_upload, boolean to indicate whether to upload or not :returns: is_extracted, boolean to indicate firmware image is actually extracted or not. """ fw_img_extractor = firmware_controller.get_fw_extractor( compact_firmware_file) LOG.debug('Extracting firmware file: %s ...', compact_firmware_file) raw_fw_file_path, is_extracted = fw_img_extractor.extract() # Note(deray): Need to check if this processing is for RIS or RIBCL # based systems. For Gen9 machines (RIS based) the firmware file needs # to be on a http store, and hence requires the upload to happen for the # firmware file. to_upload = False m = re.search('Gen(\d+)', ilo_object.model) if int(m.group(1)) > 8: to_upload = True LOG.debug('Extracting firmware file: %s ... done', compact_firmware_file) msg = ('Firmware file %(fw_file)s is %(msg)s. Need hosting (on an http ' 'store): %(yes_or_no)s' % {'fw_file': compact_firmware_file, 'msg': ('extracted. Extracted file: %s' % raw_fw_file_path if is_extracted else 'already in raw format'), 'yes_or_no': 'Yes' if to_upload else 'No'}) LOG.info(msg) return raw_fw_file_path, to_upload, is_extracted
[ "def", "process_firmware_image", "(", "compact_firmware_file", ",", "ilo_object", ")", ":", "fw_img_extractor", "=", "firmware_controller", ".", "get_fw_extractor", "(", "compact_firmware_file", ")", "LOG", ".", "debug", "(", "'Extracting firmware file: %s ...'", ",", "co...
Processes the firmware file. Processing the firmware file entails extracting the firmware file from its compact format. Along with the raw (extracted) firmware file, this method also sends out information of whether or not the extracted firmware file a) needs to be uploaded to http store b) is extracted in reality or the file was already in raw format :param compact_firmware_file: firmware file to extract from :param ilo_object: ilo client object (ribcl/ris object) :raises: InvalidInputError, for unsupported file types or raw firmware file not found from compact format. :raises: ImageExtractionFailed, for extraction related issues :returns: core(raw) firmware file :returns: to_upload, boolean to indicate whether to upload or not :returns: is_extracted, boolean to indicate firmware image is actually extracted or not.
[ "Processes", "the", "firmware", "file", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/utils.py#L33-L73
train
41,724
openstack/proliantutils
proliantutils/utils.py
_get_hash_object
def _get_hash_object(hash_algo_name): """Create a hash object based on given algorithm. :param hash_algo_name: name of the hashing algorithm. :raises: InvalidInputError, on unsupported or invalid input. :returns: a hash object based on the given named algorithm. """ algorithms = (hashlib.algorithms_guaranteed if six.PY3 else hashlib.algorithms) if hash_algo_name not in algorithms: msg = ("Unsupported/Invalid hash name '%s' provided." % hash_algo_name) raise exception.InvalidInputError(msg) return getattr(hashlib, hash_algo_name)()
python
def _get_hash_object(hash_algo_name): """Create a hash object based on given algorithm. :param hash_algo_name: name of the hashing algorithm. :raises: InvalidInputError, on unsupported or invalid input. :returns: a hash object based on the given named algorithm. """ algorithms = (hashlib.algorithms_guaranteed if six.PY3 else hashlib.algorithms) if hash_algo_name not in algorithms: msg = ("Unsupported/Invalid hash name '%s' provided." % hash_algo_name) raise exception.InvalidInputError(msg) return getattr(hashlib, hash_algo_name)()
[ "def", "_get_hash_object", "(", "hash_algo_name", ")", ":", "algorithms", "=", "(", "hashlib", ".", "algorithms_guaranteed", "if", "six", ".", "PY3", "else", "hashlib", ".", "algorithms", ")", "if", "hash_algo_name", "not", "in", "algorithms", ":", "msg", "=",...
Create a hash object based on given algorithm. :param hash_algo_name: name of the hashing algorithm. :raises: InvalidInputError, on unsupported or invalid input. :returns: a hash object based on the given named algorithm.
[ "Create", "a", "hash", "object", "based", "on", "given", "algorithm", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/utils.py#L76-L90
train
41,725
openstack/proliantutils
proliantutils/utils.py
hash_file
def hash_file(file_like_object, hash_algo='md5'): """Generate a hash for the contents of a file. It returns a hash of the file object as a string of double length, containing only hexadecimal digits. It supports all the algorithms hashlib does. :param file_like_object: file like object whose hash to be calculated. :param hash_algo: name of the hashing strategy, default being 'md5'. :raises: InvalidInputError, on unsupported or invalid input. :returns: a condensed digest of the bytes of contents. """ checksum = _get_hash_object(hash_algo) for chunk in iter(lambda: file_like_object.read(32768), b''): checksum.update(chunk) return checksum.hexdigest()
python
def hash_file(file_like_object, hash_algo='md5'): """Generate a hash for the contents of a file. It returns a hash of the file object as a string of double length, containing only hexadecimal digits. It supports all the algorithms hashlib does. :param file_like_object: file like object whose hash to be calculated. :param hash_algo: name of the hashing strategy, default being 'md5'. :raises: InvalidInputError, on unsupported or invalid input. :returns: a condensed digest of the bytes of contents. """ checksum = _get_hash_object(hash_algo) for chunk in iter(lambda: file_like_object.read(32768), b''): checksum.update(chunk) return checksum.hexdigest()
[ "def", "hash_file", "(", "file_like_object", ",", "hash_algo", "=", "'md5'", ")", ":", "checksum", "=", "_get_hash_object", "(", "hash_algo", ")", "for", "chunk", "in", "iter", "(", "lambda", ":", "file_like_object", ".", "read", "(", "32768", ")", ",", "b...
Generate a hash for the contents of a file. It returns a hash of the file object as a string of double length, containing only hexadecimal digits. It supports all the algorithms hashlib does. :param file_like_object: file like object whose hash to be calculated. :param hash_algo: name of the hashing strategy, default being 'md5'. :raises: InvalidInputError, on unsupported or invalid input. :returns: a condensed digest of the bytes of contents.
[ "Generate", "a", "hash", "for", "the", "contents", "of", "a", "file", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/utils.py#L93-L107
train
41,726
openstack/proliantutils
proliantutils/utils.py
validate_href
def validate_href(image_href): """Validate HTTP image reference. :param image_href: Image reference. :raises: exception.ImageRefValidationFailed if HEAD request failed or returned response code not equal to 200. :returns: Response to HEAD request. """ try: response = requests.head(image_href) if response.status_code != http_client.OK: raise exception.ImageRefValidationFailed( image_href=image_href, reason=("Got HTTP code %s instead of 200 in response to " "HEAD request." % response.status_code)) except requests.RequestException as e: raise exception.ImageRefValidationFailed(image_href=image_href, reason=e) return response
python
def validate_href(image_href): """Validate HTTP image reference. :param image_href: Image reference. :raises: exception.ImageRefValidationFailed if HEAD request failed or returned response code not equal to 200. :returns: Response to HEAD request. """ try: response = requests.head(image_href) if response.status_code != http_client.OK: raise exception.ImageRefValidationFailed( image_href=image_href, reason=("Got HTTP code %s instead of 200 in response to " "HEAD request." % response.status_code)) except requests.RequestException as e: raise exception.ImageRefValidationFailed(image_href=image_href, reason=e) return response
[ "def", "validate_href", "(", "image_href", ")", ":", "try", ":", "response", "=", "requests", ".", "head", "(", "image_href", ")", "if", "response", ".", "status_code", "!=", "http_client", ".", "OK", ":", "raise", "exception", ".", "ImageRefValidationFailed",...
Validate HTTP image reference. :param image_href: Image reference. :raises: exception.ImageRefValidationFailed if HEAD request failed or returned response code not equal to 200. :returns: Response to HEAD request.
[ "Validate", "HTTP", "image", "reference", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/utils.py#L138-L156
train
41,727
openstack/proliantutils
proliantutils/utils.py
apply_bios_properties_filter
def apply_bios_properties_filter(settings, filter_to_be_applied): """Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered BIOS settings. """ if not settings or not filter_to_be_applied: return settings return {k: settings[k] for k in filter_to_be_applied if k in settings}
python
def apply_bios_properties_filter(settings, filter_to_be_applied): """Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered BIOS settings. """ if not settings or not filter_to_be_applied: return settings return {k: settings[k] for k in filter_to_be_applied if k in settings}
[ "def", "apply_bios_properties_filter", "(", "settings", ",", "filter_to_be_applied", ")", ":", "if", "not", "settings", "or", "not", "filter_to_be_applied", ":", "return", "settings", "return", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "filte...
Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered BIOS settings.
[ "Applies", "the", "filter", "to", "return", "the", "dict", "of", "filtered", "BIOS", "properties", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/utils.py#L159-L169
train
41,728
openstack/proliantutils
proliantutils/redfish/resources/account_service/account_service.py
HPEAccountService.accounts
def accounts(self): """Property to provide instance of HPEAccountCollection""" return account.HPEAccountCollection( self._conn, utils.get_subresource_path_by(self, 'Accounts'), redfish_version=self.redfish_version)
python
def accounts(self): """Property to provide instance of HPEAccountCollection""" return account.HPEAccountCollection( self._conn, utils.get_subresource_path_by(self, 'Accounts'), redfish_version=self.redfish_version)
[ "def", "accounts", "(", "self", ")", ":", "return", "account", ".", "HPEAccountCollection", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "'Accounts'", ")", ",", "redfish_version", "=", "self", ".", "redfish_version...
Property to provide instance of HPEAccountCollection
[ "Property", "to", "provide", "instance", "of", "HPEAccountCollection" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/account_service/account_service.py#L31-L35
train
41,729
openstack/proliantutils
proliantutils/redfish/resources/account_service/account.py
HPEAccount.update_credentials
def update_credentials(self, password): """Update credentials of a redfish system :param password: password to be updated """ data = { 'Password': password, } self._conn.patch(self.path, data=data)
python
def update_credentials(self, password): """Update credentials of a redfish system :param password: password to be updated """ data = { 'Password': password, } self._conn.patch(self.path, data=data)
[ "def", "update_credentials", "(", "self", ",", "password", ")", ":", "data", "=", "{", "'Password'", ":", "password", ",", "}", "self", ".", "_conn", ".", "patch", "(", "self", ".", "path", ",", "data", "=", "data", ")" ]
Update credentials of a redfish system :param password: password to be updated
[ "Update", "credentials", "of", "a", "redfish", "system" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/account_service/account.py#L25-L33
train
41,730
openstack/proliantutils
proliantutils/redfish/resources/account_service/account.py
HPEAccountCollection.get_member_details
def get_member_details(self, username): """Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise """ members = self.get_members() for member in members: if member.username == username: return member
python
def get_member_details(self, username): """Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise """ members = self.get_members() for member in members: if member.username == username: return member
[ "def", "get_member_details", "(", "self", ",", "username", ")", ":", "members", "=", "self", ".", "get_members", "(", ")", "for", "member", "in", "members", ":", "if", "member", ".", "username", "==", "username", ":", "return", "member" ]
Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise
[ "Returns", "the", "HPEAccount", "object" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/account_service/account.py#L43-L52
train
41,731
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
_get_media
def _get_media(media_types): """Helper method to map the media types.""" get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
python
def _get_media(media_types): """Helper method to map the media types.""" get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
[ "def", "_get_media", "(", "media_types", ")", ":", "get_mapped_media", "=", "(", "lambda", "x", ":", "maps", ".", "VIRTUAL_MEDIA_TYPES_MAP", "[", "x", "]", "if", "x", "in", "maps", ".", "VIRTUAL_MEDIA_TYPES_MAP", "else", "None", ")", "return", "list", "(", ...
Helper method to map the media types.
[ "Helper", "method", "to", "map", "the", "media", "types", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L30-L34
train
41,732
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
VirtualMedia._get_action_element
def _get_action_element(self, action_type): """Helper method to return the action object.""" action = eval("self._hpe_actions." + action_type + "_vmedia") if not action: if action_type == "insert": action_path = '#HpeiLOVirtualMedia.InsertVirtualMedia' else: action_path = '#HpeiLOVirtualMedia.EjectVirtualMedia' raise exception.MissingAttributeError( attribute=action_path, resource=self._path) return action
python
def _get_action_element(self, action_type): """Helper method to return the action object.""" action = eval("self._hpe_actions." + action_type + "_vmedia") if not action: if action_type == "insert": action_path = '#HpeiLOVirtualMedia.InsertVirtualMedia' else: action_path = '#HpeiLOVirtualMedia.EjectVirtualMedia' raise exception.MissingAttributeError( attribute=action_path, resource=self._path) return action
[ "def", "_get_action_element", "(", "self", ",", "action_type", ")", ":", "action", "=", "eval", "(", "\"self._hpe_actions.\"", "+", "action_type", "+", "\"_vmedia\"", ")", "if", "not", "action", ":", "if", "action_type", "==", "\"insert\"", ":", "action_path", ...
Helper method to return the action object.
[ "Helper", "method", "to", "return", "the", "action", "object", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L53-L67
train
41,733
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
VirtualMedia.insert_media
def insert_media(self, url): """Inserts Virtual Media to the device :param url: URL to image. :raises: SushyError, on an error from iLO. """ try: super(VirtualMedia, self).insert_media(url, write_protected=True) except sushy_exceptions.SushyError: target_uri = self._get_action_element('insert').target_uri data = {'Image': url} self._conn.post(target_uri, data=data)
python
def insert_media(self, url): """Inserts Virtual Media to the device :param url: URL to image. :raises: SushyError, on an error from iLO. """ try: super(VirtualMedia, self).insert_media(url, write_protected=True) except sushy_exceptions.SushyError: target_uri = self._get_action_element('insert').target_uri data = {'Image': url} self._conn.post(target_uri, data=data)
[ "def", "insert_media", "(", "self", ",", "url", ")", ":", "try", ":", "super", "(", "VirtualMedia", ",", "self", ")", ".", "insert_media", "(", "url", ",", "write_protected", "=", "True", ")", "except", "sushy_exceptions", ".", "SushyError", ":", "target_u...
Inserts Virtual Media to the device :param url: URL to image. :raises: SushyError, on an error from iLO.
[ "Inserts", "Virtual", "Media", "to", "the", "device" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L69-L80
train
41,734
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
VirtualMedia.eject_media
def eject_media(self): """Ejects Virtual Media. :raises: SushyError, on an error from iLO. """ try: super(VirtualMedia, self).eject_media() except sushy_exceptions.SushyError: target_uri = self._get_action_element('eject').target_uri self._conn.post(target_uri, data={})
python
def eject_media(self): """Ejects Virtual Media. :raises: SushyError, on an error from iLO. """ try: super(VirtualMedia, self).eject_media() except sushy_exceptions.SushyError: target_uri = self._get_action_element('eject').target_uri self._conn.post(target_uri, data={})
[ "def", "eject_media", "(", "self", ")", ":", "try", ":", "super", "(", "VirtualMedia", ",", "self", ")", ".", "eject_media", "(", ")", "except", "sushy_exceptions", ".", "SushyError", ":", "target_uri", "=", "self", ".", "_get_action_element", "(", "'eject'"...
Ejects Virtual Media. :raises: SushyError, on an error from iLO.
[ "Ejects", "Virtual", "Media", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L82-L91
train
41,735
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
VirtualMedia.set_vm_status
def set_vm_status(self, boot_on_next_reset): """Set the Virtual Media drive status. :param boot_on_next_reset: boolean value :raises: SushyError, on an error from iLO. """ data = { "Oem": { "Hpe": { "BootOnNextServerReset": boot_on_next_reset } } } self._conn.patch(self.path, data=data)
python
def set_vm_status(self, boot_on_next_reset): """Set the Virtual Media drive status. :param boot_on_next_reset: boolean value :raises: SushyError, on an error from iLO. """ data = { "Oem": { "Hpe": { "BootOnNextServerReset": boot_on_next_reset } } } self._conn.patch(self.path, data=data)
[ "def", "set_vm_status", "(", "self", ",", "boot_on_next_reset", ")", ":", "data", "=", "{", "\"Oem\"", ":", "{", "\"Hpe\"", ":", "{", "\"BootOnNextServerReset\"", ":", "boot_on_next_reset", "}", "}", "}", "self", ".", "_conn", ".", "patch", "(", "self", "....
Set the Virtual Media drive status. :param boot_on_next_reset: boolean value :raises: SushyError, on an error from iLO.
[ "Set", "the", "Virtual", "Media", "drive", "status", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L93-L106
train
41,736
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
VirtualMediaCollection.get_member_device
def get_member_device(self, device): """Returns the given virtual media device object. :param device: virtual media device to be queried :returns virtual media device object. """ for vmedia_device in self.get_members(): if device in vmedia_device.media_types: return vmedia_device
python
def get_member_device(self, device): """Returns the given virtual media device object. :param device: virtual media device to be queried :returns virtual media device object. """ for vmedia_device in self.get_members(): if device in vmedia_device.media_types: return vmedia_device
[ "def", "get_member_device", "(", "self", ",", "device", ")", ":", "for", "vmedia_device", "in", "self", ".", "get_members", "(", ")", ":", "if", "device", "in", "vmedia_device", ".", "media_types", ":", "return", "vmedia_device" ]
Returns the given virtual media device object. :param device: virtual media device to be queried :returns virtual media device object.
[ "Returns", "the", "given", "virtual", "media", "device", "object", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L115-L123
train
41,737
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/table/_request.py
_get_entity
def _get_entity(partition_key, row_key, select, accept): ''' Constructs a get entity request. ''' _validate_not_none('partition_key', partition_key) _validate_not_none('row_key', row_key) _validate_not_none('accept', accept) request = HTTPRequest() request.method = 'GET' request.headers = [('Accept', _to_str(accept))] request.query = [('$select', _to_str(select))] return request
python
def _get_entity(partition_key, row_key, select, accept): ''' Constructs a get entity request. ''' _validate_not_none('partition_key', partition_key) _validate_not_none('row_key', row_key) _validate_not_none('accept', accept) request = HTTPRequest() request.method = 'GET' request.headers = [('Accept', _to_str(accept))] request.query = [('$select', _to_str(select))] return request
[ "def", "_get_entity", "(", "partition_key", ",", "row_key", ",", "select", ",", "accept", ")", ":", "_validate_not_none", "(", "'partition_key'", ",", "partition_key", ")", "_validate_not_none", "(", "'row_key'", ",", "row_key", ")", "_validate_not_none", "(", "'a...
Constructs a get entity request.
[ "Constructs", "a", "get", "entity", "request", "." ]
bd5482547f993c6eb56fd09070e15c2e9616e440
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/table/_request.py#L35-L47
train
41,738
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/table/_request.py
_insert_entity
def _insert_entity(entity): ''' Constructs an insert entity request. ''' _validate_entity(entity) request = HTTPRequest() request.method = 'POST' request.headers = [_DEFAULT_CONTENT_TYPE_HEADER, _DEFAULT_PREFER_HEADER, _DEFAULT_ACCEPT_HEADER] request.body = _get_request_body(_convert_entity_to_json(entity)) return request
python
def _insert_entity(entity): ''' Constructs an insert entity request. ''' _validate_entity(entity) request = HTTPRequest() request.method = 'POST' request.headers = [_DEFAULT_CONTENT_TYPE_HEADER, _DEFAULT_PREFER_HEADER, _DEFAULT_ACCEPT_HEADER] request.body = _get_request_body(_convert_entity_to_json(entity)) return request
[ "def", "_insert_entity", "(", "entity", ")", ":", "_validate_entity", "(", "entity", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'POST'", "request", ".", "headers", "=", "[", "_DEFAULT_CONTENT_TYPE_HEADER", ",", "_DEFAULT_PREFER...
Constructs an insert entity request.
[ "Constructs", "an", "insert", "entity", "request", "." ]
bd5482547f993c6eb56fd09070e15c2e9616e440
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/table/_request.py#L49-L62
train
41,739
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/table/_request.py
_delete_entity
def _delete_entity(partition_key, row_key, if_match): ''' Constructs a delete entity request. ''' _validate_not_none('if_match', if_match) _validate_not_none('partition_key', partition_key) _validate_not_none('row_key', row_key) request = HTTPRequest() request.method = 'DELETE' request.headers = [_DEFAULT_ACCEPT_HEADER, ('If-Match', _to_str(if_match))] return request
python
def _delete_entity(partition_key, row_key, if_match): ''' Constructs a delete entity request. ''' _validate_not_none('if_match', if_match) _validate_not_none('partition_key', partition_key) _validate_not_none('row_key', row_key) request = HTTPRequest() request.method = 'DELETE' request.headers = [_DEFAULT_ACCEPT_HEADER, ('If-Match', _to_str(if_match))] return request
[ "def", "_delete_entity", "(", "partition_key", ",", "row_key", ",", "if_match", ")", ":", "_validate_not_none", "(", "'if_match'", ",", "if_match", ")", "_validate_not_none", "(", "'partition_key'", ",", "partition_key", ")", "_validate_not_none", "(", "'row_key'", ...
Constructs a delete entity request.
[ "Constructs", "a", "delete", "entity", "request", "." ]
bd5482547f993c6eb56fd09070e15c2e9616e440
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/table/_request.py#L96-L108
train
41,740
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
find_executable
def find_executable(executable_name): """Tries to find executable in PATH environment It uses ``shutil.which`` method in Python3 and ``distutils.spawn.find_executable`` method in Python2.7 to find the absolute path to the 'name' executable. :param executable_name: name of the executable :returns: Returns the absolute path to the executable or None if not found. """ if six.PY3: executable_abs = shutil.which(executable_name) else: import distutils.spawn executable_abs = distutils.spawn.find_executable(executable_name) return executable_abs
python
def find_executable(executable_name): """Tries to find executable in PATH environment It uses ``shutil.which`` method in Python3 and ``distutils.spawn.find_executable`` method in Python2.7 to find the absolute path to the 'name' executable. :param executable_name: name of the executable :returns: Returns the absolute path to the executable or None if not found. """ if six.PY3: executable_abs = shutil.which(executable_name) else: import distutils.spawn executable_abs = distutils.spawn.find_executable(executable_name) return executable_abs
[ "def", "find_executable", "(", "executable_name", ")", ":", "if", "six", ".", "PY3", ":", "executable_abs", "=", "shutil", ".", "which", "(", "executable_name", ")", "else", ":", "import", "distutils", ".", "spawn", "executable_abs", "=", "distutils", ".", "...
Tries to find executable in PATH environment It uses ``shutil.which`` method in Python3 and ``distutils.spawn.find_executable`` method in Python2.7 to find the absolute path to the 'name' executable. :param executable_name: name of the executable :returns: Returns the absolute path to the executable or None if not found.
[ "Tries", "to", "find", "executable", "in", "PATH", "environment" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L56-L71
train
41,741
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
check_firmware_update_component
def check_firmware_update_component(func): """Checks the firmware update component.""" @six.wraps(func) def wrapper(self, filename, component_type): """Wrapper around ``update_firmware`` call. :param filename: location of the raw firmware file. :param component_type: Type of component to be applied to. """ component_type = component_type and component_type.lower() if (component_type not in SUPPORTED_FIRMWARE_UPDATE_COMPONENTS): msg = ("Got invalid component type for firmware update: " "``update_firmware`` is not supported on %(component)s" % {'component': component_type}) LOG.error(self._(msg)) # noqa raise exception.InvalidInputError(msg) return func(self, filename, component_type) return wrapper
python
def check_firmware_update_component(func): """Checks the firmware update component.""" @six.wraps(func) def wrapper(self, filename, component_type): """Wrapper around ``update_firmware`` call. :param filename: location of the raw firmware file. :param component_type: Type of component to be applied to. """ component_type = component_type and component_type.lower() if (component_type not in SUPPORTED_FIRMWARE_UPDATE_COMPONENTS): msg = ("Got invalid component type for firmware update: " "``update_firmware`` is not supported on %(component)s" % {'component': component_type}) LOG.error(self._(msg)) # noqa raise exception.InvalidInputError(msg) return func(self, filename, component_type) return wrapper
[ "def", "check_firmware_update_component", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "filename", ",", "component_type", ")", ":", "\"\"\"Wrapper around ``update_firmware`` call.\n\n :param filename: loca...
Checks the firmware update component.
[ "Checks", "the", "firmware", "update", "component", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L74-L93
train
41,742
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
get_fw_extractor
def get_fw_extractor(fw_file): """Gets the firmware extractor object fine-tuned for specified type :param fw_file: compact firmware file to be extracted from :raises: InvalidInputError, for unsupported file types :returns: FirmwareImageExtractor object """ fw_img_extractor = FirmwareImageExtractor(fw_file) extension = fw_img_extractor.fw_file_ext.lower() if extension == '.scexe': # assign _do_extract attribute to refer to _extract_scexe_file fw_img_extractor._do_extract = types.MethodType( _extract_scexe_file, fw_img_extractor) elif extension == '.rpm': # assign _do_extract attribute to refer to _extract_rpm_file fw_img_extractor._do_extract = types.MethodType( _extract_rpm_file, fw_img_extractor) elif extension in RAW_FIRMWARE_EXTNS: # Note(deray): Assigning ``extract`` attribute to return # 1. the firmware file itself # 2. boolean (False) to indicate firmware file is not extracted def dummy_extract(self): """Dummy (no-op) extract method :returns: the same firmware file with the complete path :returns: boolean(False) to indicate that a new file is not generated. """ return fw_img_extractor.fw_file, False fw_img_extractor.extract = types.MethodType( dummy_extract, fw_img_extractor) else: raise exception.InvalidInputError( 'Unexpected compact firmware file type: %s' % fw_file) return fw_img_extractor
python
def get_fw_extractor(fw_file): """Gets the firmware extractor object fine-tuned for specified type :param fw_file: compact firmware file to be extracted from :raises: InvalidInputError, for unsupported file types :returns: FirmwareImageExtractor object """ fw_img_extractor = FirmwareImageExtractor(fw_file) extension = fw_img_extractor.fw_file_ext.lower() if extension == '.scexe': # assign _do_extract attribute to refer to _extract_scexe_file fw_img_extractor._do_extract = types.MethodType( _extract_scexe_file, fw_img_extractor) elif extension == '.rpm': # assign _do_extract attribute to refer to _extract_rpm_file fw_img_extractor._do_extract = types.MethodType( _extract_rpm_file, fw_img_extractor) elif extension in RAW_FIRMWARE_EXTNS: # Note(deray): Assigning ``extract`` attribute to return # 1. the firmware file itself # 2. boolean (False) to indicate firmware file is not extracted def dummy_extract(self): """Dummy (no-op) extract method :returns: the same firmware file with the complete path :returns: boolean(False) to indicate that a new file is not generated. """ return fw_img_extractor.fw_file, False fw_img_extractor.extract = types.MethodType( dummy_extract, fw_img_extractor) else: raise exception.InvalidInputError( 'Unexpected compact firmware file type: %s' % fw_file) return fw_img_extractor
[ "def", "get_fw_extractor", "(", "fw_file", ")", ":", "fw_img_extractor", "=", "FirmwareImageExtractor", "(", "fw_file", ")", "extension", "=", "fw_img_extractor", ".", "fw_file_ext", ".", "lower", "(", ")", "if", "extension", "==", "'.scexe'", ":", "# assign _do_e...
Gets the firmware extractor object fine-tuned for specified type :param fw_file: compact firmware file to be extracted from :raises: InvalidInputError, for unsupported file types :returns: FirmwareImageExtractor object
[ "Gets", "the", "firmware", "extractor", "object", "fine", "-", "tuned", "for", "specified", "type" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L295-L332
train
41,743
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
_extract_scexe_file
def _extract_scexe_file(self, target_file, extract_path): """Extracts the scexe file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen """ # Command to extract the smart component file. unpack_cmd = '--unpack=' + extract_path # os.path.isfile(target_file) cmd = [target_file, unpack_cmd] out, err = utils.trycmd(*cmd)
python
def _extract_scexe_file(self, target_file, extract_path): """Extracts the scexe file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen """ # Command to extract the smart component file. unpack_cmd = '--unpack=' + extract_path # os.path.isfile(target_file) cmd = [target_file, unpack_cmd] out, err = utils.trycmd(*cmd)
[ "def", "_extract_scexe_file", "(", "self", ",", "target_file", ",", "extract_path", ")", ":", "# Command to extract the smart component file.", "unpack_cmd", "=", "'--unpack='", "+", "extract_path", "# os.path.isfile(target_file)", "cmd", "=", "[", "target_file", ",", "un...
Extracts the scexe file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen
[ "Extracts", "the", "scexe", "file", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L335-L345
train
41,744
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
_extract_rpm_file
def _extract_rpm_file(self, target_file, extract_path): """Extracts the rpm file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen :raises: ImageExtractionFailed, if any issue with extraction """ if not os.path.exists(extract_path): os.makedirs(extract_path) os.chdir(extract_path) if find_executable('rpm2cpio') is None: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Command `rpm2cpio` not found.') if find_executable('cpio') is None: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Command `cpio` not found.') try: rpm2cpio = subprocess.Popen('rpm2cpio ' + target_file, shell=True, stdout=subprocess.PIPE) cpio = subprocess.Popen('cpio -idm', shell=True, stdin=rpm2cpio.stdout) out, err = cpio.communicate() except (OSError, ValueError) as e: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Unexpected error in extracting file. ' + str(e))
python
def _extract_rpm_file(self, target_file, extract_path): """Extracts the rpm file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen :raises: ImageExtractionFailed, if any issue with extraction """ if not os.path.exists(extract_path): os.makedirs(extract_path) os.chdir(extract_path) if find_executable('rpm2cpio') is None: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Command `rpm2cpio` not found.') if find_executable('cpio') is None: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Command `cpio` not found.') try: rpm2cpio = subprocess.Popen('rpm2cpio ' + target_file, shell=True, stdout=subprocess.PIPE) cpio = subprocess.Popen('cpio -idm', shell=True, stdin=rpm2cpio.stdout) out, err = cpio.communicate() except (OSError, ValueError) as e: raise exception.ImageExtractionFailed( image_ref=target_file, reason='Unexpected error in extracting file. ' + str(e))
[ "def", "_extract_rpm_file", "(", "self", ",", "target_file", ",", "extract_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "extract_path", ")", ":", "os", ".", "makedirs", "(", "extract_path", ")", "os", ".", "chdir", "(", "extract_p...
Extracts the rpm file. :param target_file: the firmware file to be extracted from :param extract_path: the path where extraction is supposed to happen :raises: ImageExtractionFailed, if any issue with extraction
[ "Extracts", "the", "rpm", "file", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L348-L375
train
41,745
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
_get_firmware_file
def _get_firmware_file(path): """Gets the raw firmware file Gets the raw firmware file from the extracted directory structure :param path: the directory structure to search for :returns: the raw firmware file with the complete path """ for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: file_name, file_ext = os.path.splitext(os.path.basename(filename)) if file_ext in RAW_FIRMWARE_EXTNS: # return filename return os.path.join(dirpath, filename)
python
def _get_firmware_file(path): """Gets the raw firmware file Gets the raw firmware file from the extracted directory structure :param path: the directory structure to search for :returns: the raw firmware file with the complete path """ for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: file_name, file_ext = os.path.splitext(os.path.basename(filename)) if file_ext in RAW_FIRMWARE_EXTNS: # return filename return os.path.join(dirpath, filename)
[ "def", "_get_firmware_file", "(", "path", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "filename", "in", "filenames", ":", "file_name", ",", "file_ext", "=", "os", ".", "path", "....
Gets the raw firmware file Gets the raw firmware file from the extracted directory structure :param path: the directory structure to search for :returns: the raw firmware file with the complete path
[ "Gets", "the", "raw", "firmware", "file" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L378-L390
train
41,746
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
_get_firmware_file_in_new_path
def _get_firmware_file_in_new_path(searching_path): """Gets the raw firmware file in a new path Gets the raw firmware file from the extracted directory structure and creates a hard link to that in a file path and cleans up the lookup extract path. :param searching_path: the directory structure to search for :returns: the raw firmware file with the complete new path """ firmware_file_path = _get_firmware_file(searching_path) if not firmware_file_path: return None # Note(deray): the path of the new firmware file will be of the form: # # [TEMP_DIR]/xxx-xxx_actual_firmware_filename # # e.g. /tmp/77e8f689-f32c-4727-9fc3-a7dacefe67e4_ilo4_210.bin file_name, file_ext_with_dot = common.get_filename_and_extension_of( firmware_file_path) new_firmware_file_path = os.path.join( tempfile.gettempdir(), str(uuid.uuid4()) + '_' + file_name + file_ext_with_dot) # create a hard link to the raw firmware file os.link(firmware_file_path, new_firmware_file_path) return new_firmware_file_path
python
def _get_firmware_file_in_new_path(searching_path): """Gets the raw firmware file in a new path Gets the raw firmware file from the extracted directory structure and creates a hard link to that in a file path and cleans up the lookup extract path. :param searching_path: the directory structure to search for :returns: the raw firmware file with the complete new path """ firmware_file_path = _get_firmware_file(searching_path) if not firmware_file_path: return None # Note(deray): the path of the new firmware file will be of the form: # # [TEMP_DIR]/xxx-xxx_actual_firmware_filename # # e.g. /tmp/77e8f689-f32c-4727-9fc3-a7dacefe67e4_ilo4_210.bin file_name, file_ext_with_dot = common.get_filename_and_extension_of( firmware_file_path) new_firmware_file_path = os.path.join( tempfile.gettempdir(), str(uuid.uuid4()) + '_' + file_name + file_ext_with_dot) # create a hard link to the raw firmware file os.link(firmware_file_path, new_firmware_file_path) return new_firmware_file_path
[ "def", "_get_firmware_file_in_new_path", "(", "searching_path", ")", ":", "firmware_file_path", "=", "_get_firmware_file", "(", "searching_path", ")", "if", "not", "firmware_file_path", ":", "return", "None", "# Note(deray): the path of the new firmware file will be of the form:"...
Gets the raw firmware file in a new path Gets the raw firmware file from the extracted directory structure and creates a hard link to that in a file path and cleans up the lookup extract path. :param searching_path: the directory structure to search for :returns: the raw firmware file with the complete new path
[ "Gets", "the", "raw", "firmware", "file", "in", "a", "new", "path" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L393-L419
train
41,747
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
FirmwareImageUploader.upload_file_to
def upload_file_to(self, addressinfo, timeout): """Uploads the raw firmware file to iLO Uploads the raw firmware file (already set as attribute in FirmwareImageControllerBase constructor) to iLO, whose address information is passed to this method. :param addressinfo: tuple of hostname and port of the iLO :param timeout: timeout in secs, used for connecting to iLO :raises: IloInvalidInputError, if raw firmware file not found :raises: IloError, for other internal problems :returns: the cookie so sent back from iLO on successful upload """ self.hostname, self.port = addressinfo self.timeout = timeout filename = self.fw_file firmware = open(filename, 'rb').read() # generate boundary boundary = b('------hpiLO3t' + str(random.randint(100000, 1000000)) + 'z') while boundary in firmware: boundary = b('------hpiLO3t' + str(random.randint(100000, 1000000)) + 'z') # generate body parts parts = [ # body1 b("--") + boundary + b("""\r\nContent-Disposition: form-data; """ """name="fileType"\r\n\r\n"""), # body2 b("\r\n--") + boundary + b('''\r\nContent-Disposition: form-data; name="fwimgfile"; ''' '''filename="''') + b(filename) + b('''"\r\nContent-Type: application/octet-stream\r\n\r\n'''), # firmware image firmware, # body3 b("\r\n--") + boundary + b("--\r\n"), ] total_bytes = sum([len(x) for x in parts]) sock = self._get_socket() # send the firmware image sock.write(b(self.HTTP_UPLOAD_HEADER % (total_bytes, boundary.decode('ascii')))) for part in parts: sock.write(part) data = '' try: while True: d = sock.read() data += d.decode('latin-1') if not d: break except socket.sslerror: # Connection closed e = sys.exc_info()[1] if not data: raise exception.IloConnectionError( "Communication with %(hostname)s:%(port)d failed: " "%(error)s" % {'hostname': self.hostname, 'port': self.port, 'error': str(e)}) # Received len(data) bytes cookie_match = re.search('Set-Cookie: *(.*)', data) if not cookie_match: raise exception.IloError("Uploading of file: %s failed due " "to unknown reason." % filename) # return the cookie return cookie_match.group(1)
python
def upload_file_to(self, addressinfo, timeout): """Uploads the raw firmware file to iLO Uploads the raw firmware file (already set as attribute in FirmwareImageControllerBase constructor) to iLO, whose address information is passed to this method. :param addressinfo: tuple of hostname and port of the iLO :param timeout: timeout in secs, used for connecting to iLO :raises: IloInvalidInputError, if raw firmware file not found :raises: IloError, for other internal problems :returns: the cookie so sent back from iLO on successful upload """ self.hostname, self.port = addressinfo self.timeout = timeout filename = self.fw_file firmware = open(filename, 'rb').read() # generate boundary boundary = b('------hpiLO3t' + str(random.randint(100000, 1000000)) + 'z') while boundary in firmware: boundary = b('------hpiLO3t' + str(random.randint(100000, 1000000)) + 'z') # generate body parts parts = [ # body1 b("--") + boundary + b("""\r\nContent-Disposition: form-data; """ """name="fileType"\r\n\r\n"""), # body2 b("\r\n--") + boundary + b('''\r\nContent-Disposition: form-data; name="fwimgfile"; ''' '''filename="''') + b(filename) + b('''"\r\nContent-Type: application/octet-stream\r\n\r\n'''), # firmware image firmware, # body3 b("\r\n--") + boundary + b("--\r\n"), ] total_bytes = sum([len(x) for x in parts]) sock = self._get_socket() # send the firmware image sock.write(b(self.HTTP_UPLOAD_HEADER % (total_bytes, boundary.decode('ascii')))) for part in parts: sock.write(part) data = '' try: while True: d = sock.read() data += d.decode('latin-1') if not d: break except socket.sslerror: # Connection closed e = sys.exc_info()[1] if not data: raise exception.IloConnectionError( "Communication with %(hostname)s:%(port)d failed: " "%(error)s" % {'hostname': self.hostname, 'port': self.port, 'error': str(e)}) # Received len(data) bytes cookie_match = re.search('Set-Cookie: *(.*)', data) if not cookie_match: raise exception.IloError("Uploading of file: %s failed due " "to unknown reason." % filename) # return the cookie return cookie_match.group(1)
[ "def", "upload_file_to", "(", "self", ",", "addressinfo", ",", "timeout", ")", ":", "self", ".", "hostname", ",", "self", ".", "port", "=", "addressinfo", "self", ".", "timeout", "=", "timeout", "filename", "=", "self", ".", "fw_file", "firmware", "=", "...
Uploads the raw firmware file to iLO Uploads the raw firmware file (already set as attribute in FirmwareImageControllerBase constructor) to iLO, whose address information is passed to this method. :param addressinfo: tuple of hostname and port of the iLO :param timeout: timeout in secs, used for connecting to iLO :raises: IloInvalidInputError, if raw firmware file not found :raises: IloError, for other internal problems :returns: the cookie so sent back from iLO on successful upload
[ "Uploads", "the", "raw", "firmware", "file", "to", "iLO" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L120-L191
train
41,748
openstack/proliantutils
proliantutils/ilo/firmware_controller.py
FirmwareImageExtractor.extract
def extract(self): """Extracts the raw firmware file from its compact format Extracts the raw firmware file from its compact file format (already set as attribute in FirmwareImageControllerBase constructor). :raises: InvalidInputError, if raw firmware file not found :raises: ImageExtractionFailed, for extraction related issues :returns: the raw firmware file with the complete path :returns: boolean(True) to indicate that a new file got generated after successful extraction. """ target_file = self.fw_file common.add_exec_permission_to(target_file) # create a temp directory where the extraction will occur temp_dir = tempfile.mkdtemp() extract_path = os.path.join(temp_dir, self.fw_filename) try: self._do_extract(target_file, extract_path) except exception.ImageExtractionFailed: # clean up the partial extracted content, if any, # along with temp dir and re-raise the exception shutil.rmtree(temp_dir, ignore_errors=True) raise # creating a new hard link to the core firmware file firmware_file_path = _get_firmware_file_in_new_path(extract_path) # delete the entire extracted content along with temp dir. shutil.rmtree(temp_dir, ignore_errors=True) if not firmware_file_path: raise exception.InvalidInputError( "Raw firmware file not found in: '%s'" % target_file) return firmware_file_path, True
python
def extract(self): """Extracts the raw firmware file from its compact format Extracts the raw firmware file from its compact file format (already set as attribute in FirmwareImageControllerBase constructor). :raises: InvalidInputError, if raw firmware file not found :raises: ImageExtractionFailed, for extraction related issues :returns: the raw firmware file with the complete path :returns: boolean(True) to indicate that a new file got generated after successful extraction. """ target_file = self.fw_file common.add_exec_permission_to(target_file) # create a temp directory where the extraction will occur temp_dir = tempfile.mkdtemp() extract_path = os.path.join(temp_dir, self.fw_filename) try: self._do_extract(target_file, extract_path) except exception.ImageExtractionFailed: # clean up the partial extracted content, if any, # along with temp dir and re-raise the exception shutil.rmtree(temp_dir, ignore_errors=True) raise # creating a new hard link to the core firmware file firmware_file_path = _get_firmware_file_in_new_path(extract_path) # delete the entire extracted content along with temp dir. shutil.rmtree(temp_dir, ignore_errors=True) if not firmware_file_path: raise exception.InvalidInputError( "Raw firmware file not found in: '%s'" % target_file) return firmware_file_path, True
[ "def", "extract", "(", "self", ")", ":", "target_file", "=", "self", ".", "fw_file", "common", ".", "add_exec_permission_to", "(", "target_file", ")", "# create a temp directory where the extraction will occur", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", ...
Extracts the raw firmware file from its compact format Extracts the raw firmware file from its compact file format (already set as attribute in FirmwareImageControllerBase constructor). :raises: InvalidInputError, if raw firmware file not found :raises: ImageExtractionFailed, for extraction related issues :returns: the raw firmware file with the complete path :returns: boolean(True) to indicate that a new file got generated after successful extraction.
[ "Extracts", "the", "raw", "firmware", "file", "from", "its", "compact", "format" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L258-L292
train
41,749
openstack/proliantutils
proliantutils/redfish/resources/system/smart_storage_config.py
HPESmartStorageConfig._generic_format
def _generic_format(self, raid_config, controller=None): """Convert redfish data of current raid config to generic format. :param raid_config: Raid configuration dictionary :param controller: Array controller model in post_create read else None :returns: current raid config. """ logical_drives = raid_config["LogicalDrives"] logical_disks = [] controller = controller for ld in logical_drives: prop = {'size_gb': ld['CapacityGiB'], 'raid_level': ld['Raid'].strip('Raid'), 'root_device_hint': { 'wwn': '0x' + ld['VolumeUniqueIdentifier']}, 'controller': controller, 'physical_disks': ld['DataDrives'], 'volume_name': ld['LogicalDriveName']} logical_disks.append(prop) return logical_disks
python
def _generic_format(self, raid_config, controller=None): """Convert redfish data of current raid config to generic format. :param raid_config: Raid configuration dictionary :param controller: Array controller model in post_create read else None :returns: current raid config. """ logical_drives = raid_config["LogicalDrives"] logical_disks = [] controller = controller for ld in logical_drives: prop = {'size_gb': ld['CapacityGiB'], 'raid_level': ld['Raid'].strip('Raid'), 'root_device_hint': { 'wwn': '0x' + ld['VolumeUniqueIdentifier']}, 'controller': controller, 'physical_disks': ld['DataDrives'], 'volume_name': ld['LogicalDriveName']} logical_disks.append(prop) return logical_disks
[ "def", "_generic_format", "(", "self", ",", "raid_config", ",", "controller", "=", "None", ")", ":", "logical_drives", "=", "raid_config", "[", "\"LogicalDrives\"", "]", "logical_disks", "=", "[", "]", "controller", "=", "controller", "for", "ld", "in", "logic...
Convert redfish data of current raid config to generic format. :param raid_config: Raid configuration dictionary :param controller: Array controller model in post_create read else None :returns: current raid config.
[ "Convert", "redfish", "data", "of", "current", "raid", "config", "to", "generic", "format", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/smart_storage_config.py#L48-L68
train
41,750
openstack/proliantutils
proliantutils/redfish/resources/system/smart_storage_config.py
HPESmartStorageConfig._check_smart_storage_message
def _check_smart_storage_message(self): """Check for smart storage message. :returns: result, raid_message """ ssc_mesg = self.smart_storage_config_message result = True raid_message = "" for element in ssc_mesg: if "Success" not in element['MessageId']: result = False raid_message = element['MessageId'] return result, raid_message
python
def _check_smart_storage_message(self): """Check for smart storage message. :returns: result, raid_message """ ssc_mesg = self.smart_storage_config_message result = True raid_message = "" for element in ssc_mesg: if "Success" not in element['MessageId']: result = False raid_message = element['MessageId'] return result, raid_message
[ "def", "_check_smart_storage_message", "(", "self", ")", ":", "ssc_mesg", "=", "self", ".", "smart_storage_config_message", "result", "=", "True", "raid_message", "=", "\"\"", "for", "element", "in", "ssc_mesg", ":", "if", "\"Success\"", "not", "in", "element", ...
Check for smart storage message. :returns: result, raid_message
[ "Check", "for", "smart", "storage", "message", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/smart_storage_config.py#L70-L82
train
41,751
openstack/proliantutils
proliantutils/redfish/resources/system/smart_storage_config.py
HPESmartStorageConfig.read_raid
def read_raid(self, controller=None): """Get the current RAID configuration from the system. :param controller: If controller model its post-create read else post-delete :returns: current raid config. """ if controller: if not self.logical_drives: msg = ('No logical drives found on the controller') LOG.debug(msg) raise exception.IloLogicalDriveNotFoundError(msg) raid_op = 'create_raid' else: raid_op = 'delete_raid' result, raid_message = self._check_smart_storage_message() if result: configured_raid_settings = self._conn.get(self.settings_uri) raid_data = { 'logical_disks': self._generic_format( configured_raid_settings.json(), controller=controller)} return raid_data else: if self.physical_drives is None or not raid_message: # This controller is not configured or controller # not used in raid operation return else: msg = ('Failed to perform the %(opr)s operation ' 'successfully. Error - %(error)s' % {'opr': raid_op, 'error': str(raid_message)}) raise exception.IloError(msg)
python
def read_raid(self, controller=None): """Get the current RAID configuration from the system. :param controller: If controller model its post-create read else post-delete :returns: current raid config. """ if controller: if not self.logical_drives: msg = ('No logical drives found on the controller') LOG.debug(msg) raise exception.IloLogicalDriveNotFoundError(msg) raid_op = 'create_raid' else: raid_op = 'delete_raid' result, raid_message = self._check_smart_storage_message() if result: configured_raid_settings = self._conn.get(self.settings_uri) raid_data = { 'logical_disks': self._generic_format( configured_raid_settings.json(), controller=controller)} return raid_data else: if self.physical_drives is None or not raid_message: # This controller is not configured or controller # not used in raid operation return else: msg = ('Failed to perform the %(opr)s operation ' 'successfully. Error - %(error)s' % {'opr': raid_op, 'error': str(raid_message)}) raise exception.IloError(msg)
[ "def", "read_raid", "(", "self", ",", "controller", "=", "None", ")", ":", "if", "controller", ":", "if", "not", "self", ".", "logical_drives", ":", "msg", "=", "(", "'No logical drives found on the controller'", ")", "LOG", ".", "debug", "(", "msg", ")", ...
Get the current RAID configuration from the system. :param controller: If controller model its post-create read else post-delete :returns: current raid config.
[ "Get", "the", "current", "RAID", "configuration", "from", "the", "system", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/smart_storage_config.py#L84-L117
train
41,752
openstack/proliantutils
proliantutils/redfish/resources/system/smart_storage_config.py
HPESmartStorageConfig.delete_raid
def delete_raid(self): """Clears the RAID configuration from the system. """ if not self.logical_drives: msg = ('No logical drives found on the controller ' '%(controller)s' % {'controller': str(self.controller_id)}) LOG.debug(msg) raise exception.IloLogicalDriveNotFoundError(msg) lds = [{ 'Actions': [{"Action": "LogicalDriveDelete"}], 'VolumeUniqueIdentifier': logical_drive.volume_unique_identifier} for logical_drive in self.logical_drives] data = {'LogicalDrives': lds, 'DataGuard': 'Permissive'} self._conn.put(self.settings_uri, data=data)
python
def delete_raid(self): """Clears the RAID configuration from the system. """ if not self.logical_drives: msg = ('No logical drives found on the controller ' '%(controller)s' % {'controller': str(self.controller_id)}) LOG.debug(msg) raise exception.IloLogicalDriveNotFoundError(msg) lds = [{ 'Actions': [{"Action": "LogicalDriveDelete"}], 'VolumeUniqueIdentifier': logical_drive.volume_unique_identifier} for logical_drive in self.logical_drives] data = {'LogicalDrives': lds, 'DataGuard': 'Permissive'} self._conn.put(self.settings_uri, data=data)
[ "def", "delete_raid", "(", "self", ")", ":", "if", "not", "self", ".", "logical_drives", ":", "msg", "=", "(", "'No logical drives found on the controller '", "'%(controller)s'", "%", "{", "'controller'", ":", "str", "(", "self", ".", "controller_id", ")", "}", ...
Clears the RAID configuration from the system.
[ "Clears", "the", "RAID", "configuration", "from", "the", "system", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/smart_storage_config.py#L119-L136
train
41,753
NuGrid/NuGridPy
nugridpy/ppn.py
xtime._readFile
def _readFile(self, fname, sldir): ''' Private method that reads in the data file and organizes it within this object. ''' if sldir.endswith('/'): fname = str(sldir)+str(fname) else: fname = str(sldir)+'/'+str(fname) f=open(fname,'r') # read header line line=f.readline() cols = [] ispec = 0 for i in range(1,len(line.split('|'))): col = line.split('|')[i].strip() if '-' in col: ispec += 1 col = col.split('-')[1] cols.append(col) col_num={} col_tot = len(cols) print('number of species: ', str(ispec)) print('number of cols: ', str(col_tot)) col_num={} for a,b in zip(cols,list(range(col_tot))): col_num[a]=b # read remainder of the file lines=f.readlines() data=[] for i in range(len(lines)): v=lines[i].split() vv=array(v,dtype='float') data.append(vv) ilines=i print("There are "+str(ilines)+" time steps found.") return data,col_num,cols,col_tot,ilines
python
def _readFile(self, fname, sldir): ''' Private method that reads in the data file and organizes it within this object. ''' if sldir.endswith('/'): fname = str(sldir)+str(fname) else: fname = str(sldir)+'/'+str(fname) f=open(fname,'r') # read header line line=f.readline() cols = [] ispec = 0 for i in range(1,len(line.split('|'))): col = line.split('|')[i].strip() if '-' in col: ispec += 1 col = col.split('-')[1] cols.append(col) col_num={} col_tot = len(cols) print('number of species: ', str(ispec)) print('number of cols: ', str(col_tot)) col_num={} for a,b in zip(cols,list(range(col_tot))): col_num[a]=b # read remainder of the file lines=f.readlines() data=[] for i in range(len(lines)): v=lines[i].split() vv=array(v,dtype='float') data.append(vv) ilines=i print("There are "+str(ilines)+" time steps found.") return data,col_num,cols,col_tot,ilines
[ "def", "_readFile", "(", "self", ",", "fname", ",", "sldir", ")", ":", "if", "sldir", ".", "endswith", "(", "'/'", ")", ":", "fname", "=", "str", "(", "sldir", ")", "+", "str", "(", "fname", ")", "else", ":", "fname", "=", "str", "(", "sldir", ...
Private method that reads in the data file and organizes it within this object.
[ "Private", "method", "that", "reads", "in", "the", "data", "file", "and", "organizes", "it", "within", "this", "object", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L150-L192
train
41,754
NuGrid/NuGridPy
nugridpy/ppn.py
xtime.get
def get(self, col_str): ''' get one data column with the data Parameters ---------- col_str : string One of the column strings in self.cols. ''' data_column=zeros(self.ilines) for i in range(self.ilines): data_column[i]=self.data[i][self.col_num[col_str]] return data_column
python
def get(self, col_str): ''' get one data column with the data Parameters ---------- col_str : string One of the column strings in self.cols. ''' data_column=zeros(self.ilines) for i in range(self.ilines): data_column[i]=self.data[i][self.col_num[col_str]] return data_column
[ "def", "get", "(", "self", ",", "col_str", ")", ":", "data_column", "=", "zeros", "(", "self", ".", "ilines", ")", "for", "i", "in", "range", "(", "self", ".", "ilines", ")", ":", "data_column", "[", "i", "]", "=", "self", ".", "data", "[", "i", ...
get one data column with the data Parameters ---------- col_str : string One of the column strings in self.cols.
[ "get", "one", "data", "column", "with", "the", "data" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L194-L207
train
41,755
NuGrid/NuGridPy
nugridpy/ppn.py
xtime.plot_xtime
def plot_xtime(self, y, x='time', label='default', labelx=None, labely=None ,title=None, shape='.', logx=False, logy=True, base=10): ''' make a simple plot of two columns against each other. An example would be instance.plot_xtime('PB206', label='PB206 vs t_y' Recomend using the plot function DataPlot.plot() it has more functionality. Parameters ---------- Y : string Column on Y-axis. X : string, optional Column on X-axis. The default is "time". label : string, optional Legend label. The default is "default". labelX : string, optional The label on the X axis. The default is None. labelY : string, optional The label on the Y axis. The default is None. title : string, optional The Title of the Graph. The default is None. shape : string, optional What shape and colour the user would like their plot in. The default is '.'. logX : boolean, optional A boolean of weather the user wants the x axis logarithmically. The default is False. logY : boolean, optional A boolean of weather the user wants the Y axis logarithmically. The default is True. base : integer, optional The base of the logarithm. The default is 10. Notes ----- For all possable choices visit, <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot> ''' if label is 'default': lab_str=y else: lab_str=label try: self.get(x) except KeyError: x='age' DataPlot.plot(self,x,y,legend=lab_str,labelx=labelx, labely=labely, title=title, shape=shape,logx=logx, logy=logy, base=base) ''' print X,Y xdat=self.get(X) ydat=self.get(Y) self.xdat = xdat self.ydat = ydat plot(xdat,log10(ydat),label=lab_str) legend() '''
python
def plot_xtime(self, y, x='time', label='default', labelx=None, labely=None ,title=None, shape='.', logx=False, logy=True, base=10): ''' make a simple plot of two columns against each other. An example would be instance.plot_xtime('PB206', label='PB206 vs t_y' Recomend using the plot function DataPlot.plot() it has more functionality. Parameters ---------- Y : string Column on Y-axis. X : string, optional Column on X-axis. The default is "time". label : string, optional Legend label. The default is "default". labelX : string, optional The label on the X axis. The default is None. labelY : string, optional The label on the Y axis. The default is None. title : string, optional The Title of the Graph. The default is None. shape : string, optional What shape and colour the user would like their plot in. The default is '.'. logX : boolean, optional A boolean of weather the user wants the x axis logarithmically. The default is False. logY : boolean, optional A boolean of weather the user wants the Y axis logarithmically. The default is True. base : integer, optional The base of the logarithm. The default is 10. Notes ----- For all possable choices visit, <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot> ''' if label is 'default': lab_str=y else: lab_str=label try: self.get(x) except KeyError: x='age' DataPlot.plot(self,x,y,legend=lab_str,labelx=labelx, labely=labely, title=title, shape=shape,logx=logx, logy=logy, base=base) ''' print X,Y xdat=self.get(X) ydat=self.get(Y) self.xdat = xdat self.ydat = ydat plot(xdat,log10(ydat),label=lab_str) legend() '''
[ "def", "plot_xtime", "(", "self", ",", "y", ",", "x", "=", "'time'", ",", "label", "=", "'default'", ",", "labelx", "=", "None", ",", "labely", "=", "None", ",", "title", "=", "None", ",", "shape", "=", "'.'", ",", "logx", "=", "False", ",", "log...
make a simple plot of two columns against each other. An example would be instance.plot_xtime('PB206', label='PB206 vs t_y' Recomend using the plot function DataPlot.plot() it has more functionality. Parameters ---------- Y : string Column on Y-axis. X : string, optional Column on X-axis. The default is "time". label : string, optional Legend label. The default is "default". labelX : string, optional The label on the X axis. The default is None. labelY : string, optional The label on the Y axis. The default is None. title : string, optional The Title of the Graph. The default is None. shape : string, optional What shape and colour the user would like their plot in. The default is '.'. logX : boolean, optional A boolean of weather the user wants the x axis logarithmically. The default is False. logY : boolean, optional A boolean of weather the user wants the Y axis logarithmically. The default is True. base : integer, optional The base of the logarithm. The default is 10. Notes ----- For all possable choices visit, <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot>
[ "make", "a", "simple", "plot", "of", "two", "columns", "against", "each", "other", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L209-L273
train
41,756
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector.getCycleData
def getCycleData(self, attri, fname, numtype='cycNum'): """ In this method a column of data for the associated cycle attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". """ fname=self.findFile(fname,numtype) if self.inputdir == '': self.inputdir = self.sldir # This chunk of code changes into the directory where fname is, os.chdir(self.inputdir) # and appends a '/' to the directory title so it accesses the self.sldir=os.getcwd() + '/' # file correctly f=open(fname,'r') lines=f.readlines() if self.inputdir != './': #This chunk of code changes back into the directory you started in. os.chdir(self.startdir) self.sldir = self.inputdir for i in range(len(lines)): lines[i]=lines[i].strip() for i in range(len(lines)): if lines[i].startswith('#'): lines[i]=lines[i].strip('#') tmp=lines[i].split() tmp1=[] for j in range(len(tmp)): if tmp[j] != '=' or '': tmp1.append(tmp[j]) tmp=tmp1 for j in range(len(tmp)): if tmp[j]== attri: try: if '.' in tmp[j+1]: return float(tmp[j+1]) else: return int(tmp[j+1]) except ValueError: return str(tmp[j+1]) elif lines[i].startswith('H'): continue else: print('This cycle attribute does not exist') print('Returning None') return None
python
def getCycleData(self, attri, fname, numtype='cycNum'): """ In this method a column of data for the associated cycle attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". """ fname=self.findFile(fname,numtype) if self.inputdir == '': self.inputdir = self.sldir # This chunk of code changes into the directory where fname is, os.chdir(self.inputdir) # and appends a '/' to the directory title so it accesses the self.sldir=os.getcwd() + '/' # file correctly f=open(fname,'r') lines=f.readlines() if self.inputdir != './': #This chunk of code changes back into the directory you started in. os.chdir(self.startdir) self.sldir = self.inputdir for i in range(len(lines)): lines[i]=lines[i].strip() for i in range(len(lines)): if lines[i].startswith('#'): lines[i]=lines[i].strip('#') tmp=lines[i].split() tmp1=[] for j in range(len(tmp)): if tmp[j] != '=' or '': tmp1.append(tmp[j]) tmp=tmp1 for j in range(len(tmp)): if tmp[j]== attri: try: if '.' in tmp[j+1]: return float(tmp[j+1]) else: return int(tmp[j+1]) except ValueError: return str(tmp[j+1]) elif lines[i].startswith('H'): continue else: print('This cycle attribute does not exist') print('Returning None') return None
[ "def", "getCycleData", "(", "self", ",", "attri", ",", "fname", ",", "numtype", "=", "'cycNum'", ")", ":", "fname", "=", "self", ".", "findFile", "(", "fname", ",", "numtype", ")", "if", "self", ".", "inputdir", "==", "''", ":", "self", ".", "inputdi...
In this method a column of data for the associated cycle attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum".
[ "In", "this", "method", "a", "column", "of", "data", "for", "the", "associated", "cycle", "attribute", "is", "returned", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L478-L540
train
41,757
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector.getColData
def getColData(self, attri, fname, numtype='cycNum'): """ In this method a column of data for the associated column attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". """ fname=self.findFile(fname,numtype) f=open(fname,'r') for i in range(self.index+1): f.readline() lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() lines[i]=lines[i].split() index=0 data=[] while index < len (self.dcols): if attri== self.dcols[index]: break index+=1 for i in range(len(lines)): if index==5 and len(lines[i])==7: data.append(str(lines[i][index].capitalize())+'-'\ +str(lines[i][index+1])) elif index==5 and len(lines[i])!=7: tmp=str(lines[i][index]) if tmp[len(tmp)-1].isdigit(): tmp1=tmp[0]+tmp[1] tmp1=tmp1.capitalize() tmp2='' for j in range(len(tmp)): if j == 0 or j == 1: continue tmp2+=tmp[j] data.append(tmp1+'-'+tmp2) elif tmp=='PROT': data.append('H-1') elif tmp==('NEUT'or'NEUTR'or'nn'or'N 1'or'N-1'): data.append('N-1') else: data.append(tmp) elif index==0: data.append(int(lines[i][index])) else: data.append(float(lines[i][index])) return array(data)
python
def getColData(self, attri, fname, numtype='cycNum'): """ In this method a column of data for the associated column attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". """ fname=self.findFile(fname,numtype) f=open(fname,'r') for i in range(self.index+1): f.readline() lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() lines[i]=lines[i].split() index=0 data=[] while index < len (self.dcols): if attri== self.dcols[index]: break index+=1 for i in range(len(lines)): if index==5 and len(lines[i])==7: data.append(str(lines[i][index].capitalize())+'-'\ +str(lines[i][index+1])) elif index==5 and len(lines[i])!=7: tmp=str(lines[i][index]) if tmp[len(tmp)-1].isdigit(): tmp1=tmp[0]+tmp[1] tmp1=tmp1.capitalize() tmp2='' for j in range(len(tmp)): if j == 0 or j == 1: continue tmp2+=tmp[j] data.append(tmp1+'-'+tmp2) elif tmp=='PROT': data.append('H-1') elif tmp==('NEUT'or'NEUTR'or'nn'or'N 1'or'N-1'): data.append('N-1') else: data.append(tmp) elif index==0: data.append(int(lines[i][index])) else: data.append(float(lines[i][index])) return array(data)
[ "def", "getColData", "(", "self", ",", "attri", ",", "fname", ",", "numtype", "=", "'cycNum'", ")", ":", "fname", "=", "self", ".", "findFile", "(", "fname", ",", "numtype", ")", "f", "=", "open", "(", "fname", ",", "'r'", ")", "for", "i", "in", ...
In this method a column of data for the associated column attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum".
[ "In", "this", "method", "a", "column", "of", "data", "for", "the", "associated", "column", "attribute", "is", "returned", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L545-L607
train
41,758
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector.getElement
def getElement(self, attri, fname, numtype='cycNum'): ''' In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete list of them can be obtained by calling >>> get('element_name') fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". Returns ------- array A numpy array of the four element attributes, number, Z, A and abundance, in that order. Notes ----- Warning ''' element=[] #Variable for holding the list of element names number=[] #Variable for holding the array of numbers z=[] #Variable for holding the array of z a=[] #Variable for holding the array of a abd=[] #Variable for holding the array of Abundance data=[] #variable for the final list of data fname=self.findFile(fname,numtype) f=open(fname,'r') for i in range(self.index+1): f.readline() lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() lines[i]=lines[i].split() index=0 data=[] while index < len (self.dcols): if attri== self.dcols[index]: break index+=1 element=self.get(self.dcols[5],fname,numtype) number=[] z=[] a=[] isom=[] abd=[] for i in range(len(lines)): number.append(int(lines[i][0])) z.append(float(lines[i][1])) isom.append(float(lines[i][2])) abd.append(float(lines[i][1])) index=0 #Variable for determing the index in the data columns while index < len(element): if attri == element[index]: break index+=1 data.append(number[index]) data.append(z[index]) data.append(a[index]) data.append(isom[index]) data.append(abd[index]) return array(data)
python
def getElement(self, attri, fname, numtype='cycNum'): ''' In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete list of them can be obtained by calling >>> get('element_name') fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". Returns ------- array A numpy array of the four element attributes, number, Z, A and abundance, in that order. Notes ----- Warning ''' element=[] #Variable for holding the list of element names number=[] #Variable for holding the array of numbers z=[] #Variable for holding the array of z a=[] #Variable for holding the array of a abd=[] #Variable for holding the array of Abundance data=[] #variable for the final list of data fname=self.findFile(fname,numtype) f=open(fname,'r') for i in range(self.index+1): f.readline() lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() lines[i]=lines[i].split() index=0 data=[] while index < len (self.dcols): if attri== self.dcols[index]: break index+=1 element=self.get(self.dcols[5],fname,numtype) number=[] z=[] a=[] isom=[] abd=[] for i in range(len(lines)): number.append(int(lines[i][0])) z.append(float(lines[i][1])) isom.append(float(lines[i][2])) abd.append(float(lines[i][1])) index=0 #Variable for determing the index in the data columns while index < len(element): if attri == element[index]: break index+=1 data.append(number[index]) data.append(z[index]) data.append(a[index]) data.append(isom[index]) data.append(abd[index]) return array(data)
[ "def", "getElement", "(", "self", ",", "attri", ",", "fname", ",", "numtype", "=", "'cycNum'", ")", ":", "element", "=", "[", "]", "#Variable for holding the list of element names", "number", "=", "[", "]", "#Variable for holding the array of numbers", "z", "=", "...
In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete list of them can be obtained by calling >>> get('element_name') fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". Returns ------- array A numpy array of the four element attributes, number, Z, A and abundance, in that order. Notes ----- Warning
[ "In", "this", "method", "instead", "of", "getting", "a", "particular", "column", "of", "data", "the", "program", "gets", "a", "particular", "row", "of", "data", "for", "a", "particular", "element", "name", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L609-L688
train
41,759
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector._getcycle
def _getcycle(self, cycle, decayed=False): ''' Private method for getting a cycle, called from get.''' yps=self.get('ABUNDANCE_MF', cycle) z=self.get('Z', cycle) #charge a=self.get('A', cycle) #mass isomers=self.get('ISOM', cycle) a_iso_to_plot,z_iso_to_plot,abunds,isotope_to_plot,el_iso_to_plot,isom=\ self._process_abundance_vector(a,z,isomers,yps) self.a_iso_to_plot=a_iso_to_plot self.isotope_to_plot=isotope_to_plot self.z_iso_to_plot=z_iso_to_plot self.el_iso_to_plot=el_iso_to_plot self.abunds=array(abunds) self.isom=isom if decayed: try: self.decay_idp except AttributeError: print("WARNING: decayed in _getcycle ignores isomers " \ "and will decay alpha-unstable p-rich nuclei as if they were beta+ stable.") print("Initialising decay index pointers ....") self.decay_indexpointer() # provides self.decay_idp and ind_tmp=self.idp_to_stables_in_isostoplot isotope_decay=array(isotope_to_plot)[ind_tmp] z_iso_decay=array(z_iso_to_plot)[ind_tmp] a_iso_decay=array(a_iso_to_plot)[ind_tmp] el_iso_decay=array(el_iso_to_plot)[ind_tmp] abunds_decay=zeros(len(ind_tmp), dtype='float64') for i in range(len(isotope_to_plot)): idp=where(isotope_decay==isotope_to_plot[self.decay_idp[i]])[0] # points from # i on isotope_to_plot scale to decay target_on_decayed array scale abunds_decay[idp] += abunds[i] if self.debug: print("Decayed array:") for i in range(len(ind_tmp)): print(isotope_decay[i], z_iso_decay[i], a_iso_decay[i], el_iso_decay[i], abunds_decay[i]) self.a_iso_to_plot=a_iso_decay self.isotope_to_plot=isotope_decay self.z_iso_to_plot=z_iso_decay self.el_iso_to_plot=el_iso_decay self.abunds=abunds_decay
python
def _getcycle(self, cycle, decayed=False): ''' Private method for getting a cycle, called from get.''' yps=self.get('ABUNDANCE_MF', cycle) z=self.get('Z', cycle) #charge a=self.get('A', cycle) #mass isomers=self.get('ISOM', cycle) a_iso_to_plot,z_iso_to_plot,abunds,isotope_to_plot,el_iso_to_plot,isom=\ self._process_abundance_vector(a,z,isomers,yps) self.a_iso_to_plot=a_iso_to_plot self.isotope_to_plot=isotope_to_plot self.z_iso_to_plot=z_iso_to_plot self.el_iso_to_plot=el_iso_to_plot self.abunds=array(abunds) self.isom=isom if decayed: try: self.decay_idp except AttributeError: print("WARNING: decayed in _getcycle ignores isomers " \ "and will decay alpha-unstable p-rich nuclei as if they were beta+ stable.") print("Initialising decay index pointers ....") self.decay_indexpointer() # provides self.decay_idp and ind_tmp=self.idp_to_stables_in_isostoplot isotope_decay=array(isotope_to_plot)[ind_tmp] z_iso_decay=array(z_iso_to_plot)[ind_tmp] a_iso_decay=array(a_iso_to_plot)[ind_tmp] el_iso_decay=array(el_iso_to_plot)[ind_tmp] abunds_decay=zeros(len(ind_tmp), dtype='float64') for i in range(len(isotope_to_plot)): idp=where(isotope_decay==isotope_to_plot[self.decay_idp[i]])[0] # points from # i on isotope_to_plot scale to decay target_on_decayed array scale abunds_decay[idp] += abunds[i] if self.debug: print("Decayed array:") for i in range(len(ind_tmp)): print(isotope_decay[i], z_iso_decay[i], a_iso_decay[i], el_iso_decay[i], abunds_decay[i]) self.a_iso_to_plot=a_iso_decay self.isotope_to_plot=isotope_decay self.z_iso_to_plot=z_iso_decay self.el_iso_to_plot=el_iso_decay self.abunds=abunds_decay
[ "def", "_getcycle", "(", "self", ",", "cycle", ",", "decayed", "=", "False", ")", ":", "yps", "=", "self", ".", "get", "(", "'ABUNDANCE_MF'", ",", "cycle", ")", "z", "=", "self", ".", "get", "(", "'Z'", ",", "cycle", ")", "#charge", "a", "=", "se...
Private method for getting a cycle, called from get.
[ "Private", "method", "for", "getting", "a", "cycle", "called", "from", "get", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L765-L810
train
41,760
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector._getattr
def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>": isList=True else: isList=False data=[] if fname==None: fname=self.files numtype='file' isList=True if isList: for i in range(len(fname)): if attri in self.cattrs: data.append(self.getCycleData(attri,fname[i],numtype)) elif attri in self.dcols: data.append(self.getColData(attri,fname[i],numtype)) elif attri in self.get('ISOTP',fname,numtype): data.append(self.getElement(attri,fname[i],numtype)) else: print('Attribute '+attri+ ' does not exist') print('Returning none') return None else: if attri in self.cattrs: return self.getCycleData(attri,fname,numtype) elif attri in self.dcols: return self.getColData(attri,fname,numtype) elif attri in self.get('ISOTP',fname,numtype): return self.getElement(attri,fname,numtype) else: print('Attribute '+attri+ ' does not exist') print('Returning none') return None return data
python
def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>": isList=True else: isList=False data=[] if fname==None: fname=self.files numtype='file' isList=True if isList: for i in range(len(fname)): if attri in self.cattrs: data.append(self.getCycleData(attri,fname[i],numtype)) elif attri in self.dcols: data.append(self.getColData(attri,fname[i],numtype)) elif attri in self.get('ISOTP',fname,numtype): data.append(self.getElement(attri,fname[i],numtype)) else: print('Attribute '+attri+ ' does not exist') print('Returning none') return None else: if attri in self.cattrs: return self.getCycleData(attri,fname,numtype) elif attri in self.dcols: return self.getColData(attri,fname,numtype) elif attri in self.get('ISOTP',fname,numtype): return self.getElement(attri,fname,numtype) else: print('Attribute '+attri+ ' does not exist') print('Returning none') return None return data
[ "def", "_getattr", "(", "self", ",", "attri", ",", "fname", "=", "None", ",", "numtype", "=", "'cycNum'", ")", ":", "if", "str", "(", "fname", ".", "__class__", ")", "==", "\"<type 'list'>\"", ":", "isList", "=", "True", "else", ":", "isList", "=", "...
Private method for getting an attribute, called from get.
[ "Private", "method", "for", "getting", "an", "attribute", "called", "from", "get", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L813-L850
train
41,761
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector._readPPN
def _readPPN(self, fname, sldir): ''' Private method that reads in and organizes the .ppn file Loads the data of the .ppn file into the variable cols. ''' if sldir.endswith(os.sep): #Making sure fname will be formatted correctly fname = str(sldir)+str(fname) else: fname = str(sldir)+os.sep+str(fname) self.sldir+=os.sep f=open(fname,'r') lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() cols = ['ISOTP', 'ABUNDANCE_MF'] #These are constant, .ppn files have no header to read from for i in range(len(lines)): if not lines[i].startswith('H'): index = i-1 break return cols, index
python
def _readPPN(self, fname, sldir): ''' Private method that reads in and organizes the .ppn file Loads the data of the .ppn file into the variable cols. ''' if sldir.endswith(os.sep): #Making sure fname will be formatted correctly fname = str(sldir)+str(fname) else: fname = str(sldir)+os.sep+str(fname) self.sldir+=os.sep f=open(fname,'r') lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() cols = ['ISOTP', 'ABUNDANCE_MF'] #These are constant, .ppn files have no header to read from for i in range(len(lines)): if not lines[i].startswith('H'): index = i-1 break return cols, index
[ "def", "_readPPN", "(", "self", ",", "fname", ",", "sldir", ")", ":", "if", "sldir", ".", "endswith", "(", "os", ".", "sep", ")", ":", "#Making sure fname will be formatted correctly", "fname", "=", "str", "(", "sldir", ")", "+", "str", "(", "fname", ")"...
Private method that reads in and organizes the .ppn file Loads the data of the .ppn file into the variable cols.
[ "Private", "method", "that", "reads", "in", "and", "organizes", "the", ".", "ppn", "file", "Loads", "the", "data", "of", "the", ".", "ppn", "file", "into", "the", "variable", "cols", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L853-L876
train
41,762
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector._readFile
def _readFile(self, fname, sldir): ''' private method that reads in and organizes the .DAT file Loads the data of the .DAT File into the variables cattrs and cols. In both these cases they are dictionaries, but in the case of cols, it is a dictionary of numpy array exect for the element , element_name where it is just a list ''' cattrs=[] if sldir.endswith(os.sep): #Making sure fname will be formatted correctly fname = str(sldir)+str(fname) else: fname = str(sldir)+os.sep+str(fname) self.sldir+=os.sep f=open(fname,'r') lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() cols=lines[0].strip('H') cols=cols.strip() cols=cols.split() for i in range(len(lines)): if lines[i].startswith('#'): # if it is a cycle attribute line lines[i]=lines[i].strip('#') tmp=lines[i].split() tmp1=[] for j in range(len(tmp)): if tmp[j] != '=' or '': tmp1.append(tmp[j]) tmp=tmp1 j=0 while j <len(tmp): cattrs.append(tmp[j]) j+=2 elif not lines[i].startswith('H'): index = i-1 break return cattrs,cols, index
python
def _readFile(self, fname, sldir): ''' private method that reads in and organizes the .DAT file Loads the data of the .DAT File into the variables cattrs and cols. In both these cases they are dictionaries, but in the case of cols, it is a dictionary of numpy array exect for the element , element_name where it is just a list ''' cattrs=[] if sldir.endswith(os.sep): #Making sure fname will be formatted correctly fname = str(sldir)+str(fname) else: fname = str(sldir)+os.sep+str(fname) self.sldir+=os.sep f=open(fname,'r') lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() cols=lines[0].strip('H') cols=cols.strip() cols=cols.split() for i in range(len(lines)): if lines[i].startswith('#'): # if it is a cycle attribute line lines[i]=lines[i].strip('#') tmp=lines[i].split() tmp1=[] for j in range(len(tmp)): if tmp[j] != '=' or '': tmp1.append(tmp[j]) tmp=tmp1 j=0 while j <len(tmp): cattrs.append(tmp[j]) j+=2 elif not lines[i].startswith('H'): index = i-1 break return cattrs,cols, index
[ "def", "_readFile", "(", "self", ",", "fname", ",", "sldir", ")", ":", "cattrs", "=", "[", "]", "if", "sldir", ".", "endswith", "(", "os", ".", "sep", ")", ":", "#Making sure fname will be formatted correctly", "fname", "=", "str", "(", "sldir", ")", "+"...
private method that reads in and organizes the .DAT file Loads the data of the .DAT File into the variables cattrs and cols. In both these cases they are dictionaries, but in the case of cols, it is a dictionary of numpy array exect for the element , element_name where it is just a list
[ "private", "method", "that", "reads", "in", "and", "organizes", "the", ".", "DAT", "file", "Loads", "the", "data", "of", "the", ".", "DAT", "File", "into", "the", "variables", "cattrs", "and", "cols", ".", "In", "both", "these", "cases", "they", "are", ...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L879-L926
train
41,763
NuGrid/NuGridPy
nugridpy/ppn.py
abu_vector.findFile
def findFile(self, fname, numtype): """ Function that finds the associated file for fname when Fname is time or NDump. Parameters ---------- fname : string The name of the file we are looking for. numType : string Designates how this function acts and how it interprets fname. If numType is 'file', this function will get the desired attribute from that file. If numType is 'cycNum', this function will get the desired attribute from that file with fname's model number. """ numType=numtype.upper() if numType == 'FILE': #do nothing return fname elif numType == 'CYCNUM': try: fname = int(fname) except ValueError: print('Improper choice:'+ str(fname)) print('Reselecting as 0') fname = 0 print('Using '+self.files[fname]) try: return self.files[self.indexp_cyc2filels[fname]] except IndexError: mods = array(self.get('mod'), dtype=int) if fname not in mods: print('You seem to try to plot a cycle that is not present: '+str(fname)) fname = mods[-1] print('I will assume you want to plot the last cycle in the run: '+str(fname)) print('[I am not 100% sure this escape is debugged. You better do this again with') print('the correct input.]') return self.files[fname]
python
def findFile(self, fname, numtype): """ Function that finds the associated file for fname when Fname is time or NDump. Parameters ---------- fname : string The name of the file we are looking for. numType : string Designates how this function acts and how it interprets fname. If numType is 'file', this function will get the desired attribute from that file. If numType is 'cycNum', this function will get the desired attribute from that file with fname's model number. """ numType=numtype.upper() if numType == 'FILE': #do nothing return fname elif numType == 'CYCNUM': try: fname = int(fname) except ValueError: print('Improper choice:'+ str(fname)) print('Reselecting as 0') fname = 0 print('Using '+self.files[fname]) try: return self.files[self.indexp_cyc2filels[fname]] except IndexError: mods = array(self.get('mod'), dtype=int) if fname not in mods: print('You seem to try to plot a cycle that is not present: '+str(fname)) fname = mods[-1] print('I will assume you want to plot the last cycle in the run: '+str(fname)) print('[I am not 100% sure this escape is debugged. You better do this again with') print('the correct input.]') return self.files[fname]
[ "def", "findFile", "(", "self", ",", "fname", ",", "numtype", ")", ":", "numType", "=", "numtype", ".", "upper", "(", ")", "if", "numType", "==", "'FILE'", ":", "#do nothing", "return", "fname", "elif", "numType", "==", "'CYCNUM'", ":", "try", ":", "fn...
Function that finds the associated file for fname when Fname is time or NDump. Parameters ---------- fname : string The name of the file we are looking for. numType : string Designates how this function acts and how it interprets fname. If numType is 'file', this function will get the desired attribute from that file. If numType is 'cycNum', this function will get the desired attribute from that file with fname's model number.
[ "Function", "that", "finds", "the", "associated", "file", "for", "fname", "when", "Fname", "is", "time", "or", "NDump", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L928-L967
train
41,764
openstack/proliantutils
proliantutils/redfish/resources/update_service.py
HPEUpdateService._get_firmware_update_element
def _get_firmware_update_element(self): """Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url """ fw_update_action = self._actions.update_firmware if not fw_update_action: raise (sushy.exceptions. MissingActionError(action='#UpdateService.SimpleUpdate', resource=self._path)) return fw_update_action
python
def _get_firmware_update_element(self): """Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url """ fw_update_action = self._actions.update_firmware if not fw_update_action: raise (sushy.exceptions. MissingActionError(action='#UpdateService.SimpleUpdate', resource=self._path)) return fw_update_action
[ "def", "_get_firmware_update_element", "(", "self", ")", ":", "fw_update_action", "=", "self", ".", "_actions", ".", "update_firmware", "if", "not", "fw_update_action", ":", "raise", "(", "sushy", ".", "exceptions", ".", "MissingActionError", "(", "action", "=", ...
Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url
[ "Get", "the", "url", "for", "firmware", "update" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/update_service.py#L45-L56
train
41,765
openstack/proliantutils
proliantutils/redfish/resources/update_service.py
HPEUpdateService.flash_firmware
def flash_firmware(self, redfish_inst, file_url): """Perform firmware flashing on a redfish system :param file_url: url to firmware bits. :param redfish_inst: redfish instance :raises: IloError, on an error from iLO. """ action_data = { 'ImageURI': file_url, } target_uri = self._get_firmware_update_element().target_uri try: self._conn.post(target_uri, data=action_data) except sushy.exceptions.SushyError as e: msg = (('The Redfish controller failed to update firmware ' 'with file %(file)s Error %(error)s') % {'file': file_url, 'error': str(e)}) LOG.debug(msg) # noqa raise exception.IloError(msg) self.wait_for_redfish_firmware_update_to_complete(redfish_inst) try: state, percent = self.get_firmware_update_progress() except sushy.exceptions.SushyError as e: msg = ('Failed to get firmware progress update ' 'Error %(error)s' % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) if state == "Error": msg = 'Unable to update firmware' LOG.debug(msg) # noqa raise exception.IloError(msg) elif state == "Unknown": msg = 'Status of firmware update not known' LOG.debug(msg) # noqa else: # "Complete" | "Idle" LOG.info('Flashing firmware file: %s ... done', file_url)
python
def flash_firmware(self, redfish_inst, file_url): """Perform firmware flashing on a redfish system :param file_url: url to firmware bits. :param redfish_inst: redfish instance :raises: IloError, on an error from iLO. """ action_data = { 'ImageURI': file_url, } target_uri = self._get_firmware_update_element().target_uri try: self._conn.post(target_uri, data=action_data) except sushy.exceptions.SushyError as e: msg = (('The Redfish controller failed to update firmware ' 'with file %(file)s Error %(error)s') % {'file': file_url, 'error': str(e)}) LOG.debug(msg) # noqa raise exception.IloError(msg) self.wait_for_redfish_firmware_update_to_complete(redfish_inst) try: state, percent = self.get_firmware_update_progress() except sushy.exceptions.SushyError as e: msg = ('Failed to get firmware progress update ' 'Error %(error)s' % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) if state == "Error": msg = 'Unable to update firmware' LOG.debug(msg) # noqa raise exception.IloError(msg) elif state == "Unknown": msg = 'Status of firmware update not known' LOG.debug(msg) # noqa else: # "Complete" | "Idle" LOG.info('Flashing firmware file: %s ... done', file_url)
[ "def", "flash_firmware", "(", "self", ",", "redfish_inst", ",", "file_url", ")", ":", "action_data", "=", "{", "'ImageURI'", ":", "file_url", ",", "}", "target_uri", "=", "self", ".", "_get_firmware_update_element", "(", ")", ".", "target_uri", "try", ":", "...
Perform firmware flashing on a redfish system :param file_url: url to firmware bits. :param redfish_inst: redfish instance :raises: IloError, on an error from iLO.
[ "Perform", "firmware", "flashing", "on", "a", "redfish", "system" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/update_service.py#L58-L95
train
41,766
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSSettings.pending_settings
def pending_settings(self): """Property to provide reference to bios_pending_settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSPendingSettings( self._conn, utils.get_subresource_path_by( self, ["@Redfish.Settings", "SettingsObject"]), redfish_version=self.redfish_version)
python
def pending_settings(self): """Property to provide reference to bios_pending_settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSPendingSettings( self._conn, utils.get_subresource_path_by( self, ["@Redfish.Settings", "SettingsObject"]), redfish_version=self.redfish_version)
[ "def", "pending_settings", "(", "self", ")", ":", "return", "BIOSPendingSettings", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "[", "\"@Redfish.Settings\"", ",", "\"SettingsObject\"", "]", ")", ",", "redfish_version",...
Property to provide reference to bios_pending_settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
[ "Property", "to", "provide", "reference", "to", "bios_pending_settings", "instance" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L52-L61
train
41,767
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSSettings.boot_settings
def boot_settings(self): """Property to provide reference to bios boot instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSBootSettings( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "Boot"]), redfish_version=self.redfish_version)
python
def boot_settings(self): """Property to provide reference to bios boot instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSBootSettings( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "Boot"]), redfish_version=self.redfish_version)
[ "def", "boot_settings", "(", "self", ")", ":", "return", "BIOSBootSettings", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "[", "\"Oem\"", ",", "\"Hpe\"", ",", "\"Links\"", ",", "\"Boot\"", "]", ")", ",", "redfi...
Property to provide reference to bios boot instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
[ "Property", "to", "provide", "reference", "to", "bios", "boot", "instance" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L73-L82
train
41,768
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSSettings.iscsi_resource
def iscsi_resource(self): """Property to provide reference to bios iscsi resource instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return iscsi.ISCSIResource( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "iScsi"]), redfish_version=self.redfish_version)
python
def iscsi_resource(self): """Property to provide reference to bios iscsi resource instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return iscsi.ISCSIResource( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "iScsi"]), redfish_version=self.redfish_version)
[ "def", "iscsi_resource", "(", "self", ")", ":", "return", "iscsi", ".", "ISCSIResource", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "[", "\"Oem\"", ",", "\"Hpe\"", ",", "\"Links\"", ",", "\"iScsi\"", "]", ")"...
Property to provide reference to bios iscsi resource instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
[ "Property", "to", "provide", "reference", "to", "bios", "iscsi", "resource", "instance" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L86-L95
train
41,769
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSSettings.bios_mappings
def bios_mappings(self): """Property to provide reference to bios mappings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSMappings( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "Mappings"]), redfish_version=self.redfish_version)
python
def bios_mappings(self): """Property to provide reference to bios mappings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return BIOSMappings( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "Mappings"]), redfish_version=self.redfish_version)
[ "def", "bios_mappings", "(", "self", ")", ":", "return", "BIOSMappings", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "[", "\"Oem\"", ",", "\"Hpe\"", ",", "\"Links\"", ",", "\"Mappings\"", "]", ")", ",", "redfi...
Property to provide reference to bios mappings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
[ "Property", "to", "provide", "reference", "to", "bios", "mappings", "instance" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L99-L108
train
41,770
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSSettings._get_base_configs
def _get_base_configs(self): """Method that returns object of bios base configs.""" return BIOSBaseConfigs( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "BaseConfigs"]), redfish_version=self.redfish_version)
python
def _get_base_configs(self): """Method that returns object of bios base configs.""" return BIOSBaseConfigs( self._conn, utils.get_subresource_path_by( self, ["Oem", "Hpe", "Links", "BaseConfigs"]), redfish_version=self.redfish_version)
[ "def", "_get_base_configs", "(", "self", ")", ":", "return", "BIOSBaseConfigs", "(", "self", ".", "_conn", ",", "utils", ".", "get_subresource_path_by", "(", "self", ",", "[", "\"Oem\"", ",", "\"Hpe\"", ",", "\"Links\"", ",", "\"BaseConfigs\"", "]", ")", ","...
Method that returns object of bios base configs.
[ "Method", "that", "returns", "object", "of", "bios", "base", "configs", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L111-L116
train
41,771
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSPendingSettings.update_bios_data_by_post
def update_bios_data_by_post(self, data): """Update bios data by post :param data: default bios config data """ bios_settings_data = { 'Attributes': data } self._conn.post(self.path, data=bios_settings_data)
python
def update_bios_data_by_post(self, data): """Update bios data by post :param data: default bios config data """ bios_settings_data = { 'Attributes': data } self._conn.post(self.path, data=bios_settings_data)
[ "def", "update_bios_data_by_post", "(", "self", ",", "data", ")", ":", "bios_settings_data", "=", "{", "'Attributes'", ":", "data", "}", "self", ".", "_conn", ".", "post", "(", "self", ".", "path", ",", "data", "=", "bios_settings_data", ")" ]
Update bios data by post :param data: default bios config data
[ "Update", "bios", "data", "by", "post" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L152-L160
train
41,772
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSPendingSettings.update_bios_data_by_patch
def update_bios_data_by_patch(self, data): """Update bios data by patch :param data: default bios config data """ bios_settings_data = { 'Attributes': data } self._conn.patch(self.path, data=bios_settings_data)
python
def update_bios_data_by_patch(self, data): """Update bios data by patch :param data: default bios config data """ bios_settings_data = { 'Attributes': data } self._conn.patch(self.path, data=bios_settings_data)
[ "def", "update_bios_data_by_patch", "(", "self", ",", "data", ")", ":", "bios_settings_data", "=", "{", "'Attributes'", ":", "data", "}", "self", ".", "_conn", ".", "patch", "(", "self", ".", "path", ",", "data", "=", "bios_settings_data", ")" ]
Update bios data by patch :param data: default bios config data
[ "Update", "bios", "data", "by", "patch" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L162-L170
train
41,773
openstack/proliantutils
proliantutils/redfish/resources/system/bios.py
BIOSBootSettings.get_uefi_boot_string
def get_uefi_boot_string(self, mac): """Get uefi iscsi boot string for the host :returns: iscsi boot string for the system :raises: IloError, on an error from iLO. """ boot_sources = self.boot_sources if not boot_sources: msg = ('Boot sources are not found') LOG.debug(msg) raise exception.IloError(msg) for boot_source in boot_sources: if (mac.upper() in boot_source['UEFIDevicePath'] and 'iSCSI' in boot_source['UEFIDevicePath']): return boot_source['StructuredBootString'] else: msg = ('MAC provided "%s" is Invalid' % mac) raise exception.IloInvalidInputError(msg)
python
def get_uefi_boot_string(self, mac): """Get uefi iscsi boot string for the host :returns: iscsi boot string for the system :raises: IloError, on an error from iLO. """ boot_sources = self.boot_sources if not boot_sources: msg = ('Boot sources are not found') LOG.debug(msg) raise exception.IloError(msg) for boot_source in boot_sources: if (mac.upper() in boot_source['UEFIDevicePath'] and 'iSCSI' in boot_source['UEFIDevicePath']): return boot_source['StructuredBootString'] else: msg = ('MAC provided "%s" is Invalid' % mac) raise exception.IloInvalidInputError(msg)
[ "def", "get_uefi_boot_string", "(", "self", ",", "mac", ")", ":", "boot_sources", "=", "self", ".", "boot_sources", "if", "not", "boot_sources", ":", "msg", "=", "(", "'Boot sources are not found'", ")", "LOG", ".", "debug", "(", "msg", ")", "raise", "except...
Get uefi iscsi boot string for the host :returns: iscsi boot string for the system :raises: IloError, on an error from iLO.
[ "Get", "uefi", "iscsi", "boot", "string", "for", "the", "host" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/bios.py#L211-L229
train
41,774
NuGrid/NuGridPy
nugridpy/astronomy.py
Gamma1_gasrad
def Gamma1_gasrad(beta): ''' Gamma1 for a mix of ideal gas and radiation Hansen & Kawaler, page 177, Eqn. 3.110 Parameters ---------- beta : float Gas pressure fraction Pgas/(Pgas+Prad) ''' Gamma3minus1 = (old_div(2.,3.))*(4.-3.*beta)/(8.-7.*beta) Gamma1 = beta + (4.-3.*beta) * Gamma3minus1 return Gamma1
python
def Gamma1_gasrad(beta): ''' Gamma1 for a mix of ideal gas and radiation Hansen & Kawaler, page 177, Eqn. 3.110 Parameters ---------- beta : float Gas pressure fraction Pgas/(Pgas+Prad) ''' Gamma3minus1 = (old_div(2.,3.))*(4.-3.*beta)/(8.-7.*beta) Gamma1 = beta + (4.-3.*beta) * Gamma3minus1 return Gamma1
[ "def", "Gamma1_gasrad", "(", "beta", ")", ":", "Gamma3minus1", "=", "(", "old_div", "(", "2.", ",", "3.", ")", ")", "*", "(", "4.", "-", "3.", "*", "beta", ")", "/", "(", "8.", "-", "7.", "*", "beta", ")", "Gamma1", "=", "beta", "+", "(", "4....
Gamma1 for a mix of ideal gas and radiation Hansen & Kawaler, page 177, Eqn. 3.110 Parameters ---------- beta : float Gas pressure fraction Pgas/(Pgas+Prad)
[ "Gamma1", "for", "a", "mix", "of", "ideal", "gas", "and", "radiation" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L122-L136
train
41,775
NuGrid/NuGridPy
nugridpy/astronomy.py
mimf_ferrario
def mimf_ferrario(mi): ''' Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131.''' mf=-0.00012336*mi**6+0.003160*mi**5-0.02960*mi**4+\ 0.12350*mi**3-0.21550*mi**2+0.19022*mi+0.46575 return mf
python
def mimf_ferrario(mi): ''' Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131.''' mf=-0.00012336*mi**6+0.003160*mi**5-0.02960*mi**4+\ 0.12350*mi**3-0.21550*mi**2+0.19022*mi+0.46575 return mf
[ "def", "mimf_ferrario", "(", "mi", ")", ":", "mf", "=", "-", "0.00012336", "*", "mi", "**", "6", "+", "0.003160", "*", "mi", "**", "5", "-", "0.02960", "*", "mi", "**", "4", "+", "0.12350", "*", "mi", "**", "3", "-", "0.21550", "*", "mi", "**",...
Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131.
[ "Curvature", "MiMf", "from", "Ferrario", "etal", ".", "2005MNRAS", ".", "361", ".", "1131", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L169-L174
train
41,776
NuGrid/NuGridPy
nugridpy/astronomy.py
int_imf_dm
def int_imf_dm(m1,m2,m,imf,bywhat='bymass',integral='normal'): ''' Integrate IMF between m1 and m2. Parameters ---------- m1 : float Min mass m2 : float Max mass m : float Mass array imf : float IMF array bywhat : string, optional 'bymass' integrates the mass that goes into stars of that mass interval; or 'bynumber' which integrates the number of stars in that mass interval. The default is 'bymass'. integrate : string, optional 'normal' uses sc.integrate.trapz; 'cum' returns cumulative trapezoidal integral. The default is 'normal'. ''' ind_m = (m >= min(m1,m2)) & (m <= max(m1,m2)) if integral is 'normal': int_func = sc.integrate.trapz elif integral is 'cum': int_func = sc.integrate.cumtrapz else: print("Error in int_imf_dm: don't know how to integrate") return 0 if bywhat is 'bymass': return int_func(m[ind_m]*imf[ind_m],m[ind_m]) elif bywhat is 'bynumber': return int_func(imf[ind_m],m[ind_m]) else: print("Error in int_imf_dm: don't know by what to integrate") return 0
python
def int_imf_dm(m1,m2,m,imf,bywhat='bymass',integral='normal'): ''' Integrate IMF between m1 and m2. Parameters ---------- m1 : float Min mass m2 : float Max mass m : float Mass array imf : float IMF array bywhat : string, optional 'bymass' integrates the mass that goes into stars of that mass interval; or 'bynumber' which integrates the number of stars in that mass interval. The default is 'bymass'. integrate : string, optional 'normal' uses sc.integrate.trapz; 'cum' returns cumulative trapezoidal integral. The default is 'normal'. ''' ind_m = (m >= min(m1,m2)) & (m <= max(m1,m2)) if integral is 'normal': int_func = sc.integrate.trapz elif integral is 'cum': int_func = sc.integrate.cumtrapz else: print("Error in int_imf_dm: don't know how to integrate") return 0 if bywhat is 'bymass': return int_func(m[ind_m]*imf[ind_m],m[ind_m]) elif bywhat is 'bynumber': return int_func(imf[ind_m],m[ind_m]) else: print("Error in int_imf_dm: don't know by what to integrate") return 0
[ "def", "int_imf_dm", "(", "m1", ",", "m2", ",", "m", ",", "imf", ",", "bywhat", "=", "'bymass'", ",", "integral", "=", "'normal'", ")", ":", "ind_m", "=", "(", "m", ">=", "min", "(", "m1", ",", "m2", ")", ")", "&", "(", "m", "<=", "max", "(",...
Integrate IMF between m1 and m2. Parameters ---------- m1 : float Min mass m2 : float Max mass m : float Mass array imf : float IMF array bywhat : string, optional 'bymass' integrates the mass that goes into stars of that mass interval; or 'bynumber' which integrates the number of stars in that mass interval. The default is 'bymass'. integrate : string, optional 'normal' uses sc.integrate.trapz; 'cum' returns cumulative trapezoidal integral. The default is 'normal'.
[ "Integrate", "IMF", "between", "m1", "and", "m2", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L223-L263
train
41,777
NuGrid/NuGridPy
nugridpy/astronomy.py
am_orb
def am_orb(m1,m2,a,e): ''' orbital angular momentum. e.g Ge etal2010 Parameters ---------- m1, m2 : float Masses of both stars in Msun. A : float Separation in Rsun. e : float Eccentricity ''' a_cm = a * rsun_cm m1_g = m1 * msun_g m2_g = m2 * msun_g J_orb=np.sqrt(grav_const*a_cm*(old_div((m1_g**2*m2_g**2),(m1_g+m2_g))))*(1-e**2) return J_orb
python
def am_orb(m1,m2,a,e): ''' orbital angular momentum. e.g Ge etal2010 Parameters ---------- m1, m2 : float Masses of both stars in Msun. A : float Separation in Rsun. e : float Eccentricity ''' a_cm = a * rsun_cm m1_g = m1 * msun_g m2_g = m2 * msun_g J_orb=np.sqrt(grav_const*a_cm*(old_div((m1_g**2*m2_g**2),(m1_g+m2_g))))*(1-e**2) return J_orb
[ "def", "am_orb", "(", "m1", ",", "m2", ",", "a", ",", "e", ")", ":", "a_cm", "=", "a", "*", "rsun_cm", "m1_g", "=", "m1", "*", "msun_g", "m2_g", "=", "m2", "*", "msun_g", "J_orb", "=", "np", ".", "sqrt", "(", "grav_const", "*", "a_cm", "*", "...
orbital angular momentum. e.g Ge etal2010 Parameters ---------- m1, m2 : float Masses of both stars in Msun. A : float Separation in Rsun. e : float Eccentricity
[ "orbital", "angular", "momentum", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L265-L287
train
41,778
NuGrid/NuGridPy
nugridpy/astronomy.py
period
def period(A,M1,M2): """ calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days. """ A *= rsun_cm print(A) velocity = np.sqrt(grav_const*msun_g*(M1+M2)/A) print(old_div(velocity,1.e5)) p = 2.*np.pi * A / velocity p /= (60*60*24.) return p
python
def period(A,M1,M2): """ calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days. """ A *= rsun_cm print(A) velocity = np.sqrt(grav_const*msun_g*(M1+M2)/A) print(old_div(velocity,1.e5)) p = 2.*np.pi * A / velocity p /= (60*60*24.) return p
[ "def", "period", "(", "A", ",", "M1", ",", "M2", ")", ":", "A", "*=", "rsun_cm", "print", "(", "A", ")", "velocity", "=", "np", ".", "sqrt", "(", "grav_const", "*", "msun_g", "*", "(", "M1", "+", "M2", ")", "/", "A", ")", "print", "(", "old_d...
calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days.
[ "calculate", "binary", "period", "from", "separation", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L333-L359
train
41,779
NuGrid/NuGridPy
nugridpy/astronomy.py
mu
def mu(X,Z,A): ''' mean molecular weight assuming full ionisation. (Kippenhahn & Weigert, Ch 13.1, Eq. 13.6) Parameters ---------- X : float Mass fraction vector. Z : float Charge number vector. A : float Mass number vector. ''' if not isinstance(Z,np.ndarray): Z = np.array(Z) if not isinstance(A,np.ndarray): A = np.array(A) if not isinstance(X,np.ndarray): X = np.array(X) try: mu = old_div(1.,sum(X*(1.+Z)/A)) except TypeError: X=np.array([X]) A=np.array([A]) Z=np.array([Z]) mu = old_div(1.,sum(X*(1.+Z)/A)) return mu
python
def mu(X,Z,A): ''' mean molecular weight assuming full ionisation. (Kippenhahn & Weigert, Ch 13.1, Eq. 13.6) Parameters ---------- X : float Mass fraction vector. Z : float Charge number vector. A : float Mass number vector. ''' if not isinstance(Z,np.ndarray): Z = np.array(Z) if not isinstance(A,np.ndarray): A = np.array(A) if not isinstance(X,np.ndarray): X = np.array(X) try: mu = old_div(1.,sum(X*(1.+Z)/A)) except TypeError: X=np.array([X]) A=np.array([A]) Z=np.array([Z]) mu = old_div(1.,sum(X*(1.+Z)/A)) return mu
[ "def", "mu", "(", "X", ",", "Z", ",", "A", ")", ":", "if", "not", "isinstance", "(", "Z", ",", "np", ".", "ndarray", ")", ":", "Z", "=", "np", ".", "array", "(", "Z", ")", "if", "not", "isinstance", "(", "A", ",", "np", ".", "ndarray", ")",...
mean molecular weight assuming full ionisation. (Kippenhahn & Weigert, Ch 13.1, Eq. 13.6) Parameters ---------- X : float Mass fraction vector. Z : float Charge number vector. A : float Mass number vector.
[ "mean", "molecular", "weight", "assuming", "full", "ionisation", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L442-L474
train
41,780
openstack/proliantutils
proliantutils/hpssa/disk_allocator.py
_get_criteria_matching_disks
def _get_criteria_matching_disks(logical_disk, physical_drives): """Finds the physical drives matching the criteria of logical disk. This method finds the physical drives matching the criteria of the logical disk passed. :param logical_disk: The logical disk dictionary from raid config :param physical_drives: The physical drives to consider. :returns: A list of physical drives which match the criteria """ matching_physical_drives = [] criteria_to_consider = [x for x in FILTER_CRITERIA if x in logical_disk] for physical_drive_object in physical_drives: for criteria in criteria_to_consider: logical_drive_value = logical_disk.get(criteria) physical_drive_value = getattr(physical_drive_object, criteria) if logical_drive_value != physical_drive_value: break else: matching_physical_drives.append(physical_drive_object) return matching_physical_drives
python
def _get_criteria_matching_disks(logical_disk, physical_drives): """Finds the physical drives matching the criteria of logical disk. This method finds the physical drives matching the criteria of the logical disk passed. :param logical_disk: The logical disk dictionary from raid config :param physical_drives: The physical drives to consider. :returns: A list of physical drives which match the criteria """ matching_physical_drives = [] criteria_to_consider = [x for x in FILTER_CRITERIA if x in logical_disk] for physical_drive_object in physical_drives: for criteria in criteria_to_consider: logical_drive_value = logical_disk.get(criteria) physical_drive_value = getattr(physical_drive_object, criteria) if logical_drive_value != physical_drive_value: break else: matching_physical_drives.append(physical_drive_object) return matching_physical_drives
[ "def", "_get_criteria_matching_disks", "(", "logical_disk", ",", "physical_drives", ")", ":", "matching_physical_drives", "=", "[", "]", "criteria_to_consider", "=", "[", "x", "for", "x", "in", "FILTER_CRITERIA", "if", "x", "in", "logical_disk", "]", "for", "physi...
Finds the physical drives matching the criteria of logical disk. This method finds the physical drives matching the criteria of the logical disk passed. :param logical_disk: The logical disk dictionary from raid config :param physical_drives: The physical drives to consider. :returns: A list of physical drives which match the criteria
[ "Finds", "the", "physical", "drives", "matching", "the", "criteria", "of", "logical", "disk", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/disk_allocator.py#L21-L44
train
41,781
openstack/proliantutils
proliantutils/hpssa/disk_allocator.py
allocate_disks
def allocate_disks(logical_disk, server, raid_config): """Allocate physical disks to a logical disk. This method allocated physical disks to a logical disk based on the current state of the server and criteria mentioned in the logical disk. :param logical_disk: a dictionary of a logical disk from the RAID configuration input to the module. :param server: An objects.Server object :param raid_config: The target RAID configuration requested. :raises: PhysicalDisksNotFoundError, if cannot find physical disks for the request. """ size_gb = logical_disk['size_gb'] raid_level = logical_disk['raid_level'] number_of_physical_disks = logical_disk.get( 'number_of_physical_disks', constants.RAID_LEVEL_MIN_DISKS[raid_level]) share_physical_disks = logical_disk.get('share_physical_disks', False) # Try to create a new independent array for this request. for controller in server.controllers: physical_drives = controller.unassigned_physical_drives physical_drives = _get_criteria_matching_disks(logical_disk, physical_drives) if size_gb != "MAX": # If we want to allocate for a logical disk for which size_gb is # mentioned, we take the smallest physical drives which is required # to match the criteria. reverse_sort = False physical_drives = [x for x in physical_drives if x.size_gb >= size_gb] else: # If we want to allocate for a logical disk for which size_gb is # MAX, we take the largest physical drives available. reverse_sort = True if len(physical_drives) >= number_of_physical_disks: selected_drives = sorted(physical_drives, key=lambda x: x.size_gb, reverse=reverse_sort) selected_drive_ids = [x.id for x in selected_drives] logical_disk['controller'] = controller.id physical_disks = selected_drive_ids[:number_of_physical_disks] logical_disk['physical_disks'] = physical_disks return # We didn't find physical disks to create an independent array. # Check if we can get some shared arrays. if share_physical_disks: sharable_disk_wwns = [] for sharable_logical_disk in raid_config['logical_disks']: if (sharable_logical_disk.get('share_physical_disks', False) and 'root_device_hint' in sharable_logical_disk): wwn = sharable_logical_disk['root_device_hint']['wwn'] sharable_disk_wwns.append(wwn) for controller in server.controllers: sharable_arrays = [x for x in controller.raid_arrays if x.logical_drives[0].wwn in sharable_disk_wwns] for array in sharable_arrays: # Check if criterias for the logical disk match the ones with # physical disks in the raid array. criteria_matched_disks = _get_criteria_matching_disks( logical_disk, array.physical_drives) # Check if all disks in the array don't match the criteria if len(criteria_matched_disks) != len(array.physical_drives): continue # Check if raid array can accomodate the logical disk. if array.can_accomodate(logical_disk): logical_disk['controller'] = controller.id logical_disk['array'] = array.id return # We check both options and couldn't get any physical disks. raise exception.PhysicalDisksNotFoundError(size_gb=size_gb, raid_level=raid_level)
python
def allocate_disks(logical_disk, server, raid_config): """Allocate physical disks to a logical disk. This method allocated physical disks to a logical disk based on the current state of the server and criteria mentioned in the logical disk. :param logical_disk: a dictionary of a logical disk from the RAID configuration input to the module. :param server: An objects.Server object :param raid_config: The target RAID configuration requested. :raises: PhysicalDisksNotFoundError, if cannot find physical disks for the request. """ size_gb = logical_disk['size_gb'] raid_level = logical_disk['raid_level'] number_of_physical_disks = logical_disk.get( 'number_of_physical_disks', constants.RAID_LEVEL_MIN_DISKS[raid_level]) share_physical_disks = logical_disk.get('share_physical_disks', False) # Try to create a new independent array for this request. for controller in server.controllers: physical_drives = controller.unassigned_physical_drives physical_drives = _get_criteria_matching_disks(logical_disk, physical_drives) if size_gb != "MAX": # If we want to allocate for a logical disk for which size_gb is # mentioned, we take the smallest physical drives which is required # to match the criteria. reverse_sort = False physical_drives = [x for x in physical_drives if x.size_gb >= size_gb] else: # If we want to allocate for a logical disk for which size_gb is # MAX, we take the largest physical drives available. reverse_sort = True if len(physical_drives) >= number_of_physical_disks: selected_drives = sorted(physical_drives, key=lambda x: x.size_gb, reverse=reverse_sort) selected_drive_ids = [x.id for x in selected_drives] logical_disk['controller'] = controller.id physical_disks = selected_drive_ids[:number_of_physical_disks] logical_disk['physical_disks'] = physical_disks return # We didn't find physical disks to create an independent array. # Check if we can get some shared arrays. if share_physical_disks: sharable_disk_wwns = [] for sharable_logical_disk in raid_config['logical_disks']: if (sharable_logical_disk.get('share_physical_disks', False) and 'root_device_hint' in sharable_logical_disk): wwn = sharable_logical_disk['root_device_hint']['wwn'] sharable_disk_wwns.append(wwn) for controller in server.controllers: sharable_arrays = [x for x in controller.raid_arrays if x.logical_drives[0].wwn in sharable_disk_wwns] for array in sharable_arrays: # Check if criterias for the logical disk match the ones with # physical disks in the raid array. criteria_matched_disks = _get_criteria_matching_disks( logical_disk, array.physical_drives) # Check if all disks in the array don't match the criteria if len(criteria_matched_disks) != len(array.physical_drives): continue # Check if raid array can accomodate the logical disk. if array.can_accomodate(logical_disk): logical_disk['controller'] = controller.id logical_disk['array'] = array.id return # We check both options and couldn't get any physical disks. raise exception.PhysicalDisksNotFoundError(size_gb=size_gb, raid_level=raid_level)
[ "def", "allocate_disks", "(", "logical_disk", ",", "server", ",", "raid_config", ")", ":", "size_gb", "=", "logical_disk", "[", "'size_gb'", "]", "raid_level", "=", "logical_disk", "[", "'raid_level'", "]", "number_of_physical_disks", "=", "logical_disk", ".", "ge...
Allocate physical disks to a logical disk. This method allocated physical disks to a logical disk based on the current state of the server and criteria mentioned in the logical disk. :param logical_disk: a dictionary of a logical disk from the RAID configuration input to the module. :param server: An objects.Server object :param raid_config: The target RAID configuration requested. :raises: PhysicalDisksNotFoundError, if cannot find physical disks for the request.
[ "Allocate", "physical", "disks", "to", "a", "logical", "disk", "." ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/disk_allocator.py#L47-L127
train
41,782
NuGrid/NuGridPy
nugridpy/utils.py
trajectory_SgConst
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01): ''' setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------- Sg : float S_gamma/R, values between 0.1 and 10. reflect conditions in massive stars. The default is 0.1. delta_logt_dex : float Sets interval between time steps in dex of logtimerev. The default is -0.01. ''' # reverse logarithmic time logtimerev=np.arange(5.,-6.,delta_logt_dex) logrho=np.linspace(0,8.5,len(logtimerev)) logT = (old_div(1.,3.))*(logrho + 21.9161 + np.log10(Sg)) #rho_6=10**logrho/(0.1213*1.e6) #T9=rho_6**(1./3.) #logT_T3=np.log10(T9*1.e9) pl.close(3);pl.figure(3);pl.plot(logrho,logT,label='$S/\mathrm{N_Ak}='+str(Sg)+'$') pl.legend(loc=2);pl.xlabel('$\log \\rho$'); pl.ylabel('$\log T$') pl.close(5);pl.figure(5);pl.plot(logtimerev, logrho) pl.xlabel('$\log (t_\mathrm{final}-t)$'); pl.ylabel('$\log \\rho$') pl.xlim(8,-6) pl.close(6);pl.figure(6);pl.plot(logtimerev) pl.ylabel('$\log (t_\mathrm{final}-t)$'); pl.xlabel('cycle') # [t] logtimerev yrs # [rho] cgs # [T] K T9=old_div(10**logT,1.e9) data=[logtimerev,T9,logrho] att.writeTraj(filename='trajectory.input', data=data, ageunit=2, tunit=1, rhounit=1, idNum=1)
python
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01): ''' setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------- Sg : float S_gamma/R, values between 0.1 and 10. reflect conditions in massive stars. The default is 0.1. delta_logt_dex : float Sets interval between time steps in dex of logtimerev. The default is -0.01. ''' # reverse logarithmic time logtimerev=np.arange(5.,-6.,delta_logt_dex) logrho=np.linspace(0,8.5,len(logtimerev)) logT = (old_div(1.,3.))*(logrho + 21.9161 + np.log10(Sg)) #rho_6=10**logrho/(0.1213*1.e6) #T9=rho_6**(1./3.) #logT_T3=np.log10(T9*1.e9) pl.close(3);pl.figure(3);pl.plot(logrho,logT,label='$S/\mathrm{N_Ak}='+str(Sg)+'$') pl.legend(loc=2);pl.xlabel('$\log \\rho$'); pl.ylabel('$\log T$') pl.close(5);pl.figure(5);pl.plot(logtimerev, logrho) pl.xlabel('$\log (t_\mathrm{final}-t)$'); pl.ylabel('$\log \\rho$') pl.xlim(8,-6) pl.close(6);pl.figure(6);pl.plot(logtimerev) pl.ylabel('$\log (t_\mathrm{final}-t)$'); pl.xlabel('cycle') # [t] logtimerev yrs # [rho] cgs # [T] K T9=old_div(10**logT,1.e9) data=[logtimerev,T9,logrho] att.writeTraj(filename='trajectory.input', data=data, ageunit=2, tunit=1, rhounit=1, idNum=1)
[ "def", "trajectory_SgConst", "(", "Sg", "=", "0.1", ",", "delta_logt_dex", "=", "-", "0.01", ")", ":", "# reverse logarithmic time", "logtimerev", "=", "np", ".", "arange", "(", "5.", ",", "-", "6.", ",", "delta_logt_dex", ")", "logrho", "=", "np", ".", ...
setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------- Sg : float S_gamma/R, values between 0.1 and 10. reflect conditions in massive stars. The default is 0.1. delta_logt_dex : float Sets interval between time steps in dex of logtimerev. The default is -0.01.
[ "setup", "trajectories", "for", "constant", "radiation", "entropy", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L827-L872
train
41,783
NuGrid/NuGridPy
nugridpy/utils.py
species_list
def species_list(what_list): ''' provide default lists of elements to plot. what_list : string String name of species lists provided. If what_list is "CNONe", then C, N, O and some other light elements. If what_list is "s-process", then s-process indicators. ''' if what_list is "CNONe": list_to_print = ['H-1','He-4','C-12','N-14','O-16','Ne-20'] elif what_list is "sprocess": list_to_print = ['Fe-56','Ge-70','Zn-70','Se-76','Kr-80','Kr-82','Kr-86','Sr-88','Ba-138','Pb-208'] elif what_list is "burn_stages": list_to_print = ['H-1','He-4','C-12','O-16','Ne-20','Si-28'] elif what_list is "list_marco_1": list_to_print = ['C-12','O-16','Ne-20','Ne-22','Na-23','Fe-54','Fe-56','Zn-70','Ge-70','Se-76','Kr-80','Kr-82','Sr-88','Y-89','Zr-96','Te-124','Xe-130','Xe-134','Ba-138'] return list_to_print
python
def species_list(what_list): ''' provide default lists of elements to plot. what_list : string String name of species lists provided. If what_list is "CNONe", then C, N, O and some other light elements. If what_list is "s-process", then s-process indicators. ''' if what_list is "CNONe": list_to_print = ['H-1','He-4','C-12','N-14','O-16','Ne-20'] elif what_list is "sprocess": list_to_print = ['Fe-56','Ge-70','Zn-70','Se-76','Kr-80','Kr-82','Kr-86','Sr-88','Ba-138','Pb-208'] elif what_list is "burn_stages": list_to_print = ['H-1','He-4','C-12','O-16','Ne-20','Si-28'] elif what_list is "list_marco_1": list_to_print = ['C-12','O-16','Ne-20','Ne-22','Na-23','Fe-54','Fe-56','Zn-70','Ge-70','Se-76','Kr-80','Kr-82','Sr-88','Y-89','Zr-96','Te-124','Xe-130','Xe-134','Ba-138'] return list_to_print
[ "def", "species_list", "(", "what_list", ")", ":", "if", "what_list", "is", "\"CNONe\"", ":", "list_to_print", "=", "[", "'H-1'", ",", "'He-4'", ",", "'C-12'", ",", "'N-14'", ",", "'O-16'", ",", "'Ne-20'", "]", "elif", "what_list", "is", "\"sprocess\"", ":...
provide default lists of elements to plot. what_list : string String name of species lists provided. If what_list is "CNONe", then C, N, O and some other light elements. If what_list is "s-process", then s-process indicators.
[ "provide", "default", "lists", "of", "elements", "to", "plot", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L897-L919
train
41,784
NuGrid/NuGridPy
nugridpy/utils.py
linestyle
def linestyle(i,a=5,b=3): ''' provide one out of 25 unique combinations of style, color and mark use in combination with markevery=a+mod(i,b) to add spaced points, here a would be the base spacing that would depend on the data density, modulated with the number of lines to be plotted (b) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),linestyle(7)[0], markevery=linestyle(7)[1]) (c) 2014 FH ''' lines=['-','--','-.',':'] points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o'] colors=['b','g','r','c','m','k'] ls_string = colors[sc.mod(i,6)]+lines[sc.mod(i,4)]+points[sc.mod(i,18)] mark_i = a+sc.mod(i,b) return ls_string,int(mark_i)
python
def linestyle(i,a=5,b=3): ''' provide one out of 25 unique combinations of style, color and mark use in combination with markevery=a+mod(i,b) to add spaced points, here a would be the base spacing that would depend on the data density, modulated with the number of lines to be plotted (b) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),linestyle(7)[0], markevery=linestyle(7)[1]) (c) 2014 FH ''' lines=['-','--','-.',':'] points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o'] colors=['b','g','r','c','m','k'] ls_string = colors[sc.mod(i,6)]+lines[sc.mod(i,4)]+points[sc.mod(i,18)] mark_i = a+sc.mod(i,b) return ls_string,int(mark_i)
[ "def", "linestyle", "(", "i", ",", "a", "=", "5", ",", "b", "=", "3", ")", ":", "lines", "=", "[", "'-'", ",", "'--'", ",", "'-.'", ",", "':'", "]", "points", "=", "[", "'v'", ",", "'^'", ",", "'<'", ",", "'>'", ",", "'1'", ",", "'2'", ",...
provide one out of 25 unique combinations of style, color and mark use in combination with markevery=a+mod(i,b) to add spaced points, here a would be the base spacing that would depend on the data density, modulated with the number of lines to be plotted (b) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),linestyle(7)[0], markevery=linestyle(7)[1]) (c) 2014 FH
[ "provide", "one", "out", "of", "25", "unique", "combinations", "of", "style", "color", "and", "mark" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L921-L953
train
41,785
NuGrid/NuGridPy
nugridpy/utils.py
linestylecb
def linestylecb(i,a=5,b=3): ''' version of linestyle function with colourblind colour scheme returns linetyle, marker, color (see example) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),ls=linestyle(7)[0], marker=linestyle(7)[1], \ color=linestyle(7)[2],markevery=linestyle(7)[3]) (c) 2014 FH ''' lines=['-','--','-.',':'] points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o'] colors=['b','g','r','c','m','k'] col=colourblind(i) style=lines[sc.mod(i,4)] point=points[sc.mod(i,18)] mark_i = a+sc.mod(i,b) return style,point,col,mark_i
python
def linestylecb(i,a=5,b=3): ''' version of linestyle function with colourblind colour scheme returns linetyle, marker, color (see example) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),ls=linestyle(7)[0], marker=linestyle(7)[1], \ color=linestyle(7)[2],markevery=linestyle(7)[3]) (c) 2014 FH ''' lines=['-','--','-.',':'] points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o'] colors=['b','g','r','c','m','k'] col=colourblind(i) style=lines[sc.mod(i,4)] point=points[sc.mod(i,18)] mark_i = a+sc.mod(i,b) return style,point,col,mark_i
[ "def", "linestylecb", "(", "i", ",", "a", "=", "5", ",", "b", "=", "3", ")", ":", "lines", "=", "[", "'-'", ",", "'--'", ",", "'-.'", ",", "':'", "]", "points", "=", "[", "'v'", ",", "'^'", ",", "'<'", ",", "'>'", ",", "'1'", ",", "'2'", ...
version of linestyle function with colourblind colour scheme returns linetyle, marker, color (see example) Parameters ---------- i : integer Number of linestyle combination - there are many.... a : integer Spacing of marks. The default is 5. b : integer Modulation in case of plotting many nearby lines. The default is 3. Examples -------- >>> plot(x,sin(x),ls=linestyle(7)[0], marker=linestyle(7)[1], \ color=linestyle(7)[2],markevery=linestyle(7)[3]) (c) 2014 FH
[ "version", "of", "linestyle", "function", "with", "colourblind", "colour", "scheme" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L994-L1027
train
41,786
NuGrid/NuGridPy
nugridpy/utils.py
symbol_list
def symbol_list(what_list): ''' provide default symbol lists Parameters ---------- what_list : string String name of symbol lists provided; "list1", "list2", "lines1" or "lines2". ''' if what_list is "list1": symbol=['ro','bo','ko','go','mo'\ ,'r-','b-','k-','g-','m-','r--','b--','k--'\ ,'g--','r1'] #symbol=['r+','ro','r-'] elif what_list is "list2": symbol=['r-','b--','g-.','k:','md','.','o','v','^','<','>','1','2',\ '3','4','s','p','*','h','H','+'] elif what_list is "lines1": symbol=['b--','k--','r--','c--','m--','g--','b-','k-','r-','c-','m-','g-','b.','b-.','k-.','r-.','c-.','m-.','g-.','b:','k:','r:','c:','m:','g:'] elif what_list is "lines2": symbol=['g:','r-.','k-','b--','k-.','b+','r:','b-','c--','m--','g--','r-','c-','m-','g-','k-.','c-.','m-.','g-.','k:','r:','c:','m:','b-.','b:'] return symbol
python
def symbol_list(what_list): ''' provide default symbol lists Parameters ---------- what_list : string String name of symbol lists provided; "list1", "list2", "lines1" or "lines2". ''' if what_list is "list1": symbol=['ro','bo','ko','go','mo'\ ,'r-','b-','k-','g-','m-','r--','b--','k--'\ ,'g--','r1'] #symbol=['r+','ro','r-'] elif what_list is "list2": symbol=['r-','b--','g-.','k:','md','.','o','v','^','<','>','1','2',\ '3','4','s','p','*','h','H','+'] elif what_list is "lines1": symbol=['b--','k--','r--','c--','m--','g--','b-','k-','r-','c-','m-','g-','b.','b-.','k-.','r-.','c-.','m-.','g-.','b:','k:','r:','c:','m:','g:'] elif what_list is "lines2": symbol=['g:','r-.','k-','b--','k-.','b+','r:','b-','c--','m--','g--','r-','c-','m-','g-','k-.','c-.','m-.','g-.','k:','r:','c:','m:','b-.','b:'] return symbol
[ "def", "symbol_list", "(", "what_list", ")", ":", "if", "what_list", "is", "\"list1\"", ":", "symbol", "=", "[", "'ro'", ",", "'bo'", ",", "'ko'", ",", "'go'", ",", "'mo'", ",", "'r-'", ",", "'b-'", ",", "'k-'", ",", "'g-'", ",", "'m-'", ",", "'r--...
provide default symbol lists Parameters ---------- what_list : string String name of symbol lists provided; "list1", "list2", "lines1" or "lines2".
[ "provide", "default", "symbol", "lists" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1030-L1053
train
41,787
NuGrid/NuGridPy
nugridpy/utils.py
strictly_monotonic
def strictly_monotonic(bb): ''' bb is an index array which may have numerous double or triple occurrences of indices, such as for example the decay_index_pointer. This method removes all entries <= -, then all dublicates and finally returns a sorted list of indices. ''' cc=bb[np.where(bb>=0)] cc.sort() dc=cc[1:]-cc[:-1] # subsequent equal entries have 0 in db dc=np.insert(dc,0,1) # the first element is always unique (the second occurence is the dublicate) dc_mask=np.ma.masked_equal(dc,0) return np.ma.array(cc,mask=dc_mask.mask).compressed()
python
def strictly_monotonic(bb): ''' bb is an index array which may have numerous double or triple occurrences of indices, such as for example the decay_index_pointer. This method removes all entries <= -, then all dublicates and finally returns a sorted list of indices. ''' cc=bb[np.where(bb>=0)] cc.sort() dc=cc[1:]-cc[:-1] # subsequent equal entries have 0 in db dc=np.insert(dc,0,1) # the first element is always unique (the second occurence is the dublicate) dc_mask=np.ma.masked_equal(dc,0) return np.ma.array(cc,mask=dc_mask.mask).compressed()
[ "def", "strictly_monotonic", "(", "bb", ")", ":", "cc", "=", "bb", "[", "np", ".", "where", "(", "bb", ">=", "0", ")", "]", "cc", ".", "sort", "(", ")", "dc", "=", "cc", "[", "1", ":", "]", "-", "cc", "[", ":", "-", "1", "]", "# subsequent ...
bb is an index array which may have numerous double or triple occurrences of indices, such as for example the decay_index_pointer. This method removes all entries <= -, then all dublicates and finally returns a sorted list of indices.
[ "bb", "is", "an", "index", "array", "which", "may", "have", "numerous", "double", "or", "triple", "occurrences", "of", "indices", "such", "as", "for", "example", "the", "decay_index_pointer", ".", "This", "method", "removes", "all", "entries", "<", "=", "-",...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1075-L1088
train
41,788
NuGrid/NuGridPy
nugridpy/utils.py
solar
def solar(filename_solar, solar_factor): ''' read solar abundances from filename_solar. Parameters ---------- filename_solar : string The file name. solar_factor : float The correction factor to apply, in case filename_solar is not solar, but some file used to get initial abundances at metallicity lower than solar. However, notice that this is really rude, since alpha-enahncements and things like that are not properly considered. Only H and He4 are not multiplied. So, for publications PLEASE use proper filename_solar at...solar, and use solar_factor = 1. Marco ''' f0=open(filename_solar) sol=f0.readlines() f0.close sol[0].split(" ") # Now read in the whole file and create a hashed array: global names_sol names_sol=[] global z_sol z_sol=[] yps=np.zeros(len(sol)) mass_number=np.zeros(len(sol)) for i in range(len(sol)): z_sol.append(int(sol[i][1:3])) names_sol.extend([sol[i].split(" ")[0][4:]]) yps[i]=float(sol[i].split(" ")[1]) * solar_factor try: mass_number[i]=int(names_sol[i][2:5]) except ValueError: print("WARNING:") print("This initial abundance file uses an element name that does") print("not contain the mass number in the 3rd to 5th position.") print("It is assumed that this is the proton and we will change") print("the name to 'h 1' to be consistent with the notation used in") print("iniab.dat files") names_sol[i]='h 1' mass_number[i]=int(names_sol[i][2:5]) if mass_number[i] == 1 or mass_number[i] == 4: yps[i] = old_div(yps[i],solar_factor) # convert 'h 1' in prot, not needed any more?? #names_sol[0] = 'prot ' # now zip them together: global solar_abundance solar_abundance={} for a,b in zip(names_sol,yps): solar_abundance[a] = b z_bismuth = 83 global solar_elem_abund solar_elem_abund = np.zeros(z_bismuth) for i in range(z_bismuth): dummy = 0. for j in range(len(solar_abundance)): if z_sol[j] == i+1: dummy = dummy + float(solar_abundance[names_sol[j]]) solar_elem_abund[i] = dummy
python
def solar(filename_solar, solar_factor): ''' read solar abundances from filename_solar. Parameters ---------- filename_solar : string The file name. solar_factor : float The correction factor to apply, in case filename_solar is not solar, but some file used to get initial abundances at metallicity lower than solar. However, notice that this is really rude, since alpha-enahncements and things like that are not properly considered. Only H and He4 are not multiplied. So, for publications PLEASE use proper filename_solar at...solar, and use solar_factor = 1. Marco ''' f0=open(filename_solar) sol=f0.readlines() f0.close sol[0].split(" ") # Now read in the whole file and create a hashed array: global names_sol names_sol=[] global z_sol z_sol=[] yps=np.zeros(len(sol)) mass_number=np.zeros(len(sol)) for i in range(len(sol)): z_sol.append(int(sol[i][1:3])) names_sol.extend([sol[i].split(" ")[0][4:]]) yps[i]=float(sol[i].split(" ")[1]) * solar_factor try: mass_number[i]=int(names_sol[i][2:5]) except ValueError: print("WARNING:") print("This initial abundance file uses an element name that does") print("not contain the mass number in the 3rd to 5th position.") print("It is assumed that this is the proton and we will change") print("the name to 'h 1' to be consistent with the notation used in") print("iniab.dat files") names_sol[i]='h 1' mass_number[i]=int(names_sol[i][2:5]) if mass_number[i] == 1 or mass_number[i] == 4: yps[i] = old_div(yps[i],solar_factor) # convert 'h 1' in prot, not needed any more?? #names_sol[0] = 'prot ' # now zip them together: global solar_abundance solar_abundance={} for a,b in zip(names_sol,yps): solar_abundance[a] = b z_bismuth = 83 global solar_elem_abund solar_elem_abund = np.zeros(z_bismuth) for i in range(z_bismuth): dummy = 0. for j in range(len(solar_abundance)): if z_sol[j] == i+1: dummy = dummy + float(solar_abundance[names_sol[j]]) solar_elem_abund[i] = dummy
[ "def", "solar", "(", "filename_solar", ",", "solar_factor", ")", ":", "f0", "=", "open", "(", "filename_solar", ")", "sol", "=", "f0", ".", "readlines", "(", ")", "f0", ".", "close", "sol", "[", "0", "]", ".", "split", "(", "\" \"", ")", "# N...
read solar abundances from filename_solar. Parameters ---------- filename_solar : string The file name. solar_factor : float The correction factor to apply, in case filename_solar is not solar, but some file used to get initial abundances at metallicity lower than solar. However, notice that this is really rude, since alpha-enahncements and things like that are not properly considered. Only H and He4 are not multiplied. So, for publications PLEASE use proper filename_solar at...solar, and use solar_factor = 1. Marco
[ "read", "solar", "abundances", "from", "filename_solar", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1090-L1160
train
41,789
NuGrid/NuGridPy
nugridpy/utils.py
convert_specie_naming_from_h5_to_ppn
def convert_specie_naming_from_h5_to_ppn(isotope_names): ''' read isotopes names from h5 files, and convert them according to standard scheme used inside ppn and mppnp. Also Z and A are recalculated, for these species. Isomers are excluded for now, since there were recent changes in isomers name. As soon as the isomers names are settled, than Z and A provided here will be obsolete, and can be changed by usual Z and A. ''' spe_rude1 = [] spe_rude2 = [] spe_rude3 = [] for i in range(len(isotope_names)): spe_rude1.append(isotope_names[i].split('-')[0]) spe_rude2.append(isotope_names[i].split('-')[1]) # spe_rude1 is elem name and spe_rude2 is mass number. #print spe_rude1,spe_rude2 k = 0 for i in range(len(spe_rude1)): try: if int(spe_rude2[i]) < 10: spe_rude3.append(str(spe_rude1[i][0:2])+str(' ')+str(spe_rude2[i][0:3])) elif int(spe_rude2[i]) >= 10 and int(spe_rude2[i]) < 100 : spe_rude3.append(str(spe_rude1[i][0:2])+str(' ')+str(spe_rude2[i][0:3])) elif int(spe_rude2[i]) >= 100 : spe_rude3.append(str(spe_rude1[i][0:2])+str(spe_rude2[i][0:3])) except ValueError: k = k+1 None global spe spe = [] global n_array n_array = [] for i in range(len(spe_rude3)): if len(str(spe_rude1[i])) == 1: spe.append(str(spe_rude3[i][0:1])+str(' ')+str(spe_rude3[i][1:4])) else: spe.append(spe_rude3[i]) n_array.append(i) if spe[0]=='Ne 1': spe[0] = 'N 1' # spe_rude is the isotope name, in agreement with what we use in ppn, etc. # need to do this to can use other functions without changing them drastically. # here I skip isomers... global amass_int amass_int=np.zeros(len(spe_rude2)) for i in range(len(spe_rude2)-k): amass_int[i]=int(spe_rude2[i]) #print amass_int # here I have to create an array for the atomic numbers. # I need to this when I calculate and plot element abundances global znum_int znum_int=np.zeros(len(spe)) for i in range(len(spe)): znum_int[i] = Utils.elements_names.index(str(spe[i][0:2]).strip()) # changed by alex # if str(spe[i][0:2]) == 'H ': # znum_int[i] = 1 # elif str(spe[i][0:2]) == 'He': # znum_int[i] = 2 # elif str(spe[i][0:2]) == 'Li': # znum_int[i] = 3 # elif str(spe[i][0:2]) == 'Be': # znum_int[i] = 4 # elif str(spe[i][0:2]) == 'B ': # znum_int[i] = 5 # elif str(spe[i][0:2]) == 'C ': # znum_int[i] = 6 # elif str(spe[i][0:2]) == 'N ': # znum_int[i] = 7 # elif str(spe[i][0:2]) == 'O ': # znum_int[i] = 8 # elif str(spe[i][0:2]) == 'F ': # znum_int[i] = 9 # elif str(spe[i][0:2]) == 'Ne': # znum_int[i] = 10 # elif str(spe[i][0:2]) == 'Na': # znum_int[i] = 11 # elif str(spe[i][0:2]) == 'Mg': # znum_int[i] = 12 # elif str(spe[i][0:2]) == 'Al': # znum_int[i] = 13 # elif str(spe[i][0:2]) == 'Si': # znum_int[i] = 14 # elif str(spe[i][0:2]) == 'P ': # znum_int[i] = 15 # elif str(spe[i][0:2]) == 'S ': # znum_int[i] = 16 # elif str(spe[i][0:2]) == 'Cl': # znum_int[i] = 17 # elif str(spe[i][0:2]) == 'Ar': # znum_int[i] = 18 # elif str(spe[i][0:2]) == 'K ': # znum_int[i] = 19 # elif str(spe[i][0:2]) == 'Ca': # znum_int[i] = 20 # elif str(spe[i][0:2]) == 'Sc': # znum_int[i] = 21 # elif str(spe[i][0:2]) == 'Ti': # znum_int[i] = 22 # elif str(spe[i][0:2]) == 'V ': # znum_int[i] = 23 # elif str(spe[i][0:2]) == 'Cr': # znum_int[i] = 24 # elif str(spe[i][0:2]) == 'Mn': # znum_int[i] = 25 # elif str(spe[i][0:2]) == 'Fe': # znum_int[i] = 26 # elif str(spe[i][0:2]) == 'Co': # znum_int[i] = 27 # elif str(spe[i][0:2]) == 'Ni': # znum_int[i] = 28 # elif str(spe[i][0:2]) == 'Cu': # znum_int[i] = 29 # elif str(spe[i][0:2]) == 'Zn': # znum_int[i] = 30 # elif str(spe[i][0:2]) == 'Ga': # znum_int[i] = 31 # elif str(spe[i][0:2]) == 'Ge': # znum_int[i] = 32 # elif str(spe[i][0:2]) == 'As': # znum_int[i] = 33 # elif str(spe[i][0:2]) == 'Se': # znum_int[i] = 34 # elif str(spe[i][0:2]) == 'Br': # znum_int[i] = 35 # elif str(spe[i][0:2]) == 'Kr': # znum_int[i] = 36 # elif str(spe[i][0:2]) == 'Rb': # znum_int[i] = 37 # elif str(spe[i][0:2]) == 'Sr': # znum_int[i] = 38 # elif str(spe[i][0:2]) == 'Y ': # znum_int[i] = 39 # elif str(spe[i][0:2]) == 'Zr': # znum_int[i] = 40 # elif str(spe[i][0:2]) == 'Nb': # znum_int[i] = 41 # elif str(spe[i][0:2]) == 'Mo': # znum_int[i] = 42 # elif str(spe[i][0:2]) == 'Tc': # znum_int[i] = 43 # elif str(spe[i][0:2]) == 'Ru': # znum_int[i] = 44 # elif str(spe[i][0:2]) == 'Rh': # znum_int[i] = 45 # elif str(spe[i][0:2]) == 'Pd': # znum_int[i] = 46 # elif str(spe[i][0:2]) == 'Ag': # znum_int[i] = 47 # elif str(spe[i][0:2]) == 'Cd': # znum_int[i] = 48 # elif str(spe[i][0:2]) == 'In': # znum_int[i] = 49 # elif str(spe[i][0:2]) == 'Sn': # znum_int[i] = 50 # elif str(spe[i][0:2]) == 'Sb': # znum_int[i] = 51 # elif str(spe[i][0:2]) == 'Te': # znum_int[i] = 52 # elif str(spe[i][0:2]) == 'I ': # znum_int[i] = 53 # elif str(spe[i][0:2]) == 'Xe': # znum_int[i] = 54 # elif str(spe[i][0:2]) == 'Cs': # znum_int[i] = 55 # elif str(spe[i][0:2]) == 'Ba': # znum_int[i] = 56 # elif str(spe[i][0:2]) == 'La': # znum_int[i] = 57 # elif str(spe[i][0:2]) == 'Ce': # znum_int[i] = 58 # elif str(spe[i][0:2]) == 'Pr': # znum_int[i] = 59 # elif str(spe[i][0:2]) == 'Nd': # znum_int[i] = 60 # elif str(spe[i][0:2]) == 'Pm': # znum_int[i] = 61 # elif str(spe[i][0:2]) == 'Sm': # znum_int[i] = 62 # elif str(spe[i][0:2]) == 'Eu': # znum_int[i] = 63 # elif str(spe[i][0:2]) == 'Gd': # znum_int[i] = 64 # elif str(spe[i][0:2]) == 'Tb': # znum_int[i] = 65 # elif str(spe[i][0:2]) == 'Dy': # znum_int[i] = 66 # elif str(spe[i][0:2]) == 'Ho': # znum_int[i] = 67 # elif str(spe[i][0:2]) == 'Er': # znum_int[i] = 68 # elif str(spe[i][0:2]) == 'Tm': # znum_int[i] = 69 # elif str(spe[i][0:2]) == 'Yb': # znum_int[i] = 70 # elif str(spe[i][0:2]) == 'Lu': # znum_int[i] = 71 # elif str(spe[i][0:2]) == 'Hf': # znum_int[i] = 72 # elif str(spe[i][0:2]) == 'Ta': # znum_int[i] = 73 # elif str(spe[i][0:2]) == 'W ': # znum_int[i] = 74 # elif str(spe[i][0:2]) == 'Re': # znum_int[i] = 75 # elif str(spe[i][0:2]) == 'Os': # znum_int[i] = 76 # elif str(spe[i][0:2]) == 'Ir': # znum_int[i] = 77 # elif str(spe[i][0:2]) == 'Pt': # znum_int[i] = 78 # elif str(spe[i][0:2]) == 'Au': # znum_int[i] = 79 # elif str(spe[i][0:2]) == 'Hg': # znum_int[i] = 80 # elif str(spe[i][0:2]) == 'Tl': # znum_int[i] = 81 # elif str(spe[i][0:2]) == 'Pb': # znum_int[i] = 82 # elif str(spe[i][0:2]) == 'Bi': # znum_int[i] = 83 # elif str(spe[i][0:2]) == 'Po': # znum_int[i] = 84 # elif str(spe[i][0:2]) == 'At': # znum_int[i] = 85 # elif str(spe[i][0:2]) == 'Rn': # znum_int[i] = 86 # elif str(spe[i][0:2]) == 'Fr': # znum_int[i] = 87 # elif str(spe[i][0:2]) == 'Ra': # znum_int[i] = 88 # elif str(spe[i][0:2]) == 'Ac': # znum_int[i] = 89 # elif str(spe[i][0:2]) == 'Th': # znum_int[i] = 90 # elif str(spe[i][0:2]) == 'Pa': # znum_int[i] = 91 # elif str(spe[i][0:2]) == 'U ': # znum_int[i] = 92 # elif str(spe[i][0:2]) == 'Np': # znum_int[i] = 93 # elif str(spe[i][0:2]) == 'Pu': # znum_int[i] = 94 # elif str(spe[i][0:2]) == 'Am': # znum_int[i] = 95 # elif str(spe[i][0:2]) == 'Cm': # znum_int[i] = 96 # elif str(spe[i][0:2]) == 'Bk': # znum_int[i] = 97 # elif str(spe[i][0:2]) == 'Cf': # znum_int[i] = 98 if spe[0] == 'N 1': znum_int[0] = 0 # here the index to connect name and atomic numbers. global index_atomic_number index_atomic_number = {} for a,b in zip(spe,znum_int): index_atomic_number[a]=b
python
def convert_specie_naming_from_h5_to_ppn(isotope_names): ''' read isotopes names from h5 files, and convert them according to standard scheme used inside ppn and mppnp. Also Z and A are recalculated, for these species. Isomers are excluded for now, since there were recent changes in isomers name. As soon as the isomers names are settled, than Z and A provided here will be obsolete, and can be changed by usual Z and A. ''' spe_rude1 = [] spe_rude2 = [] spe_rude3 = [] for i in range(len(isotope_names)): spe_rude1.append(isotope_names[i].split('-')[0]) spe_rude2.append(isotope_names[i].split('-')[1]) # spe_rude1 is elem name and spe_rude2 is mass number. #print spe_rude1,spe_rude2 k = 0 for i in range(len(spe_rude1)): try: if int(spe_rude2[i]) < 10: spe_rude3.append(str(spe_rude1[i][0:2])+str(' ')+str(spe_rude2[i][0:3])) elif int(spe_rude2[i]) >= 10 and int(spe_rude2[i]) < 100 : spe_rude3.append(str(spe_rude1[i][0:2])+str(' ')+str(spe_rude2[i][0:3])) elif int(spe_rude2[i]) >= 100 : spe_rude3.append(str(spe_rude1[i][0:2])+str(spe_rude2[i][0:3])) except ValueError: k = k+1 None global spe spe = [] global n_array n_array = [] for i in range(len(spe_rude3)): if len(str(spe_rude1[i])) == 1: spe.append(str(spe_rude3[i][0:1])+str(' ')+str(spe_rude3[i][1:4])) else: spe.append(spe_rude3[i]) n_array.append(i) if spe[0]=='Ne 1': spe[0] = 'N 1' # spe_rude is the isotope name, in agreement with what we use in ppn, etc. # need to do this to can use other functions without changing them drastically. # here I skip isomers... global amass_int amass_int=np.zeros(len(spe_rude2)) for i in range(len(spe_rude2)-k): amass_int[i]=int(spe_rude2[i]) #print amass_int # here I have to create an array for the atomic numbers. # I need to this when I calculate and plot element abundances global znum_int znum_int=np.zeros(len(spe)) for i in range(len(spe)): znum_int[i] = Utils.elements_names.index(str(spe[i][0:2]).strip()) # changed by alex # if str(spe[i][0:2]) == 'H ': # znum_int[i] = 1 # elif str(spe[i][0:2]) == 'He': # znum_int[i] = 2 # elif str(spe[i][0:2]) == 'Li': # znum_int[i] = 3 # elif str(spe[i][0:2]) == 'Be': # znum_int[i] = 4 # elif str(spe[i][0:2]) == 'B ': # znum_int[i] = 5 # elif str(spe[i][0:2]) == 'C ': # znum_int[i] = 6 # elif str(spe[i][0:2]) == 'N ': # znum_int[i] = 7 # elif str(spe[i][0:2]) == 'O ': # znum_int[i] = 8 # elif str(spe[i][0:2]) == 'F ': # znum_int[i] = 9 # elif str(spe[i][0:2]) == 'Ne': # znum_int[i] = 10 # elif str(spe[i][0:2]) == 'Na': # znum_int[i] = 11 # elif str(spe[i][0:2]) == 'Mg': # znum_int[i] = 12 # elif str(spe[i][0:2]) == 'Al': # znum_int[i] = 13 # elif str(spe[i][0:2]) == 'Si': # znum_int[i] = 14 # elif str(spe[i][0:2]) == 'P ': # znum_int[i] = 15 # elif str(spe[i][0:2]) == 'S ': # znum_int[i] = 16 # elif str(spe[i][0:2]) == 'Cl': # znum_int[i] = 17 # elif str(spe[i][0:2]) == 'Ar': # znum_int[i] = 18 # elif str(spe[i][0:2]) == 'K ': # znum_int[i] = 19 # elif str(spe[i][0:2]) == 'Ca': # znum_int[i] = 20 # elif str(spe[i][0:2]) == 'Sc': # znum_int[i] = 21 # elif str(spe[i][0:2]) == 'Ti': # znum_int[i] = 22 # elif str(spe[i][0:2]) == 'V ': # znum_int[i] = 23 # elif str(spe[i][0:2]) == 'Cr': # znum_int[i] = 24 # elif str(spe[i][0:2]) == 'Mn': # znum_int[i] = 25 # elif str(spe[i][0:2]) == 'Fe': # znum_int[i] = 26 # elif str(spe[i][0:2]) == 'Co': # znum_int[i] = 27 # elif str(spe[i][0:2]) == 'Ni': # znum_int[i] = 28 # elif str(spe[i][0:2]) == 'Cu': # znum_int[i] = 29 # elif str(spe[i][0:2]) == 'Zn': # znum_int[i] = 30 # elif str(spe[i][0:2]) == 'Ga': # znum_int[i] = 31 # elif str(spe[i][0:2]) == 'Ge': # znum_int[i] = 32 # elif str(spe[i][0:2]) == 'As': # znum_int[i] = 33 # elif str(spe[i][0:2]) == 'Se': # znum_int[i] = 34 # elif str(spe[i][0:2]) == 'Br': # znum_int[i] = 35 # elif str(spe[i][0:2]) == 'Kr': # znum_int[i] = 36 # elif str(spe[i][0:2]) == 'Rb': # znum_int[i] = 37 # elif str(spe[i][0:2]) == 'Sr': # znum_int[i] = 38 # elif str(spe[i][0:2]) == 'Y ': # znum_int[i] = 39 # elif str(spe[i][0:2]) == 'Zr': # znum_int[i] = 40 # elif str(spe[i][0:2]) == 'Nb': # znum_int[i] = 41 # elif str(spe[i][0:2]) == 'Mo': # znum_int[i] = 42 # elif str(spe[i][0:2]) == 'Tc': # znum_int[i] = 43 # elif str(spe[i][0:2]) == 'Ru': # znum_int[i] = 44 # elif str(spe[i][0:2]) == 'Rh': # znum_int[i] = 45 # elif str(spe[i][0:2]) == 'Pd': # znum_int[i] = 46 # elif str(spe[i][0:2]) == 'Ag': # znum_int[i] = 47 # elif str(spe[i][0:2]) == 'Cd': # znum_int[i] = 48 # elif str(spe[i][0:2]) == 'In': # znum_int[i] = 49 # elif str(spe[i][0:2]) == 'Sn': # znum_int[i] = 50 # elif str(spe[i][0:2]) == 'Sb': # znum_int[i] = 51 # elif str(spe[i][0:2]) == 'Te': # znum_int[i] = 52 # elif str(spe[i][0:2]) == 'I ': # znum_int[i] = 53 # elif str(spe[i][0:2]) == 'Xe': # znum_int[i] = 54 # elif str(spe[i][0:2]) == 'Cs': # znum_int[i] = 55 # elif str(spe[i][0:2]) == 'Ba': # znum_int[i] = 56 # elif str(spe[i][0:2]) == 'La': # znum_int[i] = 57 # elif str(spe[i][0:2]) == 'Ce': # znum_int[i] = 58 # elif str(spe[i][0:2]) == 'Pr': # znum_int[i] = 59 # elif str(spe[i][0:2]) == 'Nd': # znum_int[i] = 60 # elif str(spe[i][0:2]) == 'Pm': # znum_int[i] = 61 # elif str(spe[i][0:2]) == 'Sm': # znum_int[i] = 62 # elif str(spe[i][0:2]) == 'Eu': # znum_int[i] = 63 # elif str(spe[i][0:2]) == 'Gd': # znum_int[i] = 64 # elif str(spe[i][0:2]) == 'Tb': # znum_int[i] = 65 # elif str(spe[i][0:2]) == 'Dy': # znum_int[i] = 66 # elif str(spe[i][0:2]) == 'Ho': # znum_int[i] = 67 # elif str(spe[i][0:2]) == 'Er': # znum_int[i] = 68 # elif str(spe[i][0:2]) == 'Tm': # znum_int[i] = 69 # elif str(spe[i][0:2]) == 'Yb': # znum_int[i] = 70 # elif str(spe[i][0:2]) == 'Lu': # znum_int[i] = 71 # elif str(spe[i][0:2]) == 'Hf': # znum_int[i] = 72 # elif str(spe[i][0:2]) == 'Ta': # znum_int[i] = 73 # elif str(spe[i][0:2]) == 'W ': # znum_int[i] = 74 # elif str(spe[i][0:2]) == 'Re': # znum_int[i] = 75 # elif str(spe[i][0:2]) == 'Os': # znum_int[i] = 76 # elif str(spe[i][0:2]) == 'Ir': # znum_int[i] = 77 # elif str(spe[i][0:2]) == 'Pt': # znum_int[i] = 78 # elif str(spe[i][0:2]) == 'Au': # znum_int[i] = 79 # elif str(spe[i][0:2]) == 'Hg': # znum_int[i] = 80 # elif str(spe[i][0:2]) == 'Tl': # znum_int[i] = 81 # elif str(spe[i][0:2]) == 'Pb': # znum_int[i] = 82 # elif str(spe[i][0:2]) == 'Bi': # znum_int[i] = 83 # elif str(spe[i][0:2]) == 'Po': # znum_int[i] = 84 # elif str(spe[i][0:2]) == 'At': # znum_int[i] = 85 # elif str(spe[i][0:2]) == 'Rn': # znum_int[i] = 86 # elif str(spe[i][0:2]) == 'Fr': # znum_int[i] = 87 # elif str(spe[i][0:2]) == 'Ra': # znum_int[i] = 88 # elif str(spe[i][0:2]) == 'Ac': # znum_int[i] = 89 # elif str(spe[i][0:2]) == 'Th': # znum_int[i] = 90 # elif str(spe[i][0:2]) == 'Pa': # znum_int[i] = 91 # elif str(spe[i][0:2]) == 'U ': # znum_int[i] = 92 # elif str(spe[i][0:2]) == 'Np': # znum_int[i] = 93 # elif str(spe[i][0:2]) == 'Pu': # znum_int[i] = 94 # elif str(spe[i][0:2]) == 'Am': # znum_int[i] = 95 # elif str(spe[i][0:2]) == 'Cm': # znum_int[i] = 96 # elif str(spe[i][0:2]) == 'Bk': # znum_int[i] = 97 # elif str(spe[i][0:2]) == 'Cf': # znum_int[i] = 98 if spe[0] == 'N 1': znum_int[0] = 0 # here the index to connect name and atomic numbers. global index_atomic_number index_atomic_number = {} for a,b in zip(spe,znum_int): index_atomic_number[a]=b
[ "def", "convert_specie_naming_from_h5_to_ppn", "(", "isotope_names", ")", ":", "spe_rude1", "=", "[", "]", "spe_rude2", "=", "[", "]", "spe_rude3", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "isotope_names", ")", ")", ":", "spe_rude1", ".",...
read isotopes names from h5 files, and convert them according to standard scheme used inside ppn and mppnp. Also Z and A are recalculated, for these species. Isomers are excluded for now, since there were recent changes in isomers name. As soon as the isomers names are settled, than Z and A provided here will be obsolete, and can be changed by usual Z and A.
[ "read", "isotopes", "names", "from", "h5", "files", "and", "convert", "them", "according", "to", "standard", "scheme", "used", "inside", "ppn", "and", "mppnp", ".", "Also", "Z", "and", "A", "are", "recalculated", "for", "these", "species", ".", "Isomers", ...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1163-L1435
train
41,790
NuGrid/NuGridPy
nugridpy/utils.py
define_zip_index_for_species
def define_zip_index_for_species(names_ppn_world, number_names_ppn_world): ''' This just give back cl, that is the original index as it is read from files from a data file.''' #connect the specie number in the list, with the specie name global cl cl={} for a,b in zip(names_ppn_world,number_names_ppn_world): cl[a] = b
python
def define_zip_index_for_species(names_ppn_world, number_names_ppn_world): ''' This just give back cl, that is the original index as it is read from files from a data file.''' #connect the specie number in the list, with the specie name global cl cl={} for a,b in zip(names_ppn_world,number_names_ppn_world): cl[a] = b
[ "def", "define_zip_index_for_species", "(", "names_ppn_world", ",", "number_names_ppn_world", ")", ":", "#connect the specie number in the list, with the specie name", "global", "cl", "cl", "=", "{", "}", "for", "a", ",", "b", "in", "zip", "(", "names_ppn_world", ",", ...
This just give back cl, that is the original index as it is read from files from a data file.
[ "This", "just", "give", "back", "cl", "that", "is", "the", "original", "index", "as", "it", "is", "read", "from", "files", "from", "a", "data", "file", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1438-L1446
train
41,791
NuGrid/NuGridPy
nugridpy/utils.py
element_abund_marco
def element_abund_marco(i_decay, stable_isotope_list, stable_isotope_identifier, mass_fractions_array_not_decayed, mass_fractions_array_decayed): ''' Given an array of isotopic abundances not decayed and a similar array of isotopic abundances not decayed, here elements abundances, and production factors for elements are calculated ''' # this way is done in a really simple way. May be done better for sure, in a couple of loops. # I keep this, since I have only to copy over old script. Falk will probably redo it. #import numpy as np #from NuGridPy import utils as u global elem_abund elem_abund = np.zeros(z_bismuth) global elem_abund_decayed elem_abund_decayed = np.zeros(z_bismuth) global elem_prod_fac elem_prod_fac = np.zeros(z_bismuth) global elem_prod_fac_decayed elem_prod_fac_decayed = np.zeros(z_bismuth) # notice that elem_abund include all contribution, both from stables and unstables in # that moment. for i in range(z_bismuth): dummy = 0. for j in range(len(spe)): if znum_int[j] == i+1 and stable_isotope_identifier[j] > 0.5: dummy = dummy + float(mass_fractions_array_not_decayed[j]) elem_abund[i] = dummy for i in range(z_bismuth): if index_stable[i] == 1: elem_prod_fac[i] = float(old_div(elem_abund[i],solar_elem_abund[i])) elif index_stable[i] == 0: elem_prod_fac[i] = 0. if i_decay == 2: for i in range(z_bismuth): dummy = 0. for j in range(len(mass_fractions_array_decayed)): if znum_int[cl[stable_isotope_list[j].capitalize()]] == i+1: #print znum_int[cl[stable[j].capitalize()]],cl[stable[j].capitalize()],stable[j] dummy = dummy + float(mass_fractions_array_decayed[j]) elem_abund_decayed[i] = dummy for i in range(z_bismuth): if index_stable[i] == 1: elem_prod_fac_decayed[i] = float(old_div(elem_abund_decayed[i],solar_elem_abund[i])) elif index_stable[i] == 0: elem_prod_fac_decayed[i] = 0.
python
def element_abund_marco(i_decay, stable_isotope_list, stable_isotope_identifier, mass_fractions_array_not_decayed, mass_fractions_array_decayed): ''' Given an array of isotopic abundances not decayed and a similar array of isotopic abundances not decayed, here elements abundances, and production factors for elements are calculated ''' # this way is done in a really simple way. May be done better for sure, in a couple of loops. # I keep this, since I have only to copy over old script. Falk will probably redo it. #import numpy as np #from NuGridPy import utils as u global elem_abund elem_abund = np.zeros(z_bismuth) global elem_abund_decayed elem_abund_decayed = np.zeros(z_bismuth) global elem_prod_fac elem_prod_fac = np.zeros(z_bismuth) global elem_prod_fac_decayed elem_prod_fac_decayed = np.zeros(z_bismuth) # notice that elem_abund include all contribution, both from stables and unstables in # that moment. for i in range(z_bismuth): dummy = 0. for j in range(len(spe)): if znum_int[j] == i+1 and stable_isotope_identifier[j] > 0.5: dummy = dummy + float(mass_fractions_array_not_decayed[j]) elem_abund[i] = dummy for i in range(z_bismuth): if index_stable[i] == 1: elem_prod_fac[i] = float(old_div(elem_abund[i],solar_elem_abund[i])) elif index_stable[i] == 0: elem_prod_fac[i] = 0. if i_decay == 2: for i in range(z_bismuth): dummy = 0. for j in range(len(mass_fractions_array_decayed)): if znum_int[cl[stable_isotope_list[j].capitalize()]] == i+1: #print znum_int[cl[stable[j].capitalize()]],cl[stable[j].capitalize()],stable[j] dummy = dummy + float(mass_fractions_array_decayed[j]) elem_abund_decayed[i] = dummy for i in range(z_bismuth): if index_stable[i] == 1: elem_prod_fac_decayed[i] = float(old_div(elem_abund_decayed[i],solar_elem_abund[i])) elif index_stable[i] == 0: elem_prod_fac_decayed[i] = 0.
[ "def", "element_abund_marco", "(", "i_decay", ",", "stable_isotope_list", ",", "stable_isotope_identifier", ",", "mass_fractions_array_not_decayed", ",", "mass_fractions_array_decayed", ")", ":", "# this way is done in a really simple way. May be done better for sure, in a couple of loop...
Given an array of isotopic abundances not decayed and a similar array of isotopic abundances not decayed, here elements abundances, and production factors for elements are calculated
[ "Given", "an", "array", "of", "isotopic", "abundances", "not", "decayed", "and", "a", "similar", "array", "of", "isotopic", "abundances", "not", "decayed", "here", "elements", "abundances", "and", "production", "factors", "for", "elements", "are", "calculated" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1450-L1509
train
41,792
NuGrid/NuGridPy
nugridpy/utils.py
data_fitting.fit
def fit(self, x, y, dcoef='none'): ''' performs the fit x, y : list Matching data arrays that define a numerical function y(x), this is the data to be fitted. dcoef : list or string You can provide a different guess for the coefficients, or provide the string 'none' to use the inital guess. The default is 'none'. Returns ------- ierr Values between 1 and 4 signal success. Notes ----- self.fcoef, contains the fitted coefficients. ''' self.x = x self.y = y if dcoef is not 'none': coef = dcoef else: coef = self.coef fcoef=optimize.leastsq(self.residual,coef,args=(y,self.func,x)) self.fcoef = fcoef[0].tolist() return fcoef[1]
python
def fit(self, x, y, dcoef='none'): ''' performs the fit x, y : list Matching data arrays that define a numerical function y(x), this is the data to be fitted. dcoef : list or string You can provide a different guess for the coefficients, or provide the string 'none' to use the inital guess. The default is 'none'. Returns ------- ierr Values between 1 and 4 signal success. Notes ----- self.fcoef, contains the fitted coefficients. ''' self.x = x self.y = y if dcoef is not 'none': coef = dcoef else: coef = self.coef fcoef=optimize.leastsq(self.residual,coef,args=(y,self.func,x)) self.fcoef = fcoef[0].tolist() return fcoef[1]
[ "def", "fit", "(", "self", ",", "x", ",", "y", ",", "dcoef", "=", "'none'", ")", ":", "self", ".", "x", "=", "x", "self", ".", "y", "=", "y", "if", "dcoef", "is", "not", "'none'", ":", "coef", "=", "dcoef", "else", ":", "coef", "=", "self", ...
performs the fit x, y : list Matching data arrays that define a numerical function y(x), this is the data to be fitted. dcoef : list or string You can provide a different guess for the coefficients, or provide the string 'none' to use the inital guess. The default is 'none'. Returns ------- ierr Values between 1 and 4 signal success. Notes ----- self.fcoef, contains the fitted coefficients.
[ "performs", "the", "fit" ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L139-L171
train
41,793
NuGrid/NuGridPy
nugridpy/utils.py
data_fitting.plot
def plot(self, ifig=1, data_label='data', fit_label='fit', data_shape='o', fit_shape='-'): ''' plot the data and the fitted function. Parameters ---------- ifig : integer Figure window number. The default is 1. data_label : string Legend for data. The default is 'data'. fit_label : string Legend for fit. If fit_lable is 'fit', then substitute fit function type self.func_name. The default is 'fit'. data_shape : character Shape for data. The default is 'o'. fit_shape : character Shape for fit. The default is '-'. ''' if len(self.coef) is not len(self.fcoef): print("Warning: the fitted coefficient list is not same") print(" length as guessed list - still I will try ...") pl.figure(ifig) pl.plot(self.x,self.y,data_shape,label=data_label) if fit_label is 'fit': fit_label=self.__name__ pl.plot(self.x,self.func(self.fcoef,self.x),fit_shape,label=fit_label) pl.legend()
python
def plot(self, ifig=1, data_label='data', fit_label='fit', data_shape='o', fit_shape='-'): ''' plot the data and the fitted function. Parameters ---------- ifig : integer Figure window number. The default is 1. data_label : string Legend for data. The default is 'data'. fit_label : string Legend for fit. If fit_lable is 'fit', then substitute fit function type self.func_name. The default is 'fit'. data_shape : character Shape for data. The default is 'o'. fit_shape : character Shape for fit. The default is '-'. ''' if len(self.coef) is not len(self.fcoef): print("Warning: the fitted coefficient list is not same") print(" length as guessed list - still I will try ...") pl.figure(ifig) pl.plot(self.x,self.y,data_shape,label=data_label) if fit_label is 'fit': fit_label=self.__name__ pl.plot(self.x,self.func(self.fcoef,self.x),fit_shape,label=fit_label) pl.legend()
[ "def", "plot", "(", "self", ",", "ifig", "=", "1", ",", "data_label", "=", "'data'", ",", "fit_label", "=", "'fit'", ",", "data_shape", "=", "'o'", ",", "fit_shape", "=", "'-'", ")", ":", "if", "len", "(", "self", ".", "coef", ")", "is", "not", "...
plot the data and the fitted function. Parameters ---------- ifig : integer Figure window number. The default is 1. data_label : string Legend for data. The default is 'data'. fit_label : string Legend for fit. If fit_lable is 'fit', then substitute fit function type self.func_name. The default is 'fit'. data_shape : character Shape for data. The default is 'o'. fit_shape : character Shape for fit. The default is '-'.
[ "plot", "the", "data", "and", "the", "fitted", "function", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L173-L203
train
41,794
NuGrid/NuGridPy
nugridpy/utils.py
Utils._read_isotopedatabase
def _read_isotopedatabase(self, ffname='isotopedatabase.txt'): ''' This private method reads the isotopedatabase.txt file in sldir run dictory and returns z, a, elements, the cutoff mass for each species that delineate beta+ and beta- decay and the logical in the last column. Also provides charge_from_element dictionary according to isotopedatabase.txt. ''' name=self.sldir+ffname z_db, a_db, el_db, stable_a_db,logic_db=\ np.loadtxt(name,unpack=True,dtype='str') z_db=np.array(z_db,dtype='int') a_db=np.array(a_db,dtype='int') stable_a_db=np.array(stable_a_db,dtype='int') # charge number for element name from dictionary in isotopedatabase.txt charge_from_element_name={} for name in self.stable_names: if name=='Neutron' or name=='Neut' or name=='NEUT' or name=='N-1': name='nn' try: zz=z_db[np.where(el_db==name)][0] charge_from_element_name[name]=zz except IndexError: print(name+" does not exist in this run") return z_db, a_db, el_db, stable_a_db,logic_db,charge_from_element_name
python
def _read_isotopedatabase(self, ffname='isotopedatabase.txt'): ''' This private method reads the isotopedatabase.txt file in sldir run dictory and returns z, a, elements, the cutoff mass for each species that delineate beta+ and beta- decay and the logical in the last column. Also provides charge_from_element dictionary according to isotopedatabase.txt. ''' name=self.sldir+ffname z_db, a_db, el_db, stable_a_db,logic_db=\ np.loadtxt(name,unpack=True,dtype='str') z_db=np.array(z_db,dtype='int') a_db=np.array(a_db,dtype='int') stable_a_db=np.array(stable_a_db,dtype='int') # charge number for element name from dictionary in isotopedatabase.txt charge_from_element_name={} for name in self.stable_names: if name=='Neutron' or name=='Neut' or name=='NEUT' or name=='N-1': name='nn' try: zz=z_db[np.where(el_db==name)][0] charge_from_element_name[name]=zz except IndexError: print(name+" does not exist in this run") return z_db, a_db, el_db, stable_a_db,logic_db,charge_from_element_name
[ "def", "_read_isotopedatabase", "(", "self", ",", "ffname", "=", "'isotopedatabase.txt'", ")", ":", "name", "=", "self", ".", "sldir", "+", "ffname", "z_db", ",", "a_db", ",", "el_db", ",", "stable_a_db", ",", "logic_db", "=", "np", ".", "loadtxt", "(", ...
This private method reads the isotopedatabase.txt file in sldir run dictory and returns z, a, elements, the cutoff mass for each species that delineate beta+ and beta- decay and the logical in the last column. Also provides charge_from_element dictionary according to isotopedatabase.txt.
[ "This", "private", "method", "reads", "the", "isotopedatabase", ".", "txt", "file", "in", "sldir", "run", "dictory", "and", "returns", "z", "a", "elements", "the", "cutoff", "mass", "for", "each", "species", "that", "delineate", "beta", "+", "and", "beta", ...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L372-L398
train
41,795
NuGrid/NuGridPy
nugridpy/utils.py
Utils.is_stable
def is_stable(self,species): ''' This routine accepts input formatted like 'He-3' and checks with stable_el list if occurs in there. If it does, the routine returns True, otherwise False. Notes ----- this method is designed to work with an se instance from nugridse.py. In order to make it work with ppn.py some additional work is required. FH, April 20, 2013. ''' element_name_of_iso = species.split('-')[0] try: a_of_iso = int(species.split('-')[1]) except ValueError: # if the species name contains in addition to the # mass number some letters, e.g. for isomere, then # we assume it is unstable. This is not correct but # related to the fact that in nugridse.py we do not # identify species properly by the three numbers A, Z # and isomeric_state. We should do that!!!!!! a_of_iso = 999 idp_of_element_in_stable_names = self.stable_names.index(element_name_of_iso) if a_of_iso in self.stable_el[idp_of_element_in_stable_names][1:]: return True else: return False
python
def is_stable(self,species): ''' This routine accepts input formatted like 'He-3' and checks with stable_el list if occurs in there. If it does, the routine returns True, otherwise False. Notes ----- this method is designed to work with an se instance from nugridse.py. In order to make it work with ppn.py some additional work is required. FH, April 20, 2013. ''' element_name_of_iso = species.split('-')[0] try: a_of_iso = int(species.split('-')[1]) except ValueError: # if the species name contains in addition to the # mass number some letters, e.g. for isomere, then # we assume it is unstable. This is not correct but # related to the fact that in nugridse.py we do not # identify species properly by the three numbers A, Z # and isomeric_state. We should do that!!!!!! a_of_iso = 999 idp_of_element_in_stable_names = self.stable_names.index(element_name_of_iso) if a_of_iso in self.stable_el[idp_of_element_in_stable_names][1:]: return True else: return False
[ "def", "is_stable", "(", "self", ",", "species", ")", ":", "element_name_of_iso", "=", "species", ".", "split", "(", "'-'", ")", "[", "0", "]", "try", ":", "a_of_iso", "=", "int", "(", "species", ".", "split", "(", "'-'", ")", "[", "1", "]", ")", ...
This routine accepts input formatted like 'He-3' and checks with stable_el list if occurs in there. If it does, the routine returns True, otherwise False. Notes ----- this method is designed to work with an se instance from nugridse.py. In order to make it work with ppn.py some additional work is required. FH, April 20, 2013.
[ "This", "routine", "accepts", "input", "formatted", "like", "He", "-", "3", "and", "checks", "with", "stable_el", "list", "if", "occurs", "in", "there", ".", "If", "it", "does", "the", "routine", "returns", "True", "otherwise", "False", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L501-L530
train
41,796
NuGrid/NuGridPy
nugridpy/utils.py
iniabu.write_mesa
def write_mesa(self, mesa_isos_file='isos.txt', add_excess_iso='fe56', outfile='xa_iniabu.dat', header_string='initial abundances for a MESA run', header_char='!'): ''' Write initial abundance file, returns written abundances and mesa names. Parameters ---------- mesa_isos_file : string, optional List with isos copied from mesa network definition file in mesa/data/net_data/nets. The default is 'isos.txt'. add_excess_iso : string, optional Add 1.-sum(isos in mesa net) to this isotope. The defualt is 'fe56'. outfile : string, optional name of output file. The default file is 'xa_iniabu.dat'. header_string : string, optional Srting with header line. The default is 'initial abundances for a MESA run'. header_char : character, optional The default is '!'. Examples -------- >>> from NuGridPy import utils >>> !ls ~/PPN/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/ # find ppn initial abundance file >>> !cat ~/mesa/data/net_data/nets/agb.net # find isos needed in mesa net >>> !cat > isos.txt # paste needed isos into file >>> help(utils.iniabu) # check documentation of method >>> x=utils.iniabu('path_to_here/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/iniab2.0E-02GN93.ppn') >>> x.write_mesa? >>> mnames,mabus = x.write_mesa(add_excess_iso='ne22', ... header_string='mppnp/USEEPP/iniab2.0E-02GN93.ppn for mesa/agb.net', ... outfile='xa_2.0E-02GN93.mesa') ''' f=open('isos.txt') a=f.readlines() isos=[] for i in range(len(a)): isos.append(a[i].strip().rstrip(',')) mesa_names=[] abus=[] for i in range(len(self.z)): b=self.names[i].split() a='' a=a.join(b) if a in isos: mesa_names.append(a) abus.append(self.abu[i]) # mesa_names.append(elements_names[int(x.z[i])].lower()+str(int(x.a[i]))) for i in range(len(isos)): if isos[i] not in mesa_names: mesa_names.append(isos[i]) abus.append(0.0) excess=1.-np.sum(np.array(abus)) abus=np.array(abus) abus[mesa_names.index(add_excess_iso)] += excess dcols=['',''] data=[mesa_names,abus] hd=[header_string] att.write(outfile,hd,dcols,data,header_char=header_char) return mesa_names,abus
python
def write_mesa(self, mesa_isos_file='isos.txt', add_excess_iso='fe56', outfile='xa_iniabu.dat', header_string='initial abundances for a MESA run', header_char='!'): ''' Write initial abundance file, returns written abundances and mesa names. Parameters ---------- mesa_isos_file : string, optional List with isos copied from mesa network definition file in mesa/data/net_data/nets. The default is 'isos.txt'. add_excess_iso : string, optional Add 1.-sum(isos in mesa net) to this isotope. The defualt is 'fe56'. outfile : string, optional name of output file. The default file is 'xa_iniabu.dat'. header_string : string, optional Srting with header line. The default is 'initial abundances for a MESA run'. header_char : character, optional The default is '!'. Examples -------- >>> from NuGridPy import utils >>> !ls ~/PPN/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/ # find ppn initial abundance file >>> !cat ~/mesa/data/net_data/nets/agb.net # find isos needed in mesa net >>> !cat > isos.txt # paste needed isos into file >>> help(utils.iniabu) # check documentation of method >>> x=utils.iniabu('path_to_here/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/iniab2.0E-02GN93.ppn') >>> x.write_mesa? >>> mnames,mabus = x.write_mesa(add_excess_iso='ne22', ... header_string='mppnp/USEEPP/iniab2.0E-02GN93.ppn for mesa/agb.net', ... outfile='xa_2.0E-02GN93.mesa') ''' f=open('isos.txt') a=f.readlines() isos=[] for i in range(len(a)): isos.append(a[i].strip().rstrip(',')) mesa_names=[] abus=[] for i in range(len(self.z)): b=self.names[i].split() a='' a=a.join(b) if a in isos: mesa_names.append(a) abus.append(self.abu[i]) # mesa_names.append(elements_names[int(x.z[i])].lower()+str(int(x.a[i]))) for i in range(len(isos)): if isos[i] not in mesa_names: mesa_names.append(isos[i]) abus.append(0.0) excess=1.-np.sum(np.array(abus)) abus=np.array(abus) abus[mesa_names.index(add_excess_iso)] += excess dcols=['',''] data=[mesa_names,abus] hd=[header_string] att.write(outfile,hd,dcols,data,header_char=header_char) return mesa_names,abus
[ "def", "write_mesa", "(", "self", ",", "mesa_isos_file", "=", "'isos.txt'", ",", "add_excess_iso", "=", "'fe56'", ",", "outfile", "=", "'xa_iniabu.dat'", ",", "header_string", "=", "'initial abundances for a MESA run'", ",", "header_char", "=", "'!'", ")", ":", "f...
Write initial abundance file, returns written abundances and mesa names. Parameters ---------- mesa_isos_file : string, optional List with isos copied from mesa network definition file in mesa/data/net_data/nets. The default is 'isos.txt'. add_excess_iso : string, optional Add 1.-sum(isos in mesa net) to this isotope. The defualt is 'fe56'. outfile : string, optional name of output file. The default file is 'xa_iniabu.dat'. header_string : string, optional Srting with header line. The default is 'initial abundances for a MESA run'. header_char : character, optional The default is '!'. Examples -------- >>> from NuGridPy import utils >>> !ls ~/PPN/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/ # find ppn initial abundance file >>> !cat ~/mesa/data/net_data/nets/agb.net # find isos needed in mesa net >>> !cat > isos.txt # paste needed isos into file >>> help(utils.iniabu) # check documentation of method >>> x=utils.iniabu('path_to_here/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/iniab2.0E-02GN93.ppn') >>> x.write_mesa? >>> mnames,mabus = x.write_mesa(add_excess_iso='ne22', ... header_string='mppnp/USEEPP/iniab2.0E-02GN93.ppn for mesa/agb.net', ... outfile='xa_2.0E-02GN93.mesa')
[ "Write", "initial", "abundance", "file", "returns", "written", "abundances", "and", "mesa", "names", "." ]
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L678-L749
train
41,797
NuGrid/NuGridPy
nugridpy/utils.py
iniabu.set_and_normalize
def set_and_normalize(self,species_hash): ''' species_hash is a hash array in which you provide abundances referenced by species names that you want to set to some particular value; all other species are then normalised so that the total sum is 1. Examples -------- You can set up the argument array for this method for example in the following way. >>> sp={} >>> sp['he 4']=0.2 >>> sp['h 1']=0.5 ''' sum_before = sum(self.abu) for i in range(len(species_hash)): sum_before -= self.abu[self.hindex[list(species_hash.keys())[i]]] print("sum_before = "+str(sum_before)) normalization_factor=old_div(1.0-sum(species_hash.values()),sum_before) print("normalizing the rest witih factor "+str(normalization_factor)) self.abu *= normalization_factor for i in range(len(species_hash)): self.abu[self.hindex[list(species_hash.keys())[i]]]=list(species_hash.values())[i] for l in range(len(self.abu)): if self.abu[l] <= 1e-99: #otherwise we might write e-100 which will be read as e-10 by ppn self.abu[l] = 1.0e-99 for name in self.habu: self.habu[name]=self.abu[self.hindex[name]]
python
def set_and_normalize(self,species_hash): ''' species_hash is a hash array in which you provide abundances referenced by species names that you want to set to some particular value; all other species are then normalised so that the total sum is 1. Examples -------- You can set up the argument array for this method for example in the following way. >>> sp={} >>> sp['he 4']=0.2 >>> sp['h 1']=0.5 ''' sum_before = sum(self.abu) for i in range(len(species_hash)): sum_before -= self.abu[self.hindex[list(species_hash.keys())[i]]] print("sum_before = "+str(sum_before)) normalization_factor=old_div(1.0-sum(species_hash.values()),sum_before) print("normalizing the rest witih factor "+str(normalization_factor)) self.abu *= normalization_factor for i in range(len(species_hash)): self.abu[self.hindex[list(species_hash.keys())[i]]]=list(species_hash.values())[i] for l in range(len(self.abu)): if self.abu[l] <= 1e-99: #otherwise we might write e-100 which will be read as e-10 by ppn self.abu[l] = 1.0e-99 for name in self.habu: self.habu[name]=self.abu[self.hindex[name]]
[ "def", "set_and_normalize", "(", "self", ",", "species_hash", ")", ":", "sum_before", "=", "sum", "(", "self", ".", "abu", ")", "for", "i", "in", "range", "(", "len", "(", "species_hash", ")", ")", ":", "sum_before", "-=", "self", ".", "abu", "[", "s...
species_hash is a hash array in which you provide abundances referenced by species names that you want to set to some particular value; all other species are then normalised so that the total sum is 1. Examples -------- You can set up the argument array for this method for example in the following way. >>> sp={} >>> sp['he 4']=0.2 >>> sp['h 1']=0.5
[ "species_hash", "is", "a", "hash", "array", "in", "which", "you", "provide", "abundances", "referenced", "by", "species", "names", "that", "you", "want", "to", "set", "to", "some", "particular", "value", ";", "all", "other", "species", "are", "then", "normal...
eee8047446e398be77362d82c1d8b3310054fab0
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L751-L784
train
41,798
openstack/proliantutils
proliantutils/redfish/resources/system/storage/physical_drive.py
HPEPhysicalDriveCollection.drive_rotational_speed_rpm
def drive_rotational_speed_rpm(self): """Gets the set of rotational speed of the HDD drives""" drv_rot_speed_rpm = set() for member in self.get_members(): if member.rotational_speed_rpm is not None: drv_rot_speed_rpm.add(member.rotational_speed_rpm) return drv_rot_speed_rpm
python
def drive_rotational_speed_rpm(self): """Gets the set of rotational speed of the HDD drives""" drv_rot_speed_rpm = set() for member in self.get_members(): if member.rotational_speed_rpm is not None: drv_rot_speed_rpm.add(member.rotational_speed_rpm) return drv_rot_speed_rpm
[ "def", "drive_rotational_speed_rpm", "(", "self", ")", ":", "drv_rot_speed_rpm", "=", "set", "(", ")", "for", "member", "in", "self", ".", "get_members", "(", ")", ":", "if", "member", ".", "rotational_speed_rpm", "is", "not", "None", ":", "drv_rot_speed_rpm",...
Gets the set of rotational speed of the HDD drives
[ "Gets", "the", "set", "of", "rotational", "speed", "of", "the", "HDD", "drives" ]
86ef3b47b4eca97c221577e3570b0240d6a25f22
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/storage/physical_drive.py#L77-L83
train
41,799