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
has2k1/plotnine
plotnine/stats/smoothers.py
wls_prediction_std
def wls_prediction_std(res, exog=None, weights=None, alpha=0.05, interval='confidence'): """ calculate standard deviation and confidence interval Applies to WLS and OLS, not to general GLS, that is independently but not identically distributed observations Parameters ---------- res : regression result instance results of WLS or OLS regression required attributes see notes exog : array_like (optional) exogenous variables for points to predict weights : scalar or array_like (optional) weights as defined for WLS (inverse of variance of observation) alpha : float (default: alpha = 0.05) confidence level for two-sided hypothesis Returns ------- predstd : array_like, 1d standard error of prediction same length as rows of exog interval_l, interval_u : array_like lower und upper confidence bounds Notes ----- The result instance needs to have at least the following res.model.predict() : predicted values or res.fittedvalues : values used in estimation res.cov_params() : covariance matrix of parameter estimates If exog is 1d, then it is interpreted as one observation, i.e. a row vector. testing status: not compared with other packages References ---------- Greene p.111 for OLS, extended to WLS by analogy """ # work around current bug: # fit doesn't attach results to model, predict broken # res.model.results covb = res.cov_params() if exog is None: exog = res.model.exog predicted = res.fittedvalues if weights is None: weights = res.model.weights else: exog = np.atleast_2d(exog) if covb.shape[1] != exog.shape[1]: raise ValueError('wrong shape of exog') predicted = res.model.predict(res.params, exog) if weights is None: weights = 1. else: weights = np.asarray(weights) if weights.size > 1 and len(weights) != exog.shape[0]: raise ValueError('weights and exog do not have matching shape') # full covariance: # predvar = res3.mse_resid + np.diag(np.dot(X2,np.dot(covb,X2.T))) # predication variance only predvar = res.mse_resid/weights ip = (exog * np.dot(covb, exog.T).T).sum(1) if interval == 'confidence': predstd = np.sqrt(ip) elif interval == 'prediction': predstd = np.sqrt(ip + predvar) tppf = stats.t.isf(alpha/2., res.df_resid) interval_u = predicted + tppf * predstd interval_l = predicted - tppf * predstd return predstd, interval_l, interval_u
python
def wls_prediction_std(res, exog=None, weights=None, alpha=0.05, interval='confidence'): """ calculate standard deviation and confidence interval Applies to WLS and OLS, not to general GLS, that is independently but not identically distributed observations Parameters ---------- res : regression result instance results of WLS or OLS regression required attributes see notes exog : array_like (optional) exogenous variables for points to predict weights : scalar or array_like (optional) weights as defined for WLS (inverse of variance of observation) alpha : float (default: alpha = 0.05) confidence level for two-sided hypothesis Returns ------- predstd : array_like, 1d standard error of prediction same length as rows of exog interval_l, interval_u : array_like lower und upper confidence bounds Notes ----- The result instance needs to have at least the following res.model.predict() : predicted values or res.fittedvalues : values used in estimation res.cov_params() : covariance matrix of parameter estimates If exog is 1d, then it is interpreted as one observation, i.e. a row vector. testing status: not compared with other packages References ---------- Greene p.111 for OLS, extended to WLS by analogy """ # work around current bug: # fit doesn't attach results to model, predict broken # res.model.results covb = res.cov_params() if exog is None: exog = res.model.exog predicted = res.fittedvalues if weights is None: weights = res.model.weights else: exog = np.atleast_2d(exog) if covb.shape[1] != exog.shape[1]: raise ValueError('wrong shape of exog') predicted = res.model.predict(res.params, exog) if weights is None: weights = 1. else: weights = np.asarray(weights) if weights.size > 1 and len(weights) != exog.shape[0]: raise ValueError('weights and exog do not have matching shape') # full covariance: # predvar = res3.mse_resid + np.diag(np.dot(X2,np.dot(covb,X2.T))) # predication variance only predvar = res.mse_resid/weights ip = (exog * np.dot(covb, exog.T).T).sum(1) if interval == 'confidence': predstd = np.sqrt(ip) elif interval == 'prediction': predstd = np.sqrt(ip + predvar) tppf = stats.t.isf(alpha/2., res.df_resid) interval_u = predicted + tppf * predstd interval_l = predicted - tppf * predstd return predstd, interval_l, interval_u
[ "def", "wls_prediction_std", "(", "res", ",", "exog", "=", "None", ",", "weights", "=", "None", ",", "alpha", "=", "0.05", ",", "interval", "=", "'confidence'", ")", ":", "# work around current bug:", "# fit doesn't attach results to model, predict broken", "# res....
calculate standard deviation and confidence interval Applies to WLS and OLS, not to general GLS, that is independently but not identically distributed observations Parameters ---------- res : regression result instance results of WLS or OLS regression required attributes see notes exog : array_like (optional) exogenous variables for points to predict weights : scalar or array_like (optional) weights as defined for WLS (inverse of variance of observation) alpha : float (default: alpha = 0.05) confidence level for two-sided hypothesis Returns ------- predstd : array_like, 1d standard error of prediction same length as rows of exog interval_l, interval_u : array_like lower und upper confidence bounds Notes ----- The result instance needs to have at least the following res.model.predict() : predicted values or res.fittedvalues : values used in estimation res.cov_params() : covariance matrix of parameter estimates If exog is 1d, then it is interpreted as one observation, i.e. a row vector. testing status: not compared with other packages References ---------- Greene p.111 for OLS, extended to WLS by analogy
[ "calculate", "standard", "deviation", "and", "confidence", "interval" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/smoothers.py#L293-L371
train
214,500
has2k1/plotnine
plotnine/facets/layout.py
Layout.setup
def setup(self, layers, plot): """ Create a layout for the panels The layout is a dataframe that stores all the structual information about the panels that will make up the plot. The actual layout depends on the type of facet. This method ensures that each layer has a copy of the data it needs in `layer.data`. That data is also has column `PANEL` that indicates the panel onto which each data row/item will be plotted. """ data = [l.data for l in layers] # setup facets self.facet = plot.facet self.facet.setup_params(data) data = self.facet.setup_data(data) # setup coords self.coord = plot.coordinates self.coord.setup_params(data) data = self.coord.setup_data(data) # Generate panel layout data = self.facet.setup_data(data) self.layout = self.facet.compute_layout(data) self.layout = self.coord.setup_layout(self.layout) self.check_layout() # Map the data to the panels for layer, ldata in zip(layers, data): layer.data = self.facet.map(ldata, self.layout)
python
def setup(self, layers, plot): """ Create a layout for the panels The layout is a dataframe that stores all the structual information about the panels that will make up the plot. The actual layout depends on the type of facet. This method ensures that each layer has a copy of the data it needs in `layer.data`. That data is also has column `PANEL` that indicates the panel onto which each data row/item will be plotted. """ data = [l.data for l in layers] # setup facets self.facet = plot.facet self.facet.setup_params(data) data = self.facet.setup_data(data) # setup coords self.coord = plot.coordinates self.coord.setup_params(data) data = self.coord.setup_data(data) # Generate panel layout data = self.facet.setup_data(data) self.layout = self.facet.compute_layout(data) self.layout = self.coord.setup_layout(self.layout) self.check_layout() # Map the data to the panels for layer, ldata in zip(layers, data): layer.data = self.facet.map(ldata, self.layout)
[ "def", "setup", "(", "self", ",", "layers", ",", "plot", ")", ":", "data", "=", "[", "l", ".", "data", "for", "l", "in", "layers", "]", "# setup facets", "self", ".", "facet", "=", "plot", ".", "facet", "self", ".", "facet", ".", "setup_params", "(...
Create a layout for the panels The layout is a dataframe that stores all the structual information about the panels that will make up the plot. The actual layout depends on the type of facet. This method ensures that each layer has a copy of the data it needs in `layer.data`. That data is also has column `PANEL` that indicates the panel onto which each data row/item will be plotted.
[ "Create", "a", "layout", "for", "the", "panels" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L30-L64
train
214,501
has2k1/plotnine
plotnine/facets/layout.py
Layout.train_position
def train_position(self, layers, x_scale, y_scale): """ Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data. Notes ----- The number of x or y scales depends on the facetting, particularly the scales parameter. e.g if `scales='free'` then each panel will have separate x and y scales, and if `scales='fixed'` then all panels will share an x scale and a y scale. """ layout = self.layout if self.panel_scales_x is None and x_scale: result = self.facet.init_scales(layout, x_scale, None) self.panel_scales_x = result.x if self.panel_scales_y is None and y_scale: result = self.facet.init_scales(layout, None, y_scale) self.panel_scales_y = result.y self.facet.train_position_scales(self, layers)
python
def train_position(self, layers, x_scale, y_scale): """ Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data. Notes ----- The number of x or y scales depends on the facetting, particularly the scales parameter. e.g if `scales='free'` then each panel will have separate x and y scales, and if `scales='fixed'` then all panels will share an x scale and a y scale. """ layout = self.layout if self.panel_scales_x is None and x_scale: result = self.facet.init_scales(layout, x_scale, None) self.panel_scales_x = result.x if self.panel_scales_y is None and y_scale: result = self.facet.init_scales(layout, None, y_scale) self.panel_scales_y = result.y self.facet.train_position_scales(self, layers)
[ "def", "train_position", "(", "self", ",", "layers", ",", "x_scale", ",", "y_scale", ")", ":", "layout", "=", "self", ".", "layout", "if", "self", ".", "panel_scales_x", "is", "None", "and", "x_scale", ":", "result", "=", "self", ".", "facet", ".", "in...
Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data. Notes ----- The number of x or y scales depends on the facetting, particularly the scales parameter. e.g if `scales='free'` then each panel will have separate x and y scales, and if `scales='fixed'` then all panels will share an x scale and a y scale.
[ "Create", "all", "the", "required", "x", "&", "y", "panel_scales", "y_scales", "and", "set", "the", "ranges", "for", "each", "scale", "according", "to", "the", "data", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L66-L88
train
214,502
has2k1/plotnine
plotnine/facets/layout.py
Layout.get_scales
def get_scales(self, i): """ Return x & y scales for panel i Parameters ---------- i : int Panel id Returns ------- scales : types.SimpleNamespace Class attributes *x* for the x scale and *y* for the y scale of the panel """ # wrapping with np.asarray prevents an exception # on some datasets bool_idx = (np.asarray(self.layout['PANEL']) == i) xsc = None ysc = None if self.panel_scales_x: idx = self.layout.loc[bool_idx, 'SCALE_X'].values[0] xsc = self.panel_scales_x[idx-1] if self.panel_scales_y: idx = self.layout.loc[bool_idx, 'SCALE_Y'].values[0] ysc = self.panel_scales_y[idx-1] return types.SimpleNamespace(x=xsc, y=ysc)
python
def get_scales(self, i): """ Return x & y scales for panel i Parameters ---------- i : int Panel id Returns ------- scales : types.SimpleNamespace Class attributes *x* for the x scale and *y* for the y scale of the panel """ # wrapping with np.asarray prevents an exception # on some datasets bool_idx = (np.asarray(self.layout['PANEL']) == i) xsc = None ysc = None if self.panel_scales_x: idx = self.layout.loc[bool_idx, 'SCALE_X'].values[0] xsc = self.panel_scales_x[idx-1] if self.panel_scales_y: idx = self.layout.loc[bool_idx, 'SCALE_Y'].values[0] ysc = self.panel_scales_y[idx-1] return types.SimpleNamespace(x=xsc, y=ysc)
[ "def", "get_scales", "(", "self", ",", "i", ")", ":", "# wrapping with np.asarray prevents an exception", "# on some datasets", "bool_idx", "=", "(", "np", ".", "asarray", "(", "self", ".", "layout", "[", "'PANEL'", "]", ")", "==", "i", ")", "xsc", "=", "Non...
Return x & y scales for panel i Parameters ---------- i : int Panel id Returns ------- scales : types.SimpleNamespace Class attributes *x* for the x scale and *y* for the y scale of the panel
[ "Return", "x", "&", "y", "scales", "for", "panel", "i" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L116-L146
train
214,503
has2k1/plotnine
plotnine/facets/layout.py
Layout.reset_position_scales
def reset_position_scales(self): """ Reset x and y scales """ if not self.facet.shrink: return with suppress(AttributeError): self.panel_scales_x.reset() with suppress(AttributeError): self.panel_scales_y.reset()
python
def reset_position_scales(self): """ Reset x and y scales """ if not self.facet.shrink: return with suppress(AttributeError): self.panel_scales_x.reset() with suppress(AttributeError): self.panel_scales_y.reset()
[ "def", "reset_position_scales", "(", "self", ")", ":", "if", "not", "self", ".", "facet", ".", "shrink", ":", "return", "with", "suppress", "(", "AttributeError", ")", ":", "self", ".", "panel_scales_x", ".", "reset", "(", ")", "with", "suppress", "(", "...
Reset x and y scales
[ "Reset", "x", "and", "y", "scales" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L148-L159
train
214,504
has2k1/plotnine
plotnine/facets/layout.py
Layout.setup_panel_params
def setup_panel_params(self, coord): """ Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate """ if not self.panel_scales_x: raise PlotnineError('Missing an x scale') if not self.panel_scales_y: raise PlotnineError('Missing a y scale') self.panel_params = [] cols = ['SCALE_X', 'SCALE_Y'] for i, j in self.layout[cols].itertuples(index=False): i, j = i-1, j-1 params = coord.setup_panel_params( self.panel_scales_x[i], self.panel_scales_y[j]) self.panel_params.append(params)
python
def setup_panel_params(self, coord): """ Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate """ if not self.panel_scales_x: raise PlotnineError('Missing an x scale') if not self.panel_scales_y: raise PlotnineError('Missing a y scale') self.panel_params = [] cols = ['SCALE_X', 'SCALE_Y'] for i, j in self.layout[cols].itertuples(index=False): i, j = i-1, j-1 params = coord.setup_panel_params( self.panel_scales_x[i], self.panel_scales_y[j]) self.panel_params.append(params)
[ "def", "setup_panel_params", "(", "self", ",", "coord", ")", ":", "if", "not", "self", ".", "panel_scales_x", ":", "raise", "PlotnineError", "(", "'Missing an x scale'", ")", "if", "not", "self", ".", "panel_scales_y", ":", "raise", "PlotnineError", "(", "'Mis...
Calculate the x & y range & breaks information for each panel Parameters ---------- coord : coord Coordinate
[ "Calculate", "the", "x", "&", "y", "range", "&", "breaks", "information", "for", "each", "panel" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L161-L183
train
214,505
has2k1/plotnine
plotnine/facets/layout.py
Layout.finish_data
def finish_data(self, layers): """ Modify data before it is drawn out by the geom Parameters ---------- layers : list List of layers """ for layer in layers: layer.data = self.facet.finish_data(layer.data, self)
python
def finish_data(self, layers): """ Modify data before it is drawn out by the geom Parameters ---------- layers : list List of layers """ for layer in layers: layer.data = self.facet.finish_data(layer.data, self)
[ "def", "finish_data", "(", "self", ",", "layers", ")", ":", "for", "layer", "in", "layers", ":", "layer", ".", "data", "=", "self", ".", "facet", ".", "finish_data", "(", "layer", ".", "data", ",", "self", ")" ]
Modify data before it is drawn out by the geom Parameters ---------- layers : list List of layers
[ "Modify", "data", "before", "it", "is", "drawn", "out", "by", "the", "geom" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L185-L195
train
214,506
has2k1/plotnine
plotnine/guides/guide.py
guide._set_defaults
def _set_defaults(self): """ Set configuration parameters for drawing guide """ valid_locations = {'top', 'bottom', 'left', 'right'} horizontal_locations = {'left', 'right'} get_property = self.theme.themeables.property margin_location_lookup = {'t': 'b', 'b': 't', 'l': 'r', 'r': 'l'} # label position self.label_position = self.label_position or 'right' if self.label_position not in valid_locations: msg = "label position '{}' is invalid" raise PlotnineError(msg.format(self.label_position)) # label margin # legend_text_legend or legend_text_colorbar name = 'legend_text_{}'.format( self.__class__.__name__.split('_')[-1]) loc = margin_location_lookup[self.label_position[0]] try: margin = get_property(name, 'margin') except KeyError: self._label_margin = 3 else: self._label_margin = margin.get_as(loc, 'pt') # direction of guide if self.direction is None: if self.label_position in horizontal_locations: self.direction = 'vertical' else: self.direction = 'horizontal' # title position if self.title_position is None: if self.direction == 'vertical': self.title_position = 'top' elif self.direction == 'horizontal': self.title_position = 'left' if self.title_position not in valid_locations: msg = "title position '{}' is invalid" raise PlotnineError(msg.format(self.title_position)) # title alignment tmp = 'left' if self.direction == 'vertical' else 'center' self._title_align = self._default('legend_title_align', tmp) # by default, direction of each guide depends on # the position all the guides try: position = get_property('legend_position') except KeyError: position = 'right' if position in {'top', 'bottom'}: tmp = 'horizontal' else: # left, right, (default) tmp = 'vertical' self.direction = self._default('legend_direction', tmp) # title margin loc = margin_location_lookup[self.title_position[0]] try: margin = get_property('legend_title', 'margin') except KeyError: self._title_margin = 8 else: self._title_margin = margin.get_as(loc, 'pt') # legend_margin try: self._legend_margin = get_property('legend_margin') except KeyError: self._legend_margin = 10 # legend_entry_spacing try: self._legend_entry_spacing_x = get_property( 'legend_entry_spacing_x') except KeyError: self._legend_entry_spacing_x = 5 try: self._legend_entry_spacing_y = get_property( 'legend_entry_spacing_y') except KeyError: self._legend_entry_spacing_y = 2
python
def _set_defaults(self): """ Set configuration parameters for drawing guide """ valid_locations = {'top', 'bottom', 'left', 'right'} horizontal_locations = {'left', 'right'} get_property = self.theme.themeables.property margin_location_lookup = {'t': 'b', 'b': 't', 'l': 'r', 'r': 'l'} # label position self.label_position = self.label_position or 'right' if self.label_position not in valid_locations: msg = "label position '{}' is invalid" raise PlotnineError(msg.format(self.label_position)) # label margin # legend_text_legend or legend_text_colorbar name = 'legend_text_{}'.format( self.__class__.__name__.split('_')[-1]) loc = margin_location_lookup[self.label_position[0]] try: margin = get_property(name, 'margin') except KeyError: self._label_margin = 3 else: self._label_margin = margin.get_as(loc, 'pt') # direction of guide if self.direction is None: if self.label_position in horizontal_locations: self.direction = 'vertical' else: self.direction = 'horizontal' # title position if self.title_position is None: if self.direction == 'vertical': self.title_position = 'top' elif self.direction == 'horizontal': self.title_position = 'left' if self.title_position not in valid_locations: msg = "title position '{}' is invalid" raise PlotnineError(msg.format(self.title_position)) # title alignment tmp = 'left' if self.direction == 'vertical' else 'center' self._title_align = self._default('legend_title_align', tmp) # by default, direction of each guide depends on # the position all the guides try: position = get_property('legend_position') except KeyError: position = 'right' if position in {'top', 'bottom'}: tmp = 'horizontal' else: # left, right, (default) tmp = 'vertical' self.direction = self._default('legend_direction', tmp) # title margin loc = margin_location_lookup[self.title_position[0]] try: margin = get_property('legend_title', 'margin') except KeyError: self._title_margin = 8 else: self._title_margin = margin.get_as(loc, 'pt') # legend_margin try: self._legend_margin = get_property('legend_margin') except KeyError: self._legend_margin = 10 # legend_entry_spacing try: self._legend_entry_spacing_x = get_property( 'legend_entry_spacing_x') except KeyError: self._legend_entry_spacing_x = 5 try: self._legend_entry_spacing_y = get_property( 'legend_entry_spacing_y') except KeyError: self._legend_entry_spacing_y = 2
[ "def", "_set_defaults", "(", "self", ")", ":", "valid_locations", "=", "{", "'top'", ",", "'bottom'", ",", "'left'", ",", "'right'", "}", "horizontal_locations", "=", "{", "'left'", ",", "'right'", "}", "get_property", "=", "self", ".", "theme", ".", "them...
Set configuration parameters for drawing guide
[ "Set", "configuration", "parameters", "for", "drawing", "guide" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide.py#L107-L195
train
214,507
has2k1/plotnine
plotnine/guides/guide.py
guide.legend_aesthetics
def legend_aesthetics(self, layer, plot): """ Return the aesthetics that contribute to the legend Parameters ---------- layer : Layer Layer whose legend is to be drawn plot : ggplot Plot object Returns ------- matched : list List of the names of the aethetics that contribute to the legend. """ l = layer legend_ae = set(self.key.columns) - {'label'} all_ae = (l.mapping.keys() | (plot.mapping if l.inherit_aes else set()) | l.stat.DEFAULT_AES.keys()) geom_ae = l.geom.REQUIRED_AES | l.geom.DEFAULT_AES.keys() matched = all_ae & geom_ae & legend_ae matched = list(matched - set(l.geom.aes_params)) return matched
python
def legend_aesthetics(self, layer, plot): """ Return the aesthetics that contribute to the legend Parameters ---------- layer : Layer Layer whose legend is to be drawn plot : ggplot Plot object Returns ------- matched : list List of the names of the aethetics that contribute to the legend. """ l = layer legend_ae = set(self.key.columns) - {'label'} all_ae = (l.mapping.keys() | (plot.mapping if l.inherit_aes else set()) | l.stat.DEFAULT_AES.keys()) geom_ae = l.geom.REQUIRED_AES | l.geom.DEFAULT_AES.keys() matched = all_ae & geom_ae & legend_ae matched = list(matched - set(l.geom.aes_params)) return matched
[ "def", "legend_aesthetics", "(", "self", ",", "layer", ",", "plot", ")", ":", "l", "=", "layer", "legend_ae", "=", "set", "(", "self", ".", "key", ".", "columns", ")", "-", "{", "'label'", "}", "all_ae", "=", "(", "l", ".", "mapping", ".", "keys", ...
Return the aesthetics that contribute to the legend Parameters ---------- layer : Layer Layer whose legend is to be drawn plot : ggplot Plot object Returns ------- matched : list List of the names of the aethetics that contribute to the legend.
[ "Return", "the", "aesthetics", "that", "contribute", "to", "the", "legend" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide.py#L197-L222
train
214,508
has2k1/plotnine
plotnine/scales/scale.py
scale.train_df
def train_df(self, df): """ Train scale from a dataframe """ aesthetics = sorted(set(self.aesthetics) & set(df.columns)) for ae in aesthetics: self.train(df[ae])
python
def train_df(self, df): """ Train scale from a dataframe """ aesthetics = sorted(set(self.aesthetics) & set(df.columns)) for ae in aesthetics: self.train(df[ae])
[ "def", "train_df", "(", "self", ",", "df", ")", ":", "aesthetics", "=", "sorted", "(", "set", "(", "self", ".", "aesthetics", ")", "&", "set", "(", "df", ".", "columns", ")", ")", "for", "ae", "in", "aesthetics", ":", "self", ".", "train", "(", "...
Train scale from a dataframe
[ "Train", "scale", "from", "a", "dataframe" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scale.py#L214-L220
train
214,509
has2k1/plotnine
plotnine/guides/guide_legend.py
guide_legend.train
def train(self, scale, aesthetic=None): """ Create the key for the guide The key is a dataframe with two columns: - scale name : values - label : labels for each value scale name is one of the aesthetics ['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha', 'stroke'] Returns this guide if training is successful and None if it fails """ if aesthetic is None: aesthetic = scale.aesthetics[0] breaks = scale.get_breaks() if isinstance(breaks, OrderedDict): if all([np.isnan(x) for x in breaks.values()]): return None elif not len(breaks) or all(np.isnan(breaks)): return None with suppress(AttributeError): breaks = list(breaks.keys()) key = pd.DataFrame({ aesthetic: scale.map(breaks), 'label': scale.get_labels(breaks)}) # Drop out-of-range values for continuous scale # (should use scale$oob?) # Currently, numpy does not deal with NA (Not available) # When they are introduced, the block below should be # adjusted likewise, see ggplot2, guide-lengend.r if isinstance(scale, scale_continuous): limits = scale.limits b = np.asarray(breaks) noob = np.logical_and(limits[0] <= b, b <= limits[1]) key = key[noob] if len(key) == 0: return None self.key = key # create a hash of the important information in the guide labels = ' '.join(str(x) for x in self.key['label']) info = '\n'.join([self.title, labels, str(self.direction), self.__class__.__name__]) self.hash = hashlib.md5(info.encode('utf-8')).hexdigest() return self
python
def train(self, scale, aesthetic=None): """ Create the key for the guide The key is a dataframe with two columns: - scale name : values - label : labels for each value scale name is one of the aesthetics ['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha', 'stroke'] Returns this guide if training is successful and None if it fails """ if aesthetic is None: aesthetic = scale.aesthetics[0] breaks = scale.get_breaks() if isinstance(breaks, OrderedDict): if all([np.isnan(x) for x in breaks.values()]): return None elif not len(breaks) or all(np.isnan(breaks)): return None with suppress(AttributeError): breaks = list(breaks.keys()) key = pd.DataFrame({ aesthetic: scale.map(breaks), 'label': scale.get_labels(breaks)}) # Drop out-of-range values for continuous scale # (should use scale$oob?) # Currently, numpy does not deal with NA (Not available) # When they are introduced, the block below should be # adjusted likewise, see ggplot2, guide-lengend.r if isinstance(scale, scale_continuous): limits = scale.limits b = np.asarray(breaks) noob = np.logical_and(limits[0] <= b, b <= limits[1]) key = key[noob] if len(key) == 0: return None self.key = key # create a hash of the important information in the guide labels = ' '.join(str(x) for x in self.key['label']) info = '\n'.join([self.title, labels, str(self.direction), self.__class__.__name__]) self.hash = hashlib.md5(info.encode('utf-8')).hexdigest() return self
[ "def", "train", "(", "self", ",", "scale", ",", "aesthetic", "=", "None", ")", ":", "if", "aesthetic", "is", "None", ":", "aesthetic", "=", "scale", ".", "aesthetics", "[", "0", "]", "breaks", "=", "scale", ".", "get_breaks", "(", ")", "if", "isinsta...
Create the key for the guide The key is a dataframe with two columns: - scale name : values - label : labels for each value scale name is one of the aesthetics ['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha', 'stroke'] Returns this guide if training is successful and None if it fails
[ "Create", "the", "key", "for", "the", "guide" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_legend.py#L54-L108
train
214,510
has2k1/plotnine
plotnine/guides/guide_legend.py
guide_legend.create_geoms
def create_geoms(self, plot): """ Make information needed to draw a legend for each of the layers. For each layer, that information is a dictionary with the geom to draw the guide together with the data and the parameters that will be used in the call to geom. """ def get_legend_geom(layer): if hasattr(layer.geom, 'draw_legend'): geom = layer.geom.__class__ else: name = 'geom_{}'.format(layer.geom.legend_geom) geom = Registry[name] return geom # A layer either contributes to the guide, or it does not. The # guide entries may be ploted in the layers self.glayers = [] for l in plot.layers: exclude = set() if isinstance(l.show_legend, dict): l.show_legend = rename_aesthetics(l.show_legend) exclude = {ae for ae, val in l.show_legend.items() if not val} elif l.show_legend not in (None, True): continue matched = self.legend_aesthetics(l, plot) # This layer does not contribute to the legend if not set(matched) - exclude: continue data = self.key[matched].copy() data = l.use_defaults(data) # override.aes in guide_legend manually changes the geom for ae in set(self.override_aes) & set(data.columns): data[ae] = self.override_aes[ae] geom = get_legend_geom(l) data = remove_missing( data, l.geom.params['na_rm'], list(l.geom.REQUIRED_AES | l.geom.NON_MISSING_AES), '{} legend'.format(l.geom.__class__.__name__)) self.glayers.append( types.SimpleNamespace(geom=geom, data=data, layer=l)) if not self.glayers: return None return self
python
def create_geoms(self, plot): """ Make information needed to draw a legend for each of the layers. For each layer, that information is a dictionary with the geom to draw the guide together with the data and the parameters that will be used in the call to geom. """ def get_legend_geom(layer): if hasattr(layer.geom, 'draw_legend'): geom = layer.geom.__class__ else: name = 'geom_{}'.format(layer.geom.legend_geom) geom = Registry[name] return geom # A layer either contributes to the guide, or it does not. The # guide entries may be ploted in the layers self.glayers = [] for l in plot.layers: exclude = set() if isinstance(l.show_legend, dict): l.show_legend = rename_aesthetics(l.show_legend) exclude = {ae for ae, val in l.show_legend.items() if not val} elif l.show_legend not in (None, True): continue matched = self.legend_aesthetics(l, plot) # This layer does not contribute to the legend if not set(matched) - exclude: continue data = self.key[matched].copy() data = l.use_defaults(data) # override.aes in guide_legend manually changes the geom for ae in set(self.override_aes) & set(data.columns): data[ae] = self.override_aes[ae] geom = get_legend_geom(l) data = remove_missing( data, l.geom.params['na_rm'], list(l.geom.REQUIRED_AES | l.geom.NON_MISSING_AES), '{} legend'.format(l.geom.__class__.__name__)) self.glayers.append( types.SimpleNamespace(geom=geom, data=data, layer=l)) if not self.glayers: return None return self
[ "def", "create_geoms", "(", "self", ",", "plot", ")", ":", "def", "get_legend_geom", "(", "layer", ")", ":", "if", "hasattr", "(", "layer", ".", "geom", ",", "'draw_legend'", ")", ":", "geom", "=", "layer", ".", "geom", ".", "__class__", "else", ":", ...
Make information needed to draw a legend for each of the layers. For each layer, that information is a dictionary with the geom to draw the guide together with the data and the parameters that will be used in the call to geom.
[ "Make", "information", "needed", "to", "draw", "a", "legend", "for", "each", "of", "the", "layers", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_legend.py#L132-L182
train
214,511
has2k1/plotnine
setup.py
get_package_data
def get_package_data(): """ Return package data For example: {'': ['*.txt', '*.rst'], 'hello': ['*.msg']} means: - If any package contains *.txt or *.rst files, include them - And include any *.msg files found in the 'hello' package, too: """ baseline_images = [ 'tests/baseline_images/%s/*' % x for x in os.listdir('plotnine/tests/baseline_images')] csv_data = ['data/*.csv'] package_data = {'plotnine': baseline_images + csv_data} return package_data
python
def get_package_data(): """ Return package data For example: {'': ['*.txt', '*.rst'], 'hello': ['*.msg']} means: - If any package contains *.txt or *.rst files, include them - And include any *.msg files found in the 'hello' package, too: """ baseline_images = [ 'tests/baseline_images/%s/*' % x for x in os.listdir('plotnine/tests/baseline_images')] csv_data = ['data/*.csv'] package_data = {'plotnine': baseline_images + csv_data} return package_data
[ "def", "get_package_data", "(", ")", ":", "baseline_images", "=", "[", "'tests/baseline_images/%s/*'", "%", "x", "for", "x", "in", "os", ".", "listdir", "(", "'plotnine/tests/baseline_images'", ")", "]", "csv_data", "=", "[", "'data/*.csv'", "]", "package_data", ...
Return package data For example: {'': ['*.txt', '*.rst'], 'hello': ['*.msg']} means: - If any package contains *.txt or *.rst files, include them - And include any *.msg files found in the 'hello' package, too:
[ "Return", "package", "data" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/setup.py#L73-L93
train
214,512
has2k1/plotnine
plotnine/__init__.py
_get_all_imports
def _get_all_imports(): """ Return list of all the imports This prevents sub-modules (geoms, stats, utils, ...) from being imported into the user namespace by the following import statement from plotnine import * This is because `from Module import Something` leads to `Module` itself coming into the namespace!! """ import types lst = [name for name, obj in globals().items() if not (name.startswith('_') or name == 'absolute_import' or isinstance(obj, types.ModuleType))] return lst
python
def _get_all_imports(): """ Return list of all the imports This prevents sub-modules (geoms, stats, utils, ...) from being imported into the user namespace by the following import statement from plotnine import * This is because `from Module import Something` leads to `Module` itself coming into the namespace!! """ import types lst = [name for name, obj in globals().items() if not (name.startswith('_') or name == 'absolute_import' or isinstance(obj, types.ModuleType))] return lst
[ "def", "_get_all_imports", "(", ")", ":", "import", "types", "lst", "=", "[", "name", "for", "name", ",", "obj", "in", "globals", "(", ")", ".", "items", "(", ")", "if", "not", "(", "name", ".", "startswith", "(", "'_'", ")", "or", "name", "==", ...
Return list of all the imports This prevents sub-modules (geoms, stats, utils, ...) from being imported into the user namespace by the following import statement from plotnine import * This is because `from Module import Something` leads to `Module` itself coming into the namespace!!
[ "Return", "list", "of", "all", "the", "imports" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/__init__.py#L22-L40
train
214,513
has2k1/plotnine
plotnine/geoms/geom_rect.py
_rectangles_to_polygons
def _rectangles_to_polygons(df): """ Convert rect data to polygons Paramters --------- df : dataframe Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns, plus others for aesthetics ... Returns ------- data : dataframe Dataframe with *x* and *y* columns, plus others for aesthetics ... """ n = len(df) # Helper indexing arrays xmin_idx = np.tile([True, True, False, False], n) xmax_idx = ~xmin_idx ymin_idx = np.tile([True, False, False, True], n) ymax_idx = ~ymin_idx # There are 2 x and 2 y values for each of xmin, xmax, ymin & ymax # The positions are as layed out in the indexing arrays # x and y values x = np.empty(n*4) y = np.empty(n*4) x[xmin_idx] = df['xmin'].repeat(2) x[xmax_idx] = df['xmax'].repeat(2) y[ymin_idx] = df['ymin'].repeat(2) y[ymax_idx] = df['ymax'].repeat(2) # Aesthetic columns and others other_cols = df.columns.difference( ['x', 'y', 'xmin', 'xmax', 'ymin', 'ymax']) d = {col: np.repeat(df[col].values, 4) for col in other_cols} data = pd.DataFrame({ 'x': x, 'y': y, **d }) return data
python
def _rectangles_to_polygons(df): """ Convert rect data to polygons Paramters --------- df : dataframe Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns, plus others for aesthetics ... Returns ------- data : dataframe Dataframe with *x* and *y* columns, plus others for aesthetics ... """ n = len(df) # Helper indexing arrays xmin_idx = np.tile([True, True, False, False], n) xmax_idx = ~xmin_idx ymin_idx = np.tile([True, False, False, True], n) ymax_idx = ~ymin_idx # There are 2 x and 2 y values for each of xmin, xmax, ymin & ymax # The positions are as layed out in the indexing arrays # x and y values x = np.empty(n*4) y = np.empty(n*4) x[xmin_idx] = df['xmin'].repeat(2) x[xmax_idx] = df['xmax'].repeat(2) y[ymin_idx] = df['ymin'].repeat(2) y[ymax_idx] = df['ymax'].repeat(2) # Aesthetic columns and others other_cols = df.columns.difference( ['x', 'y', 'xmin', 'xmax', 'ymin', 'ymax']) d = {col: np.repeat(df[col].values, 4) for col in other_cols} data = pd.DataFrame({ 'x': x, 'y': y, **d }) return data
[ "def", "_rectangles_to_polygons", "(", "df", ")", ":", "n", "=", "len", "(", "df", ")", "# Helper indexing arrays", "xmin_idx", "=", "np", ".", "tile", "(", "[", "True", ",", "True", ",", "False", ",", "False", "]", ",", "n", ")", "xmax_idx", "=", "~...
Convert rect data to polygons Paramters --------- df : dataframe Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns, plus others for aesthetics ... Returns ------- data : dataframe Dataframe with *x* and *y* columns, plus others for aesthetics ...
[ "Convert", "rect", "data", "to", "polygons" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/geom_rect.py#L73-L116
train
214,514
has2k1/plotnine
plotnine/aes.py
rename_aesthetics
def rename_aesthetics(obj): """ Rename aesthetics in obj Parameters ---------- obj : dict or list Object that contains aesthetics names Returns ------- obj : dict or list Object that contains aesthetics names """ if isinstance(obj, dict): for name in obj: new_name = name.replace('colour', 'color') if name != new_name: obj[new_name] = obj.pop(name) else: obj = [name.replace('colour', 'color') for name in obj] return obj
python
def rename_aesthetics(obj): """ Rename aesthetics in obj Parameters ---------- obj : dict or list Object that contains aesthetics names Returns ------- obj : dict or list Object that contains aesthetics names """ if isinstance(obj, dict): for name in obj: new_name = name.replace('colour', 'color') if name != new_name: obj[new_name] = obj.pop(name) else: obj = [name.replace('colour', 'color') for name in obj] return obj
[ "def", "rename_aesthetics", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "name", "in", "obj", ":", "new_name", "=", "name", ".", "replace", "(", "'colour'", ",", "'color'", ")", "if", "name", "!=", "new_name", "...
Rename aesthetics in obj Parameters ---------- obj : dict or list Object that contains aesthetics names Returns ------- obj : dict or list Object that contains aesthetics names
[ "Rename", "aesthetics", "in", "obj" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L144-L166
train
214,515
has2k1/plotnine
plotnine/aes.py
get_calculated_aes
def get_calculated_aes(aesthetics): """ Return a list of the aesthetics that are calculated """ calculated_aesthetics = [] for name, value in aesthetics.items(): if is_calculated_aes(value): calculated_aesthetics.append(name) return calculated_aesthetics
python
def get_calculated_aes(aesthetics): """ Return a list of the aesthetics that are calculated """ calculated_aesthetics = [] for name, value in aesthetics.items(): if is_calculated_aes(value): calculated_aesthetics.append(name) return calculated_aesthetics
[ "def", "get_calculated_aes", "(", "aesthetics", ")", ":", "calculated_aesthetics", "=", "[", "]", "for", "name", ",", "value", "in", "aesthetics", ".", "items", "(", ")", ":", "if", "is_calculated_aes", "(", "value", ")", ":", "calculated_aesthetics", ".", "...
Return a list of the aesthetics that are calculated
[ "Return", "a", "list", "of", "the", "aesthetics", "that", "are", "calculated" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L169-L177
train
214,516
has2k1/plotnine
plotnine/aes.py
is_calculated_aes
def is_calculated_aes(ae): """ Return a True if of the aesthetics that are calculated Parameters ---------- ae : object Aesthetic mapping >>> is_calculated_aes('density') False >>> is_calculated_aes(4) False >>> is_calculated_aes('..density..') True >>> is_calculated_aes('stat(density)') True >>> is_calculated_aes('stat(100*density)') True >>> is_calculated_aes('100*stat(density)') True """ if not isinstance(ae, str): return False for pattern in (STAT_RE, DOTS_RE): if pattern.search(ae): return True return False
python
def is_calculated_aes(ae): """ Return a True if of the aesthetics that are calculated Parameters ---------- ae : object Aesthetic mapping >>> is_calculated_aes('density') False >>> is_calculated_aes(4) False >>> is_calculated_aes('..density..') True >>> is_calculated_aes('stat(density)') True >>> is_calculated_aes('stat(100*density)') True >>> is_calculated_aes('100*stat(density)') True """ if not isinstance(ae, str): return False for pattern in (STAT_RE, DOTS_RE): if pattern.search(ae): return True return False
[ "def", "is_calculated_aes", "(", "ae", ")", ":", "if", "not", "isinstance", "(", "ae", ",", "str", ")", ":", "return", "False", "for", "pattern", "in", "(", "STAT_RE", ",", "DOTS_RE", ")", ":", "if", "pattern", ".", "search", "(", "ae", ")", ":", "...
Return a True if of the aesthetics that are calculated Parameters ---------- ae : object Aesthetic mapping >>> is_calculated_aes('density') False >>> is_calculated_aes(4) False >>> is_calculated_aes('..density..') True >>> is_calculated_aes('stat(density)') True >>> is_calculated_aes('stat(100*density)') True >>> is_calculated_aes('100*stat(density)') True
[ "Return", "a", "True", "if", "of", "the", "aesthetics", "that", "are", "calculated" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L180-L214
train
214,517
has2k1/plotnine
plotnine/aes.py
strip_stat
def strip_stat(value): """ Remove calc function that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value with the dots removed. >>> strip_stat('stat(density + stat(count))') density + count >>> strip_stat('stat(density) + 5') density + 5 >>> strip_stat('5 + stat(func(density))') 5 + func(density) >>> strip_stat('stat(func(density) + var1)') func(density) + var1 >>> strip_stat('calc + var1') calc + var1 >>> strip_stat(4) 4 """ def strip_hanging_closing_parens(s): """ Remove leftover parens """ # Use and integer stack to track parens # and ignore leftover closing parens stack = 0 idx = [] for i, c in enumerate(s): if c == '(': stack += 1 elif c == ')': stack -= 1 if stack < 0: idx.append(i) stack = 0 continue yield c with suppress(TypeError): if STAT_RE.search(value): value = re.sub(r'\bstat\(', '', value) value = ''.join(strip_hanging_closing_parens(value)) return value
python
def strip_stat(value): """ Remove calc function that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value with the dots removed. >>> strip_stat('stat(density + stat(count))') density + count >>> strip_stat('stat(density) + 5') density + 5 >>> strip_stat('5 + stat(func(density))') 5 + func(density) >>> strip_stat('stat(func(density) + var1)') func(density) + var1 >>> strip_stat('calc + var1') calc + var1 >>> strip_stat(4) 4 """ def strip_hanging_closing_parens(s): """ Remove leftover parens """ # Use and integer stack to track parens # and ignore leftover closing parens stack = 0 idx = [] for i, c in enumerate(s): if c == '(': stack += 1 elif c == ')': stack -= 1 if stack < 0: idx.append(i) stack = 0 continue yield c with suppress(TypeError): if STAT_RE.search(value): value = re.sub(r'\bstat\(', '', value) value = ''.join(strip_hanging_closing_parens(value)) return value
[ "def", "strip_stat", "(", "value", ")", ":", "def", "strip_hanging_closing_parens", "(", "s", ")", ":", "\"\"\"\n Remove leftover parens\n \"\"\"", "# Use and integer stack to track parens", "# and ignore leftover closing parens", "stack", "=", "0", "idx", "=", ...
Remove calc function that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value with the dots removed. >>> strip_stat('stat(density + stat(count))') density + count >>> strip_stat('stat(density) + 5') density + 5 >>> strip_stat('5 + stat(func(density))') 5 + func(density) >>> strip_stat('stat(func(density) + var1)') func(density) + var1 >>> strip_stat('calc + var1') calc + var1 >>> strip_stat(4) 4
[ "Remove", "calc", "function", "that", "mark", "calculated", "aesthetics" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L234-L291
train
214,518
has2k1/plotnine
plotnine/aes.py
is_position_aes
def is_position_aes(vars_): """ Figure out if an aesthetic is a position aesthetic or not """ try: return all([aes_to_scale(v) in {'x', 'y'} for v in vars_]) except TypeError: return aes_to_scale(vars_) in {'x', 'y'}
python
def is_position_aes(vars_): """ Figure out if an aesthetic is a position aesthetic or not """ try: return all([aes_to_scale(v) in {'x', 'y'} for v in vars_]) except TypeError: return aes_to_scale(vars_) in {'x', 'y'}
[ "def", "is_position_aes", "(", "vars_", ")", ":", "try", ":", "return", "all", "(", "[", "aes_to_scale", "(", "v", ")", "in", "{", "'x'", ",", "'y'", "}", "for", "v", "in", "vars_", "]", ")", "except", "TypeError", ":", "return", "aes_to_scale", "(",...
Figure out if an aesthetic is a position aesthetic or not
[ "Figure", "out", "if", "an", "aesthetic", "is", "a", "position", "aesthetic", "or", "not" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L343-L350
train
214,519
has2k1/plotnine
plotnine/aes.py
make_labels
def make_labels(mapping): """ Convert aesthetic mapping into text labels """ labels = mapping.copy() for ae in labels: labels[ae] = strip_calculated_markers(labels[ae]) return labels
python
def make_labels(mapping): """ Convert aesthetic mapping into text labels """ labels = mapping.copy() for ae in labels: labels[ae] = strip_calculated_markers(labels[ae]) return labels
[ "def", "make_labels", "(", "mapping", ")", ":", "labels", "=", "mapping", ".", "copy", "(", ")", "for", "ae", "in", "labels", ":", "labels", "[", "ae", "]", "=", "strip_calculated_markers", "(", "labels", "[", "ae", "]", ")", "return", "labels" ]
Convert aesthetic mapping into text labels
[ "Convert", "aesthetic", "mapping", "into", "text", "labels" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L353-L360
train
214,520
has2k1/plotnine
plotnine/aes.py
is_valid_aesthetic
def is_valid_aesthetic(value, ae): """ Return True if `value` looks valid. Parameters ---------- value : object Value to check ae : str Aesthetic name Returns ------- out : bool Whether the value is of a valid looking form. Notes ----- There are no guarantees that he value is spot on valid. """ if ae == 'linetype': named = {'solid', 'dashed', 'dashdot', 'dotted', '_', '--', '-.', ':', 'None', ' ', ''} if value in named: return True # tuple of the form (offset, (on, off, on, off, ...)) # e.g (0, (1, 2)) conditions = [isinstance(value, tuple), isinstance(value[0], int), isinstance(value[1], tuple), len(value[1]) % 2 == 0, all(isinstance(x, int) for x in value[1])] if all(conditions): return True return False elif ae == 'shape': if isinstance(value, str): return True # tuple of the form (numsides, style, angle) # where style is in the range [0, 3] # e.g (4, 1, 45) conditions = [isinstance(value, tuple), all(isinstance(x, int) for x in value), 0 <= value[1] < 3] if all(conditions): return True return False elif ae in {'color', 'fill'}: if isinstance(value, str): return True with suppress(TypeError): if (isinstance(value, (tuple, list)) and all(0 <= x <= 1 for x in value)): return True return False # For any other aesthetics we return False to allow # for special cases to be discovered and then coded # for appropriately. return False
python
def is_valid_aesthetic(value, ae): """ Return True if `value` looks valid. Parameters ---------- value : object Value to check ae : str Aesthetic name Returns ------- out : bool Whether the value is of a valid looking form. Notes ----- There are no guarantees that he value is spot on valid. """ if ae == 'linetype': named = {'solid', 'dashed', 'dashdot', 'dotted', '_', '--', '-.', ':', 'None', ' ', ''} if value in named: return True # tuple of the form (offset, (on, off, on, off, ...)) # e.g (0, (1, 2)) conditions = [isinstance(value, tuple), isinstance(value[0], int), isinstance(value[1], tuple), len(value[1]) % 2 == 0, all(isinstance(x, int) for x in value[1])] if all(conditions): return True return False elif ae == 'shape': if isinstance(value, str): return True # tuple of the form (numsides, style, angle) # where style is in the range [0, 3] # e.g (4, 1, 45) conditions = [isinstance(value, tuple), all(isinstance(x, int) for x in value), 0 <= value[1] < 3] if all(conditions): return True return False elif ae in {'color', 'fill'}: if isinstance(value, str): return True with suppress(TypeError): if (isinstance(value, (tuple, list)) and all(0 <= x <= 1 for x in value)): return True return False # For any other aesthetics we return False to allow # for special cases to be discovered and then coded # for appropriately. return False
[ "def", "is_valid_aesthetic", "(", "value", ",", "ae", ")", ":", "if", "ae", "==", "'linetype'", ":", "named", "=", "{", "'solid'", ",", "'dashed'", ",", "'dashdot'", ",", "'dotted'", ",", "'_'", ",", "'--'", ",", "'-.'", ",", "':'", ",", "'None'", ",...
Return True if `value` looks valid. Parameters ---------- value : object Value to check ae : str Aesthetic name Returns ------- out : bool Whether the value is of a valid looking form. Notes ----- There are no guarantees that he value is spot on valid.
[ "Return", "True", "if", "value", "looks", "valid", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L363-L428
train
214,521
has2k1/plotnine
plotnine/facets/facet_wrap.py
parse_wrap_facets
def parse_wrap_facets(facets): """ Return list of facetting variables """ valid_forms = ['~ var1', '~ var1 + var2'] error_msg = ("Valid formula for 'facet_wrap' look like" " {}".format(valid_forms)) if isinstance(facets, (list, tuple)): return facets if not isinstance(facets, str): raise PlotnineError(error_msg) if '~' in facets: variables_pattern = r'(\w+(?:\s*\+\s*\w+)*|\.)' pattern = r'\s*~\s*{0}\s*'.format(variables_pattern) match = re.match(pattern, facets) if not match: raise PlotnineError(error_msg) facets = [var.strip() for var in match.group(1).split('+')] elif re.match(r'\w+', facets): # allow plain string as the variable name facets = [facets] else: raise PlotnineError(error_msg) return facets
python
def parse_wrap_facets(facets): """ Return list of facetting variables """ valid_forms = ['~ var1', '~ var1 + var2'] error_msg = ("Valid formula for 'facet_wrap' look like" " {}".format(valid_forms)) if isinstance(facets, (list, tuple)): return facets if not isinstance(facets, str): raise PlotnineError(error_msg) if '~' in facets: variables_pattern = r'(\w+(?:\s*\+\s*\w+)*|\.)' pattern = r'\s*~\s*{0}\s*'.format(variables_pattern) match = re.match(pattern, facets) if not match: raise PlotnineError(error_msg) facets = [var.strip() for var in match.group(1).split('+')] elif re.match(r'\w+', facets): # allow plain string as the variable name facets = [facets] else: raise PlotnineError(error_msg) return facets
[ "def", "parse_wrap_facets", "(", "facets", ")", ":", "valid_forms", "=", "[", "'~ var1'", ",", "'~ var1 + var2'", "]", "error_msg", "=", "(", "\"Valid formula for 'facet_wrap' look like\"", "\" {}\"", ".", "format", "(", "valid_forms", ")", ")", "if", "isinstance", ...
Return list of facetting variables
[ "Return", "list", "of", "facetting", "variables" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L256-L284
train
214,522
has2k1/plotnine
plotnine/facets/facet_wrap.py
n2mfrow
def n2mfrow(nr_plots): """ Compute the rows and columns given the number of plots. This is a port of grDevices::n2mfrow from R """ if nr_plots <= 3: nrow, ncol = nr_plots, 1 elif nr_plots <= 6: nrow, ncol = (nr_plots + 1) // 2, 2 elif nr_plots <= 12: nrow, ncol = (nr_plots + 2) // 3, 3 else: nrow = int(np.ceil(np.sqrt(nr_plots))) ncol = int(np.ceil(nr_plots/nrow)) return (nrow, ncol)
python
def n2mfrow(nr_plots): """ Compute the rows and columns given the number of plots. This is a port of grDevices::n2mfrow from R """ if nr_plots <= 3: nrow, ncol = nr_plots, 1 elif nr_plots <= 6: nrow, ncol = (nr_plots + 1) // 2, 2 elif nr_plots <= 12: nrow, ncol = (nr_plots + 2) // 3, 3 else: nrow = int(np.ceil(np.sqrt(nr_plots))) ncol = int(np.ceil(nr_plots/nrow)) return (nrow, ncol)
[ "def", "n2mfrow", "(", "nr_plots", ")", ":", "if", "nr_plots", "<=", "3", ":", "nrow", ",", "ncol", "=", "nr_plots", ",", "1", "elif", "nr_plots", "<=", "6", ":", "nrow", ",", "ncol", "=", "(", "nr_plots", "+", "1", ")", "//", "2", ",", "2", "e...
Compute the rows and columns given the number of plots. This is a port of grDevices::n2mfrow from R
[ "Compute", "the", "rows", "and", "columns", "given", "the", "number", "of", "plots", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L302-L318
train
214,523
has2k1/plotnine
plotnine/facets/facet_wrap.py
facet_wrap.spaceout_and_resize_panels
def spaceout_and_resize_panels(self): """ Adjust the spacing between the panels and resize them to meet the aspect ratio """ ncol = self.ncol nrow = self.nrow figure = self.figure theme = self.theme get_property = theme.themeables.property left = figure.subplotpars.left right = figure.subplotpars.right top = figure.subplotpars.top bottom = figure.subplotpars.bottom top_strip_height = self.strip_size('top') W, H = figure.get_size_inches() try: spacing_x = get_property('panel_spacing_x') except KeyError: spacing_x = 0.1 try: spacing_y = get_property('panel_spacing_y') except KeyError: spacing_y = 0.1 try: aspect_ratio = get_property('aspect_ratio') except KeyError: # If the panels have different limits the coordinates # cannot compute a common aspect ratio if not self.free['x'] and not self.free['y']: aspect_ratio = self.coordinates.aspect( self.layout.panel_params[0]) else: aspect_ratio = None if theme.themeables.is_blank('strip_text_x'): top_strip_height = 0 # Account for the vertical sliding of the strip if any with suppress(KeyError): strip_margin_x = get_property('strip_margin_x') top_strip_height *= (1 + strip_margin_x) # The goal is to have equal spacing along the vertical # and the horizontal. We use the wspace and compute # the appropriate hspace. It would be a lot easier if # MPL had a better layout manager. # width of axes and height of axes w = ((right-left)*W - spacing_x*(ncol-1)) / ncol h = ((top-bottom)*H - (spacing_y+top_strip_height)*(nrow-1)) / nrow # aspect ratio changes the size of the figure if aspect_ratio is not None: h = w*aspect_ratio H = (h*nrow + (spacing_y+top_strip_height)*(nrow-1)) / \ (top-bottom) figure.set_figheight(H) # spacing wspace = spacing_x/w hspace = (spacing_y + top_strip_height) / h figure.subplots_adjust(wspace=wspace, hspace=hspace)
python
def spaceout_and_resize_panels(self): """ Adjust the spacing between the panels and resize them to meet the aspect ratio """ ncol = self.ncol nrow = self.nrow figure = self.figure theme = self.theme get_property = theme.themeables.property left = figure.subplotpars.left right = figure.subplotpars.right top = figure.subplotpars.top bottom = figure.subplotpars.bottom top_strip_height = self.strip_size('top') W, H = figure.get_size_inches() try: spacing_x = get_property('panel_spacing_x') except KeyError: spacing_x = 0.1 try: spacing_y = get_property('panel_spacing_y') except KeyError: spacing_y = 0.1 try: aspect_ratio = get_property('aspect_ratio') except KeyError: # If the panels have different limits the coordinates # cannot compute a common aspect ratio if not self.free['x'] and not self.free['y']: aspect_ratio = self.coordinates.aspect( self.layout.panel_params[0]) else: aspect_ratio = None if theme.themeables.is_blank('strip_text_x'): top_strip_height = 0 # Account for the vertical sliding of the strip if any with suppress(KeyError): strip_margin_x = get_property('strip_margin_x') top_strip_height *= (1 + strip_margin_x) # The goal is to have equal spacing along the vertical # and the horizontal. We use the wspace and compute # the appropriate hspace. It would be a lot easier if # MPL had a better layout manager. # width of axes and height of axes w = ((right-left)*W - spacing_x*(ncol-1)) / ncol h = ((top-bottom)*H - (spacing_y+top_strip_height)*(nrow-1)) / nrow # aspect ratio changes the size of the figure if aspect_ratio is not None: h = w*aspect_ratio H = (h*nrow + (spacing_y+top_strip_height)*(nrow-1)) / \ (top-bottom) figure.set_figheight(H) # spacing wspace = spacing_x/w hspace = (spacing_y + top_strip_height) / h figure.subplots_adjust(wspace=wspace, hspace=hspace)
[ "def", "spaceout_and_resize_panels", "(", "self", ")", ":", "ncol", "=", "self", ".", "ncol", "nrow", "=", "self", ".", "nrow", "figure", "=", "self", ".", "figure", "theme", "=", "self", ".", "theme", "get_property", "=", "theme", ".", "themeables", "."...
Adjust the spacing between the panels and resize them to meet the aspect ratio
[ "Adjust", "the", "spacing", "between", "the", "panels", "and", "resize", "them", "to", "meet", "the", "aspect", "ratio" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L149-L215
train
214,524
has2k1/plotnine
plotnine/themes/elements.py
Margin.get_as
def get_as(self, key, units='pt'): """ Return key in given units """ dpi = 72 size = self.element.properties.get('size', 0) value = self[key] functions = { 'pt-lines': lambda x: x/size, 'pt-in': lambda x: x/dpi, 'lines-pt': lambda x: x*size, 'lines-in': lambda x: x*size/dpi, 'in-pt': lambda x: x*dpi, 'in-lines': lambda x: x*dpi/size } if self['units'] != units: conversion = '{}-{}'.format(self['units'], units) try: value = functions[conversion](value) except ZeroDivisionError: value = 0 return value
python
def get_as(self, key, units='pt'): """ Return key in given units """ dpi = 72 size = self.element.properties.get('size', 0) value = self[key] functions = { 'pt-lines': lambda x: x/size, 'pt-in': lambda x: x/dpi, 'lines-pt': lambda x: x*size, 'lines-in': lambda x: x*size/dpi, 'in-pt': lambda x: x*dpi, 'in-lines': lambda x: x*dpi/size } if self['units'] != units: conversion = '{}-{}'.format(self['units'], units) try: value = functions[conversion](value) except ZeroDivisionError: value = 0 return value
[ "def", "get_as", "(", "self", ",", "key", ",", "units", "=", "'pt'", ")", ":", "dpi", "=", "72", "size", "=", "self", ".", "element", ".", "properties", ".", "get", "(", "'size'", ",", "0", ")", "value", "=", "self", "[", "key", "]", "functions",...
Return key in given units
[ "Return", "key", "in", "given", "units" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/elements.py#L223-L247
train
214,525
has2k1/plotnine
plotnine/layer.py
discrete_columns
def discrete_columns(df, ignore): """ Return a list of the discrete columns in the dataframe `df`. `ignore` is a list|set|tuple with the names of the columns to skip. """ lst = [] for col in df: if array_kind.discrete(df[col]) and (col not in ignore): # Some columns are represented as object dtype # but may have compound structures as values. try: hash(df[col].iloc[0]) except TypeError: continue lst.append(col) return lst
python
def discrete_columns(df, ignore): """ Return a list of the discrete columns in the dataframe `df`. `ignore` is a list|set|tuple with the names of the columns to skip. """ lst = [] for col in df: if array_kind.discrete(df[col]) and (col not in ignore): # Some columns are represented as object dtype # but may have compound structures as values. try: hash(df[col].iloc[0]) except TypeError: continue lst.append(col) return lst
[ "def", "discrete_columns", "(", "df", ",", "ignore", ")", ":", "lst", "=", "[", "]", "for", "col", "in", "df", ":", "if", "array_kind", ".", "discrete", "(", "df", "[", "col", "]", ")", "and", "(", "col", "not", "in", "ignore", ")", ":", "# Some ...
Return a list of the discrete columns in the dataframe `df`. `ignore` is a list|set|tuple with the names of the columns to skip.
[ "Return", "a", "list", "of", "the", "discrete", "columns", "in", "the", "dataframe", "df", ".", "ignore", "is", "a", "list|set|tuple", "with", "the", "names", "of", "the", "columns", "to", "skip", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L490-L506
train
214,526
has2k1/plotnine
plotnine/layer.py
is_known_scalar
def is_known_scalar(value): """ Return True if value is a type we expect in a dataframe """ def _is_datetime_or_timedelta(value): # Using pandas.Series helps catch python, numpy and pandas # versions of these types return pd.Series(value).dtype.kind in ('M', 'm') return not np.iterable(value) and (isinstance(value, numbers.Number) or _is_datetime_or_timedelta(value))
python
def is_known_scalar(value): """ Return True if value is a type we expect in a dataframe """ def _is_datetime_or_timedelta(value): # Using pandas.Series helps catch python, numpy and pandas # versions of these types return pd.Series(value).dtype.kind in ('M', 'm') return not np.iterable(value) and (isinstance(value, numbers.Number) or _is_datetime_or_timedelta(value))
[ "def", "is_known_scalar", "(", "value", ")", ":", "def", "_is_datetime_or_timedelta", "(", "value", ")", ":", "# Using pandas.Series helps catch python, numpy and pandas", "# versions of these types", "return", "pd", ".", "Series", "(", "value", ")", ".", "dtype", ".", ...
Return True if value is a type we expect in a dataframe
[ "Return", "True", "if", "value", "is", "a", "type", "we", "expect", "in", "a", "dataframe" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L509-L519
train
214,527
has2k1/plotnine
plotnine/layer.py
layer.generate_data
def generate_data(self, plot_data): """ Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data """ # Each layer that does not have data gets a copy of # of the ggplot.data. If the has data it is replaced # by copy so that we do not alter the users data if self.data is None: self.data = plot_data.copy() elif hasattr(self.data, '__call__'): self.data = self.data(plot_data) if not isinstance(self.data, pd.DataFrame): raise PlotnineError( "Data function must return a dataframe") else: self.data = self.data.copy()
python
def generate_data(self, plot_data): """ Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data """ # Each layer that does not have data gets a copy of # of the ggplot.data. If the has data it is replaced # by copy so that we do not alter the users data if self.data is None: self.data = plot_data.copy() elif hasattr(self.data, '__call__'): self.data = self.data(plot_data) if not isinstance(self.data, pd.DataFrame): raise PlotnineError( "Data function must return a dataframe") else: self.data = self.data.copy()
[ "def", "generate_data", "(", "self", ",", "plot_data", ")", ":", "# Each layer that does not have data gets a copy of", "# of the ggplot.data. If the has data it is replaced", "# by copy so that we do not alter the users data", "if", "self", ".", "data", "is", "None", ":", "self"...
Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data
[ "Generate", "data", "to", "be", "used", "by", "this", "layer" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L229-L249
train
214,528
has2k1/plotnine
plotnine/layer.py
layer.layer_mapping
def layer_mapping(self, mapping): """ Return the mappings that are active in this layer Parameters ---------- mapping : aes mappings in the ggplot call Notes ----- Once computed the layer mappings are also stored in self._active_mapping """ # For certain geoms, it is useful to be able to # ignore the default aesthetics and only use those # set in the layer if self.inherit_aes: aesthetics = defaults(self.mapping, mapping) else: aesthetics = self.mapping # drop aesthetic parameters or the calculated aesthetics calculated = set(get_calculated_aes(aesthetics)) d = dict((ae, v) for ae, v in aesthetics.items() if (ae not in self.geom.aes_params) and (ae not in calculated)) self._active_mapping = aes(**d) return self._active_mapping
python
def layer_mapping(self, mapping): """ Return the mappings that are active in this layer Parameters ---------- mapping : aes mappings in the ggplot call Notes ----- Once computed the layer mappings are also stored in self._active_mapping """ # For certain geoms, it is useful to be able to # ignore the default aesthetics and only use those # set in the layer if self.inherit_aes: aesthetics = defaults(self.mapping, mapping) else: aesthetics = self.mapping # drop aesthetic parameters or the calculated aesthetics calculated = set(get_calculated_aes(aesthetics)) d = dict((ae, v) for ae, v in aesthetics.items() if (ae not in self.geom.aes_params) and (ae not in calculated)) self._active_mapping = aes(**d) return self._active_mapping
[ "def", "layer_mapping", "(", "self", ",", "mapping", ")", ":", "# For certain geoms, it is useful to be able to", "# ignore the default aesthetics and only use those", "# set in the layer", "if", "self", ".", "inherit_aes", ":", "aesthetics", "=", "defaults", "(", "self", "...
Return the mappings that are active in this layer Parameters ---------- mapping : aes mappings in the ggplot call Notes ----- Once computed the layer mappings are also stored in self._active_mapping
[ "Return", "the", "mappings", "that", "are", "active", "in", "this", "layer" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L251-L279
train
214,529
has2k1/plotnine
plotnine/layer.py
layer.compute_aesthetics
def compute_aesthetics(self, plot): """ Return a dataframe where the columns match the aesthetic mappings. Transformations like 'factor(cyl)' and other expression evaluation are made in here """ data = self.data aesthetics = self.layer_mapping(plot.mapping) # Override grouping if set in layer. with suppress(KeyError): aesthetics['group'] = self.geom.aes_params['group'] env = EvalEnvironment.capture(eval_env=plot.environment) env = env.with_outer_namespace({'factor': pd.Categorical}) # Using `type` preserves the subclass of pd.DataFrame evaled = type(data)(index=data.index) # If a column name is not in the data, it is evaluated/transformed # in the environment of the call to ggplot for ae, col in aesthetics.items(): if isinstance(col, str): if col in data: evaled[ae] = data[col] else: try: new_val = env.eval(col, inner_namespace=data) except Exception as e: raise PlotnineError( _TPL_EVAL_FAIL.format(ae, col, str(e))) try: evaled[ae] = new_val except Exception as e: raise PlotnineError( _TPL_BAD_EVAL_TYPE.format( ae, col, str(type(new_val)), str(e))) elif pdtypes.is_list_like(col): n = len(col) if len(data) and n != len(data) and n != 1: raise PlotnineError( "Aesthetics must either be length one, " + "or the same length as the data") # An empty dataframe does not admit a scalar value elif len(evaled) and n == 1: col = col[0] evaled[ae] = col elif is_known_scalar(col): if not len(evaled): col = [col] evaled[ae] = col else: msg = "Do not know how to deal with aesthetic '{}'" raise PlotnineError(msg.format(ae)) evaled_aes = aes(**dict((col, col) for col in evaled)) plot.scales.add_defaults(evaled, evaled_aes) if len(data) == 0 and len(evaled) > 0: # No data, and vectors suppled to aesthetics evaled['PANEL'] = 1 else: evaled['PANEL'] = data['PANEL'] self.data = add_group(evaled)
python
def compute_aesthetics(self, plot): """ Return a dataframe where the columns match the aesthetic mappings. Transformations like 'factor(cyl)' and other expression evaluation are made in here """ data = self.data aesthetics = self.layer_mapping(plot.mapping) # Override grouping if set in layer. with suppress(KeyError): aesthetics['group'] = self.geom.aes_params['group'] env = EvalEnvironment.capture(eval_env=plot.environment) env = env.with_outer_namespace({'factor': pd.Categorical}) # Using `type` preserves the subclass of pd.DataFrame evaled = type(data)(index=data.index) # If a column name is not in the data, it is evaluated/transformed # in the environment of the call to ggplot for ae, col in aesthetics.items(): if isinstance(col, str): if col in data: evaled[ae] = data[col] else: try: new_val = env.eval(col, inner_namespace=data) except Exception as e: raise PlotnineError( _TPL_EVAL_FAIL.format(ae, col, str(e))) try: evaled[ae] = new_val except Exception as e: raise PlotnineError( _TPL_BAD_EVAL_TYPE.format( ae, col, str(type(new_val)), str(e))) elif pdtypes.is_list_like(col): n = len(col) if len(data) and n != len(data) and n != 1: raise PlotnineError( "Aesthetics must either be length one, " + "or the same length as the data") # An empty dataframe does not admit a scalar value elif len(evaled) and n == 1: col = col[0] evaled[ae] = col elif is_known_scalar(col): if not len(evaled): col = [col] evaled[ae] = col else: msg = "Do not know how to deal with aesthetic '{}'" raise PlotnineError(msg.format(ae)) evaled_aes = aes(**dict((col, col) for col in evaled)) plot.scales.add_defaults(evaled, evaled_aes) if len(data) == 0 and len(evaled) > 0: # No data, and vectors suppled to aesthetics evaled['PANEL'] = 1 else: evaled['PANEL'] = data['PANEL'] self.data = add_group(evaled)
[ "def", "compute_aesthetics", "(", "self", ",", "plot", ")", ":", "data", "=", "self", ".", "data", "aesthetics", "=", "self", ".", "layer_mapping", "(", "plot", ".", "mapping", ")", "# Override grouping if set in layer.", "with", "suppress", "(", "KeyError", "...
Return a dataframe where the columns match the aesthetic mappings. Transformations like 'factor(cyl)' and other expression evaluation are made in here
[ "Return", "a", "dataframe", "where", "the", "columns", "match", "the", "aesthetic", "mappings", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L281-L348
train
214,530
has2k1/plotnine
plotnine/layer.py
layer.compute_statistic
def compute_statistic(self, layout): """ Compute & return statistics for this layer """ data = self.data if not len(data): return type(data)() params = self.stat.setup_params(data) data = self.stat.use_defaults(data) data = self.stat.setup_data(data) data = self.stat.compute_layer(data, params, layout) self.data = data
python
def compute_statistic(self, layout): """ Compute & return statistics for this layer """ data = self.data if not len(data): return type(data)() params = self.stat.setup_params(data) data = self.stat.use_defaults(data) data = self.stat.setup_data(data) data = self.stat.compute_layer(data, params, layout) self.data = data
[ "def", "compute_statistic", "(", "self", ",", "layout", ")", ":", "data", "=", "self", ".", "data", "if", "not", "len", "(", "data", ")", ":", "return", "type", "(", "data", ")", "(", ")", "params", "=", "self", ".", "stat", ".", "setup_params", "(...
Compute & return statistics for this layer
[ "Compute", "&", "return", "statistics", "for", "this", "layer" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L350-L362
train
214,531
has2k1/plotnine
plotnine/layer.py
layer.map_statistic
def map_statistic(self, plot): """ Mapping aesthetics to computed statistics """ data = self.data if not len(data): return type(data)() # Assemble aesthetics from layer, plot and stat mappings aesthetics = deepcopy(self.mapping) if self.inherit_aes: aesthetics = defaults(aesthetics, plot.mapping) aesthetics = defaults(aesthetics, self.stat.DEFAULT_AES) # The new aesthetics are those that the stat calculates # and have been mapped to with dot dot notation # e.g aes(y='..count..'), y is the new aesthetic and # 'count' is the computed column in data new = {} # {'aesthetic_name': 'calculated_stat'} stat_data = type(data)() stat_namespace = dict(stat=stat) env = plot.environment.with_outer_namespace(stat_namespace) for ae in get_calculated_aes(aesthetics): new[ae] = strip_calculated_markers(aesthetics[ae]) # In conjuction with the pd.concat at the end, # be careful not to create duplicate columns # for cases like y='..y..' if new[ae] != ae: stat_data[ae] = env.eval( new[ae], inner_namespace=data) if not new: return # (see stat_spoke for one exception) if self.stat.retransform: stat_data = plot.scales.transform_df(stat_data) # When there are duplicate columns, we use the computed # ones in stat_data columns = data.columns.difference(stat_data.columns) self.data = pd.concat([data[columns], stat_data], axis=1) # Add any new scales, if needed plot.scales.add_defaults(self.data, new)
python
def map_statistic(self, plot): """ Mapping aesthetics to computed statistics """ data = self.data if not len(data): return type(data)() # Assemble aesthetics from layer, plot and stat mappings aesthetics = deepcopy(self.mapping) if self.inherit_aes: aesthetics = defaults(aesthetics, plot.mapping) aesthetics = defaults(aesthetics, self.stat.DEFAULT_AES) # The new aesthetics are those that the stat calculates # and have been mapped to with dot dot notation # e.g aes(y='..count..'), y is the new aesthetic and # 'count' is the computed column in data new = {} # {'aesthetic_name': 'calculated_stat'} stat_data = type(data)() stat_namespace = dict(stat=stat) env = plot.environment.with_outer_namespace(stat_namespace) for ae in get_calculated_aes(aesthetics): new[ae] = strip_calculated_markers(aesthetics[ae]) # In conjuction with the pd.concat at the end, # be careful not to create duplicate columns # for cases like y='..y..' if new[ae] != ae: stat_data[ae] = env.eval( new[ae], inner_namespace=data) if not new: return # (see stat_spoke for one exception) if self.stat.retransform: stat_data = plot.scales.transform_df(stat_data) # When there are duplicate columns, we use the computed # ones in stat_data columns = data.columns.difference(stat_data.columns) self.data = pd.concat([data[columns], stat_data], axis=1) # Add any new scales, if needed plot.scales.add_defaults(self.data, new)
[ "def", "map_statistic", "(", "self", ",", "plot", ")", ":", "data", "=", "self", ".", "data", "if", "not", "len", "(", "data", ")", ":", "return", "type", "(", "data", ")", "(", ")", "# Assemble aesthetics from layer, plot and stat mappings", "aesthetics", "...
Mapping aesthetics to computed statistics
[ "Mapping", "aesthetics", "to", "computed", "statistics" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L364-L409
train
214,532
has2k1/plotnine
plotnine/layer.py
layer.compute_position
def compute_position(self, layout): """ Compute the position of each geometric object in concert with the other objects in the panel """ params = self.position.setup_params(self.data) data = self.position.setup_data(self.data, params) data = self.position.compute_layer(data, params, layout) self.data = data
python
def compute_position(self, layout): """ Compute the position of each geometric object in concert with the other objects in the panel """ params = self.position.setup_params(self.data) data = self.position.setup_data(self.data, params) data = self.position.compute_layer(data, params, layout) self.data = data
[ "def", "compute_position", "(", "self", ",", "layout", ")", ":", "params", "=", "self", ".", "position", ".", "setup_params", "(", "self", ".", "data", ")", "data", "=", "self", ".", "position", ".", "setup_data", "(", "self", ".", "data", ",", "params...
Compute the position of each geometric object in concert with the other objects in the panel
[ "Compute", "the", "position", "of", "each", "geometric", "object", "in", "concert", "with", "the", "other", "objects", "in", "the", "panel" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L428-L436
train
214,533
has2k1/plotnine
plotnine/scales/range.py
RangeContinuous.train
def train(self, x): """ Train continuous range """ self.range = scale_continuous.train(x, self.range)
python
def train(self, x): """ Train continuous range """ self.range = scale_continuous.train(x, self.range)
[ "def", "train", "(", "self", ",", "x", ")", ":", "self", ".", "range", "=", "scale_continuous", ".", "train", "(", "x", ",", "self", ".", "range", ")" ]
Train continuous range
[ "Train", "continuous", "range" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/range.py#L28-L32
train
214,534
has2k1/plotnine
plotnine/scales/range.py
RangeDiscrete.train
def train(self, x, drop=False, na_rm=False): """ Train discrete range """ self.range = scale_discrete.train(x, self.range, drop, na_rm=na_rm)
python
def train(self, x, drop=False, na_rm=False): """ Train discrete range """ self.range = scale_discrete.train(x, self.range, drop, na_rm=na_rm)
[ "def", "train", "(", "self", ",", "x", ",", "drop", "=", "False", ",", "na_rm", "=", "False", ")", ":", "self", ".", "range", "=", "scale_discrete", ".", "train", "(", "x", ",", "self", ".", "range", ",", "drop", ",", "na_rm", "=", "na_rm", ")" ]
Train discrete range
[ "Train", "discrete", "range" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/range.py#L39-L43
train
214,535
has2k1/plotnine
plotnine/utils.py
_margins
def _margins(vars, margins=True): """ Figure out margining variables. Given the variables that form the rows and columns, and a set of desired margins, works out which ones are possible. Variables that can't be margined over are dropped silently. Parameters ---------- vars : list variable names for rows and columns margins : bool | list If true, margins over all vars, otherwise only those listed Return ------ out : list All the margins to create. """ if margins is False: return [] def fn(_vars): "The margin variables for a given row or column" # The first item is and empty list for no margins dim_margins = [[]] # for each wanted variable, couple it with # all variables to the right for i, u in enumerate(_vars): if margins is True or u in margins: lst = [u] + [v for v in _vars[i+1:]] dim_margins.append(lst) return dim_margins # Margin variables for rows and columns row_margins = fn(vars[0]) col_margins = fn(vars[1]) # Cross the two lst = list(itertools.product(col_margins, row_margins)) # Clean up -- merge the row and column variables pretty = [] for c, r in lst: pretty.append(r + c) return pretty
python
def _margins(vars, margins=True): """ Figure out margining variables. Given the variables that form the rows and columns, and a set of desired margins, works out which ones are possible. Variables that can't be margined over are dropped silently. Parameters ---------- vars : list variable names for rows and columns margins : bool | list If true, margins over all vars, otherwise only those listed Return ------ out : list All the margins to create. """ if margins is False: return [] def fn(_vars): "The margin variables for a given row or column" # The first item is and empty list for no margins dim_margins = [[]] # for each wanted variable, couple it with # all variables to the right for i, u in enumerate(_vars): if margins is True or u in margins: lst = [u] + [v for v in _vars[i+1:]] dim_margins.append(lst) return dim_margins # Margin variables for rows and columns row_margins = fn(vars[0]) col_margins = fn(vars[1]) # Cross the two lst = list(itertools.product(col_margins, row_margins)) # Clean up -- merge the row and column variables pretty = [] for c, r in lst: pretty.append(r + c) return pretty
[ "def", "_margins", "(", "vars", ",", "margins", "=", "True", ")", ":", "if", "margins", "is", "False", ":", "return", "[", "]", "def", "fn", "(", "_vars", ")", ":", "\"The margin variables for a given row or column\"", "# The first item is and empty list for no marg...
Figure out margining variables. Given the variables that form the rows and columns, and a set of desired margins, works out which ones are possible. Variables that can't be margined over are dropped silently. Parameters ---------- vars : list variable names for rows and columns margins : bool | list If true, margins over all vars, otherwise only those listed Return ------ out : list All the margins to create.
[ "Figure", "out", "margining", "variables", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L143-L191
train
214,536
has2k1/plotnine
plotnine/utils.py
add_margins
def add_margins(df, vars, margins=True): """ Add margins to a data frame. All margining variables will be converted to factors. Parameters ---------- df : dataframe input data frame vars : list a list of 2 lists | tuples vectors giving the variables in each dimension margins : bool | list variable names to compute margins for. True will compute all possible margins. """ margin_vars = _margins(vars, margins) if not margin_vars: return df # create margin dataframes margin_dfs = [df] for vlst in margin_vars[1:]: dfx = df.copy() for v in vlst: dfx.loc[0:, v] = '(all)' margin_dfs.append(dfx) merged = pd.concat(margin_dfs, axis=0) merged.reset_index(drop=True, inplace=True) # All margin columns become categoricals. The margin indicator # (all) needs to be added as the last level of the categories. categories = {} for v in itertools.chain(*vars): col = df[v] if not pdtypes.is_categorical_dtype(df[v].dtype): col = pd.Categorical(df[v]) categories[v] = col.categories if '(all)' not in categories[v]: categories[v] = categories[v].insert( len(categories[v]), '(all)') for v in merged.columns.intersection(set(categories)): merged[v] = merged[v].astype( pdtypes.CategoricalDtype(categories[v])) return merged
python
def add_margins(df, vars, margins=True): """ Add margins to a data frame. All margining variables will be converted to factors. Parameters ---------- df : dataframe input data frame vars : list a list of 2 lists | tuples vectors giving the variables in each dimension margins : bool | list variable names to compute margins for. True will compute all possible margins. """ margin_vars = _margins(vars, margins) if not margin_vars: return df # create margin dataframes margin_dfs = [df] for vlst in margin_vars[1:]: dfx = df.copy() for v in vlst: dfx.loc[0:, v] = '(all)' margin_dfs.append(dfx) merged = pd.concat(margin_dfs, axis=0) merged.reset_index(drop=True, inplace=True) # All margin columns become categoricals. The margin indicator # (all) needs to be added as the last level of the categories. categories = {} for v in itertools.chain(*vars): col = df[v] if not pdtypes.is_categorical_dtype(df[v].dtype): col = pd.Categorical(df[v]) categories[v] = col.categories if '(all)' not in categories[v]: categories[v] = categories[v].insert( len(categories[v]), '(all)') for v in merged.columns.intersection(set(categories)): merged[v] = merged[v].astype( pdtypes.CategoricalDtype(categories[v])) return merged
[ "def", "add_margins", "(", "df", ",", "vars", ",", "margins", "=", "True", ")", ":", "margin_vars", "=", "_margins", "(", "vars", ",", "margins", ")", "if", "not", "margin_vars", ":", "return", "df", "# create margin dataframes", "margin_dfs", "=", "[", "d...
Add margins to a data frame. All margining variables will be converted to factors. Parameters ---------- df : dataframe input data frame vars : list a list of 2 lists | tuples vectors giving the variables in each dimension margins : bool | list variable names to compute margins for. True will compute all possible margins.
[ "Add", "margins", "to", "a", "data", "frame", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L194-L244
train
214,537
has2k1/plotnine
plotnine/utils.py
_id_var
def _id_var(x, drop=False): """ Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels """ if len(x) == 0: return [] categorical = pdtypes.is_categorical_dtype(x) if categorical: if drop: x = x.cat.remove_unused_categories() lst = list(x.cat.codes + 1) else: has_nan = any(np.isnan(i) for i in x if isinstance(i, float)) if has_nan: # NaNs are -1, we give them the highest code nan_code = -1 new_nan_code = np.max(x.cat.codes) + 1 lst = [val if val != nan_code else new_nan_code for val in x] else: lst = list(x.cat.codes + 1) else: try: levels = np.sort(np.unique(x)) except TypeError: # x probably has NANs levels = multitype_sort(set(x)) lst = match(x, levels) lst = [item + 1 for item in lst] return lst
python
def _id_var(x, drop=False): """ Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels """ if len(x) == 0: return [] categorical = pdtypes.is_categorical_dtype(x) if categorical: if drop: x = x.cat.remove_unused_categories() lst = list(x.cat.codes + 1) else: has_nan = any(np.isnan(i) for i in x if isinstance(i, float)) if has_nan: # NaNs are -1, we give them the highest code nan_code = -1 new_nan_code = np.max(x.cat.codes) + 1 lst = [val if val != nan_code else new_nan_code for val in x] else: lst = list(x.cat.codes + 1) else: try: levels = np.sort(np.unique(x)) except TypeError: # x probably has NANs levels = multitype_sort(set(x)) lst = match(x, levels) lst = [item + 1 for item in lst] return lst
[ "def", "_id_var", "(", "x", ",", "drop", "=", "False", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "return", "[", "]", "categorical", "=", "pdtypes", ".", "is_categorical_dtype", "(", "x", ")", "if", "categorical", ":", "if", "drop", ":",...
Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels
[ "Assign", "ids", "to", "items", "in", "x", ".", "If", "two", "items", "are", "the", "same", "they", "get", "the", "same", "id", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L299-L339
train
214,538
has2k1/plotnine
plotnine/utils.py
join_keys
def join_keys(x, y, by=None): """ Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The values of both keys are arrays with integer elements. Identical rows in x and y dataframes would have the same key in the output. The key elements start at 1. """ if by is None: by = slice(None, None, None) if isinstance(by, tuple): by = list(by) joint = x[by].append(y[by], ignore_index=True) keys = ninteraction(joint, drop=True) keys = np.asarray(keys) nx, ny = len(x), len(y) return {'x': keys[np.arange(nx)], 'y': keys[nx + np.arange(ny)]}
python
def join_keys(x, y, by=None): """ Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The values of both keys are arrays with integer elements. Identical rows in x and y dataframes would have the same key in the output. The key elements start at 1. """ if by is None: by = slice(None, None, None) if isinstance(by, tuple): by = list(by) joint = x[by].append(y[by], ignore_index=True) keys = ninteraction(joint, drop=True) keys = np.asarray(keys) nx, ny = len(x), len(y) return {'x': keys[np.arange(nx)], 'y': keys[nx + np.arange(ny)]}
[ "def", "join_keys", "(", "x", ",", "y", ",", "by", "=", "None", ")", ":", "if", "by", "is", "None", ":", "by", "=", "slice", "(", "None", ",", "None", ",", "None", ")", "if", "isinstance", "(", "by", ",", "tuple", ")", ":", "by", "=", "list",...
Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The values of both keys are arrays with integer elements. Identical rows in x and y dataframes would have the same key in the output. The key elements start at 1.
[ "Join", "keys", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L342-L374
train
214,539
has2k1/plotnine
plotnine/utils.py
uniquecols
def uniquecols(df): """ Return unique columns This is used for figuring out which columns are constant within a group """ bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0) df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True) return df
python
def uniquecols(df): """ Return unique columns This is used for figuring out which columns are constant within a group """ bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0) df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True) return df
[ "def", "uniquecols", "(", "df", ")", ":", "bool_idx", "=", "df", ".", "apply", "(", "lambda", "col", ":", "len", "(", "np", ".", "unique", "(", "col", ")", ")", "==", "1", ",", "axis", "=", "0", ")", "df", "=", "df", ".", "loc", "[", ":", "...
Return unique columns This is used for figuring out which columns are constant within a group
[ "Return", "unique", "columns" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L386-L395
train
214,540
has2k1/plotnine
plotnine/utils.py
defaults
def defaults(d1, d2): """ Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ------- out : dict | dataframe Result of adding default values type of d1 """ d1 = d1.copy() tolist = isinstance(d2, pd.DataFrame) keys = (k for k in d2 if k not in d1) for k in keys: if tolist: d1[k] = d2[k].tolist() else: d1[k] = d2[k] return d1
python
def defaults(d1, d2): """ Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ------- out : dict | dataframe Result of adding default values type of d1 """ d1 = d1.copy() tolist = isinstance(d2, pd.DataFrame) keys = (k for k in d2 if k not in d1) for k in keys: if tolist: d1[k] = d2[k].tolist() else: d1[k] = d2[k] return d1
[ "def", "defaults", "(", "d1", ",", "d2", ")", ":", "d1", "=", "d1", ".", "copy", "(", ")", "tolist", "=", "isinstance", "(", "d2", ",", "pd", ".", "DataFrame", ")", "keys", "=", "(", "k", "for", "k", "in", "d2", "if", "k", "not", "in", "d1", ...
Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ------- out : dict | dataframe Result of adding default values type of d1
[ "Update", "a", "copy", "of", "d1", "with", "the", "contents", "of", "d2", "that", "are", "not", "in", "d1", ".", "d1", "and", "d2", "are", "dictionary", "like", "objects", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L398-L424
train
214,541
has2k1/plotnine
plotnine/utils.py
jitter
def jitter(x, factor=1, amount=None, random_state=None): """ Add a small amount of noise to values in an array_like Parameters ---------- x : array_like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the `amount`. If the `amount` is given then the `factor` has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to apply to the values. If `0` then ``amount = factor * z/50``. If `None` then ``amount = factor * d/5``, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional Seed or Random number generator to use. If ``None``, then numpy global generator :class:`numpy.random` is used. References: - Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) *Graphical Methods for Data Analysis*. Wadsworth; figures 2.8, 4.22, 5.4. """ if len(x) == 0: return x if random_state is None: random_state = np.random elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) x = np.asarray(x) try: z = np.ptp(x[np.isfinite(x)]) except IndexError: z = 0 if z == 0: z = np.abs(np.min(x)) if z == 0: z = 1 if amount is None: _x = np.round(x, 3-np.int(np.floor(np.log10(z)))).astype(np.int) xx = np.unique(np.sort(_x)) d = np.diff(xx) if len(d): d = d.min() elif xx != 0: d = xx/10. else: d = z/10 amount = factor/5. * abs(d) elif amount == 0: amount = factor * (z / 50.) return x + random_state.uniform(-amount, amount, len(x))
python
def jitter(x, factor=1, amount=None, random_state=None): """ Add a small amount of noise to values in an array_like Parameters ---------- x : array_like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the `amount`. If the `amount` is given then the `factor` has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to apply to the values. If `0` then ``amount = factor * z/50``. If `None` then ``amount = factor * d/5``, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional Seed or Random number generator to use. If ``None``, then numpy global generator :class:`numpy.random` is used. References: - Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) *Graphical Methods for Data Analysis*. Wadsworth; figures 2.8, 4.22, 5.4. """ if len(x) == 0: return x if random_state is None: random_state = np.random elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) x = np.asarray(x) try: z = np.ptp(x[np.isfinite(x)]) except IndexError: z = 0 if z == 0: z = np.abs(np.min(x)) if z == 0: z = 1 if amount is None: _x = np.round(x, 3-np.int(np.floor(np.log10(z)))).astype(np.int) xx = np.unique(np.sort(_x)) d = np.diff(xx) if len(d): d = d.min() elif xx != 0: d = xx/10. else: d = z/10 amount = factor/5. * abs(d) elif amount == 0: amount = factor * (z / 50.) return x + random_state.uniform(-amount, amount, len(x))
[ "def", "jitter", "(", "x", ",", "factor", "=", "1", ",", "amount", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "return", "x", "if", "random_state", "is", "None", ":", "random_state", "=", "...
Add a small amount of noise to values in an array_like Parameters ---------- x : array_like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the `amount`. If the `amount` is given then the `factor` has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to apply to the values. If `0` then ``amount = factor * z/50``. If `None` then ``amount = factor * d/5``, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional Seed or Random number generator to use. If ``None``, then numpy global generator :class:`numpy.random` is used. References: - Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) *Graphical Methods for Data Analysis*. Wadsworth; figures 2.8, 4.22, 5.4.
[ "Add", "a", "small", "amount", "of", "noise", "to", "values", "in", "an", "array_like" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L427-L489
train
214,542
has2k1/plotnine
plotnine/utils.py
remove_missing
def remove_missing(df, na_rm=False, vars=None, name='', finite=False): """ Convenience function to remove missing values from a dataframe Parameters ---------- df : dataframe na_rm : bool If False remove all non-complete rows with and show warning. vars : list-like columns to act on name : str Name of calling method for a more informative message finite : bool If True replace the infinite values in addition to the NaNs """ n = len(df) if vars is None: vars = df.columns else: vars = df.columns.intersection(vars) if finite: lst = [np.inf, -np.inf] to_replace = {v: lst for v in vars} df.replace(to_replace, np.nan, inplace=True) txt = 'non-finite' else: txt = 'missing' df = df.dropna(subset=vars) df.reset_index(drop=True, inplace=True) if len(df) < n and not na_rm: msg = '{} : Removed {} rows containing {} values.' warn(msg.format(name, n-len(df), txt), PlotnineWarning, stacklevel=3) return df
python
def remove_missing(df, na_rm=False, vars=None, name='', finite=False): """ Convenience function to remove missing values from a dataframe Parameters ---------- df : dataframe na_rm : bool If False remove all non-complete rows with and show warning. vars : list-like columns to act on name : str Name of calling method for a more informative message finite : bool If True replace the infinite values in addition to the NaNs """ n = len(df) if vars is None: vars = df.columns else: vars = df.columns.intersection(vars) if finite: lst = [np.inf, -np.inf] to_replace = {v: lst for v in vars} df.replace(to_replace, np.nan, inplace=True) txt = 'non-finite' else: txt = 'missing' df = df.dropna(subset=vars) df.reset_index(drop=True, inplace=True) if len(df) < n and not na_rm: msg = '{} : Removed {} rows containing {} values.' warn(msg.format(name, n-len(df), txt), PlotnineWarning, stacklevel=3) return df
[ "def", "remove_missing", "(", "df", ",", "na_rm", "=", "False", ",", "vars", "=", "None", ",", "name", "=", "''", ",", "finite", "=", "False", ")", ":", "n", "=", "len", "(", "df", ")", "if", "vars", "is", "None", ":", "vars", "=", "df", ".", ...
Convenience function to remove missing values from a dataframe Parameters ---------- df : dataframe na_rm : bool If False remove all non-complete rows with and show warning. vars : list-like columns to act on name : str Name of calling method for a more informative message finite : bool If True replace the infinite values in addition to the NaNs
[ "Convenience", "function", "to", "remove", "missing", "values", "from", "a", "dataframe" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L492-L528
train
214,543
has2k1/plotnine
plotnine/utils.py
to_rgba
def to_rgba(colors, alpha): """ Covert hex colors to rgba values. Parameters ---------- colors : iterable | str colors to convert alphas : iterable | float alpha values Returns ------- out : ndarray | tuple rgba color(s) Notes ----- Matplotlib plotting functions only accept scalar alpha values. Hence no two objects with different alpha values may be plotted in one call. This would make plots with continuous alpha values innefficient. However :), the colors can be rgba hex values or list-likes and the alpha dimension will be respected. """ def is_iterable(var): return cbook.iterable(var) and not is_string(var) def has_alpha(c): if isinstance(c, tuple): if len(c) == 4: return True elif isinstance(c, str): if c[0] == '#' and len(c) == 9: return True return False def no_color(c): return c is None or c == '' or c.lower() == 'none' def to_rgba_hex(c, a): """ Conver rgb color to rgba hex value If color c has an alpha channel, then alpha value a is ignored """ _has_alpha = has_alpha(c) c = mcolors.to_hex(c, keep_alpha=_has_alpha) if not _has_alpha: arr = colorConverter.to_rgba(c, a) return mcolors.to_hex(arr, keep_alpha=True) return c if is_iterable(colors): if all(no_color(c) for c in colors): return 'none' if is_iterable(alpha): return [to_rgba_hex(c, a) for c, a in zip(colors, alpha)] else: return [to_rgba_hex(c, alpha) for c in colors] else: if no_color(colors): return colors if is_iterable(alpha): return [to_rgba_hex(colors, a) for a in alpha] else: return to_rgba_hex(colors, alpha)
python
def to_rgba(colors, alpha): """ Covert hex colors to rgba values. Parameters ---------- colors : iterable | str colors to convert alphas : iterable | float alpha values Returns ------- out : ndarray | tuple rgba color(s) Notes ----- Matplotlib plotting functions only accept scalar alpha values. Hence no two objects with different alpha values may be plotted in one call. This would make plots with continuous alpha values innefficient. However :), the colors can be rgba hex values or list-likes and the alpha dimension will be respected. """ def is_iterable(var): return cbook.iterable(var) and not is_string(var) def has_alpha(c): if isinstance(c, tuple): if len(c) == 4: return True elif isinstance(c, str): if c[0] == '#' and len(c) == 9: return True return False def no_color(c): return c is None or c == '' or c.lower() == 'none' def to_rgba_hex(c, a): """ Conver rgb color to rgba hex value If color c has an alpha channel, then alpha value a is ignored """ _has_alpha = has_alpha(c) c = mcolors.to_hex(c, keep_alpha=_has_alpha) if not _has_alpha: arr = colorConverter.to_rgba(c, a) return mcolors.to_hex(arr, keep_alpha=True) return c if is_iterable(colors): if all(no_color(c) for c in colors): return 'none' if is_iterable(alpha): return [to_rgba_hex(c, a) for c, a in zip(colors, alpha)] else: return [to_rgba_hex(c, alpha) for c in colors] else: if no_color(colors): return colors if is_iterable(alpha): return [to_rgba_hex(colors, a) for a in alpha] else: return to_rgba_hex(colors, alpha)
[ "def", "to_rgba", "(", "colors", ",", "alpha", ")", ":", "def", "is_iterable", "(", "var", ")", ":", "return", "cbook", ".", "iterable", "(", "var", ")", "and", "not", "is_string", "(", "var", ")", "def", "has_alpha", "(", "c", ")", ":", "if", "isi...
Covert hex colors to rgba values. Parameters ---------- colors : iterable | str colors to convert alphas : iterable | float alpha values Returns ------- out : ndarray | tuple rgba color(s) Notes ----- Matplotlib plotting functions only accept scalar alpha values. Hence no two objects with different alpha values may be plotted in one call. This would make plots with continuous alpha values innefficient. However :), the colors can be rgba hex values or list-likes and the alpha dimension will be respected.
[ "Covert", "hex", "colors", "to", "rgba", "values", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L531-L601
train
214,544
has2k1/plotnine
plotnine/utils.py
groupby_apply
def groupby_apply(df, cols, func, *args, **kwargs): """ Groupby cols and call the function fn on each grouped dataframe. Parameters ---------- cols : str | list of str columns to groupby func : function function to call on the grouped data *args : tuple positional parameters to pass to func **kwargs : dict keyword parameter to pass to func This is meant to avoid pandas df.groupby('col').apply(fn, *args), as it calls fn twice on the first dataframe. If the nested code also does the same thing, it can be very expensive """ try: axis = kwargs.pop('axis') except KeyError: axis = 0 lst = [] for _, d in df.groupby(cols): # function fn should be free to modify dataframe d, therefore # do not mark d as a slice of df i.e no SettingWithCopyWarning lst.append(func(d, *args, **kwargs)) return pd.concat(lst, axis=axis, ignore_index=True)
python
def groupby_apply(df, cols, func, *args, **kwargs): """ Groupby cols and call the function fn on each grouped dataframe. Parameters ---------- cols : str | list of str columns to groupby func : function function to call on the grouped data *args : tuple positional parameters to pass to func **kwargs : dict keyword parameter to pass to func This is meant to avoid pandas df.groupby('col').apply(fn, *args), as it calls fn twice on the first dataframe. If the nested code also does the same thing, it can be very expensive """ try: axis = kwargs.pop('axis') except KeyError: axis = 0 lst = [] for _, d in df.groupby(cols): # function fn should be free to modify dataframe d, therefore # do not mark d as a slice of df i.e no SettingWithCopyWarning lst.append(func(d, *args, **kwargs)) return pd.concat(lst, axis=axis, ignore_index=True)
[ "def", "groupby_apply", "(", "df", ",", "cols", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "axis", "=", "kwargs", ".", "pop", "(", "'axis'", ")", "except", "KeyError", ":", "axis", "=", "0", "lst", "=", "[", "...
Groupby cols and call the function fn on each grouped dataframe. Parameters ---------- cols : str | list of str columns to groupby func : function function to call on the grouped data *args : tuple positional parameters to pass to func **kwargs : dict keyword parameter to pass to func This is meant to avoid pandas df.groupby('col').apply(fn, *args), as it calls fn twice on the first dataframe. If the nested code also does the same thing, it can be very expensive
[ "Groupby", "cols", "and", "call", "the", "function", "fn", "on", "each", "grouped", "dataframe", "." ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L604-L633
train
214,545
has2k1/plotnine
plotnine/utils.py
pivot_apply
def pivot_apply(df, column, index, func, *args, **kwargs): """ Apply a function to each group of a column The function is kind of equivalent to R's *tapply*. Parameters ---------- df : dataframe Dataframe to be pivoted column : str Column to apply function to. index : str Column that will be grouped on (and whose unique values will make up the index of the returned dataframe) func : function Function to apply to each column group. It *should* return a single value. *args : tuple Arguments to ``func`` **kwargs : dict Keyword arguments to ``func`` Returns ------- out : dataframe Dataframe with index ``index`` and column ``column`` of computed/aggregate values . """ def _func(x): return func(x, *args, **kwargs) return df.pivot_table(column, index, aggfunc=_func)[column]
python
def pivot_apply(df, column, index, func, *args, **kwargs): """ Apply a function to each group of a column The function is kind of equivalent to R's *tapply*. Parameters ---------- df : dataframe Dataframe to be pivoted column : str Column to apply function to. index : str Column that will be grouped on (and whose unique values will make up the index of the returned dataframe) func : function Function to apply to each column group. It *should* return a single value. *args : tuple Arguments to ``func`` **kwargs : dict Keyword arguments to ``func`` Returns ------- out : dataframe Dataframe with index ``index`` and column ``column`` of computed/aggregate values . """ def _func(x): return func(x, *args, **kwargs) return df.pivot_table(column, index, aggfunc=_func)[column]
[ "def", "pivot_apply", "(", "df", ",", "column", ",", "index", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_func", "(", "x", ")", ":", "return", "func", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", "r...
Apply a function to each group of a column The function is kind of equivalent to R's *tapply*. Parameters ---------- df : dataframe Dataframe to be pivoted column : str Column to apply function to. index : str Column that will be grouped on (and whose unique values will make up the index of the returned dataframe) func : function Function to apply to each column group. It *should* return a single value. *args : tuple Arguments to ``func`` **kwargs : dict Keyword arguments to ``func`` Returns ------- out : dataframe Dataframe with index ``index`` and column ``column`` of computed/aggregate values .
[ "Apply", "a", "function", "to", "each", "group", "of", "a", "column" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L636-L668
train
214,546
has2k1/plotnine
plotnine/utils.py
copy_keys
def copy_keys(source, destination, keys=None): """ Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()` """ if keys is None: keys = destination.keys() for k in set(source) & set(keys): destination[k] = source[k] return destination
python
def copy_keys(source, destination, keys=None): """ Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()` """ if keys is None: keys = destination.keys() for k in set(source) & set(keys): destination[k] = source[k] return destination
[ "def", "copy_keys", "(", "source", ",", "destination", ",", "keys", "=", "None", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "destination", ".", "keys", "(", ")", "for", "k", "in", "set", "(", "source", ")", "&", "set", "(", "keys", "...
Add keys in source to destination Parameters ---------- source : dict destination: dict keys : None | iterable The keys in source to be copied into destination. If None, then `keys = destination.keys()`
[ "Add", "keys", "in", "source", "to", "destination" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L766-L784
train
214,547
has2k1/plotnine
plotnine/utils.py
alias
def alias(name, class_object): """ Create an alias of a class object The objective of this method is to have an alias that is Registered. i.e If we have class_b = class_a Makes `class_b` an alias of `class_a`, but if `class_a` is registered by its metaclass, `class_b` is not. The solution alias('class_b', class_a) is equivalent to: class_b = class_a Register['class_b'] = class_a """ module = inspect.getmodule(class_object) module.__dict__[name] = class_object if isinstance(class_object, Registry): Registry[name] = class_object
python
def alias(name, class_object): """ Create an alias of a class object The objective of this method is to have an alias that is Registered. i.e If we have class_b = class_a Makes `class_b` an alias of `class_a`, but if `class_a` is registered by its metaclass, `class_b` is not. The solution alias('class_b', class_a) is equivalent to: class_b = class_a Register['class_b'] = class_a """ module = inspect.getmodule(class_object) module.__dict__[name] = class_object if isinstance(class_object, Registry): Registry[name] = class_object
[ "def", "alias", "(", "name", ",", "class_object", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "class_object", ")", "module", ".", "__dict__", "[", "name", "]", "=", "class_object", "if", "isinstance", "(", "class_object", ",", "Registry", ")...
Create an alias of a class object The objective of this method is to have an alias that is Registered. i.e If we have class_b = class_a Makes `class_b` an alias of `class_a`, but if `class_a` is registered by its metaclass, `class_b` is not. The solution alias('class_b', class_a) is equivalent to: class_b = class_a Register['class_b'] = class_a
[ "Create", "an", "alias", "of", "a", "class", "object" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L881-L904
train
214,548
has2k1/plotnine
plotnine/utils.py
get_kwarg_names
def get_kwarg_names(func): """ Return a list of valid kwargs to function func """ sig = inspect.signature(func) kwonlyargs = [p.name for p in sig.parameters.values() if p.default is not p.empty] return kwonlyargs
python
def get_kwarg_names(func): """ Return a list of valid kwargs to function func """ sig = inspect.signature(func) kwonlyargs = [p.name for p in sig.parameters.values() if p.default is not p.empty] return kwonlyargs
[ "def", "get_kwarg_names", "(", "func", ")", ":", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "kwonlyargs", "=", "[", "p", ".", "name", "for", "p", "in", "sig", ".", "parameters", ".", "values", "(", ")", "if", "p", ".", "default", "i...
Return a list of valid kwargs to function func
[ "Return", "a", "list", "of", "valid", "kwargs", "to", "function", "func" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L907-L914
train
214,549
has2k1/plotnine
plotnine/utils.py
get_valid_kwargs
def get_valid_kwargs(func, potential_kwargs): """ Return valid kwargs to function func """ kwargs = {} for name in get_kwarg_names(func): with suppress(KeyError): kwargs[name] = potential_kwargs[name] return kwargs
python
def get_valid_kwargs(func, potential_kwargs): """ Return valid kwargs to function func """ kwargs = {} for name in get_kwarg_names(func): with suppress(KeyError): kwargs[name] = potential_kwargs[name] return kwargs
[ "def", "get_valid_kwargs", "(", "func", ",", "potential_kwargs", ")", ":", "kwargs", "=", "{", "}", "for", "name", "in", "get_kwarg_names", "(", "func", ")", ":", "with", "suppress", "(", "KeyError", ")", ":", "kwargs", "[", "name", "]", "=", "potential_...
Return valid kwargs to function func
[ "Return", "valid", "kwargs", "to", "function", "func" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L917-L925
train
214,550
has2k1/plotnine
plotnine/utils.py
copy_missing_columns
def copy_missing_columns(df, ref_df): """ Copy missing columns from ref_df to df If df and ref_df are the same length, the columns are copied in the entirety. If the length ofref_df is a divisor of the length of df, then the values of the columns from ref_df are repeated. Otherwise if not the same length, df gets a column where all elements are the same as the first element in ref_df Parameters ---------- df : dataframe Dataframe to which columns will be added ref_df : dataframe Dataframe from which columns will be copied """ cols = ref_df.columns.difference(df.columns) _loc = ref_df.columns.get_loc l1, l2 = len(df), len(ref_df) if l1 >= l2 and l1 % l2 == 0: idx = np.tile(range(l2), l1 // l2) else: idx = np.repeat(0, l1) for col in cols: df[col] = ref_df.iloc[idx, _loc(col)].values
python
def copy_missing_columns(df, ref_df): """ Copy missing columns from ref_df to df If df and ref_df are the same length, the columns are copied in the entirety. If the length ofref_df is a divisor of the length of df, then the values of the columns from ref_df are repeated. Otherwise if not the same length, df gets a column where all elements are the same as the first element in ref_df Parameters ---------- df : dataframe Dataframe to which columns will be added ref_df : dataframe Dataframe from which columns will be copied """ cols = ref_df.columns.difference(df.columns) _loc = ref_df.columns.get_loc l1, l2 = len(df), len(ref_df) if l1 >= l2 and l1 % l2 == 0: idx = np.tile(range(l2), l1 // l2) else: idx = np.repeat(0, l1) for col in cols: df[col] = ref_df.iloc[idx, _loc(col)].values
[ "def", "copy_missing_columns", "(", "df", ",", "ref_df", ")", ":", "cols", "=", "ref_df", ".", "columns", ".", "difference", "(", "df", ".", "columns", ")", "_loc", "=", "ref_df", ".", "columns", ".", "get_loc", "l1", ",", "l2", "=", "len", "(", "df"...
Copy missing columns from ref_df to df If df and ref_df are the same length, the columns are copied in the entirety. If the length ofref_df is a divisor of the length of df, then the values of the columns from ref_df are repeated. Otherwise if not the same length, df gets a column where all elements are the same as the first element in ref_df Parameters ---------- df : dataframe Dataframe to which columns will be added ref_df : dataframe Dataframe from which columns will be copied
[ "Copy", "missing", "columns", "from", "ref_df", "to", "df" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L928-L958
train
214,551
has2k1/plotnine
plotnine/utils.py
data_mapping_as_kwargs
def data_mapping_as_kwargs(args, kwargs): """ Return kwargs with the mapping and data values Parameters ---------- args : tuple Arguments to :class:`geom` or :class:`stat`. kwargs : dict Keyword arguments to :class:`geom` or :class:`stat`. Returns ------- out : dict kwargs that includes 'data' and 'mapping' keys. """ # No need to be strict about the aesthetic superclass aes = dict mapping, data = aes(), None aes_err = ("Found more than one aes argument. " "Expecting zero or one") data_err = "More than one dataframe argument." # check args # for arg in args: if isinstance(arg, aes) and mapping: raise PlotnineError(aes_err) if isinstance(arg, pd.DataFrame) and data: raise PlotnineError(data_err) if isinstance(arg, aes): mapping = arg elif isinstance(arg, pd.DataFrame): data = arg else: msg = "Unknown argument of type '{0}'." raise PlotnineError(msg.format(type(arg))) # check kwargs # # kwargs mapping has precedence over that in args if 'mapping' not in kwargs: kwargs['mapping'] = mapping if data is not None and 'data' in kwargs: raise PlotnineError(data_err) elif 'data' not in kwargs: kwargs['data'] = data duplicates = set(kwargs['mapping']) & set(kwargs) if duplicates: msg = "Aesthetics {} specified two times." raise PlotnineError(msg.format(duplicates)) return kwargs
python
def data_mapping_as_kwargs(args, kwargs): """ Return kwargs with the mapping and data values Parameters ---------- args : tuple Arguments to :class:`geom` or :class:`stat`. kwargs : dict Keyword arguments to :class:`geom` or :class:`stat`. Returns ------- out : dict kwargs that includes 'data' and 'mapping' keys. """ # No need to be strict about the aesthetic superclass aes = dict mapping, data = aes(), None aes_err = ("Found more than one aes argument. " "Expecting zero or one") data_err = "More than one dataframe argument." # check args # for arg in args: if isinstance(arg, aes) and mapping: raise PlotnineError(aes_err) if isinstance(arg, pd.DataFrame) and data: raise PlotnineError(data_err) if isinstance(arg, aes): mapping = arg elif isinstance(arg, pd.DataFrame): data = arg else: msg = "Unknown argument of type '{0}'." raise PlotnineError(msg.format(type(arg))) # check kwargs # # kwargs mapping has precedence over that in args if 'mapping' not in kwargs: kwargs['mapping'] = mapping if data is not None and 'data' in kwargs: raise PlotnineError(data_err) elif 'data' not in kwargs: kwargs['data'] = data duplicates = set(kwargs['mapping']) & set(kwargs) if duplicates: msg = "Aesthetics {} specified two times." raise PlotnineError(msg.format(duplicates)) return kwargs
[ "def", "data_mapping_as_kwargs", "(", "args", ",", "kwargs", ")", ":", "# No need to be strict about the aesthetic superclass", "aes", "=", "dict", "mapping", ",", "data", "=", "aes", "(", ")", ",", "None", "aes_err", "=", "(", "\"Found more than one aes argument. \""...
Return kwargs with the mapping and data values Parameters ---------- args : tuple Arguments to :class:`geom` or :class:`stat`. kwargs : dict Keyword arguments to :class:`geom` or :class:`stat`. Returns ------- out : dict kwargs that includes 'data' and 'mapping' keys.
[ "Return", "kwargs", "with", "the", "mapping", "and", "data", "values" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L961-L1013
train
214,552
has2k1/plotnine
plotnine/utils.py
resolution
def resolution(x, zero=True): """ Compute the resolution of a data vector Resolution is smallest non-zero distance between adjacent values Parameters ---------- x : 1D array-like zero : Boolean Whether to include zero values in the computation Result ------ res : resolution of x If x is an integer array, then the resolution is 1 """ x = np.asarray(x) # (unsigned) integers or an effective range of zero _x = x[~np.isnan(x)] _x = (x.min(), x.max()) if x.dtype.kind in ('i', 'u') or zero_range(_x): return 1 x = np.unique(x) if zero: x = np.unique(np.hstack([0, x])) return np.min(np.diff(np.sort(x)))
python
def resolution(x, zero=True): """ Compute the resolution of a data vector Resolution is smallest non-zero distance between adjacent values Parameters ---------- x : 1D array-like zero : Boolean Whether to include zero values in the computation Result ------ res : resolution of x If x is an integer array, then the resolution is 1 """ x = np.asarray(x) # (unsigned) integers or an effective range of zero _x = x[~np.isnan(x)] _x = (x.min(), x.max()) if x.dtype.kind in ('i', 'u') or zero_range(_x): return 1 x = np.unique(x) if zero: x = np.unique(np.hstack([0, x])) return np.min(np.diff(np.sort(x)))
[ "def", "resolution", "(", "x", ",", "zero", "=", "True", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "# (unsigned) integers or an effective range of zero", "_x", "=", "x", "[", "~", "np", ".", "isnan", "(", "x", ")", "]", "_x", "=", "(",...
Compute the resolution of a data vector Resolution is smallest non-zero distance between adjacent values Parameters ---------- x : 1D array-like zero : Boolean Whether to include zero values in the computation Result ------ res : resolution of x If x is an integer array, then the resolution is 1
[ "Compute", "the", "resolution", "of", "a", "data", "vector" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1035-L1064
train
214,553
has2k1/plotnine
plotnine/utils.py
cross_join
def cross_join(df1, df2): """ Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401 """ if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd.Index(list(df1.columns) + list(df2.columns)) df1['key'] = 1 df2['key'] = 1 return pd.merge(df1, df2, on='key').loc[:, all_columns]
python
def cross_join(df1, df2): """ Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401 """ if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd.Index(list(df1.columns) + list(df2.columns)) df1['key'] = 1 df2['key'] = 1 return pd.merge(df1, df2, on='key').loc[:, all_columns]
[ "def", "cross_join", "(", "df1", ",", "df2", ")", ":", "if", "len", "(", "df1", ")", "==", "0", ":", "return", "df2", "if", "len", "(", "df2", ")", "==", "0", ":", "return", "df1", "# Add as lists so that the new index keeps the items in", "# the order that ...
Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401
[ "Return", "a", "dataframe", "that", "is", "a", "cross", "between", "dataframes", "df1", "and", "df2" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1067-L1085
train
214,554
has2k1/plotnine
plotnine/utils.py
to_inches
def to_inches(value, units): """ Convert value to inches Parameters ---------- value : float Value to be converted units : str Units of value. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x/2.54, 'mm': lambda x: x/(2.54*10)} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
python
def to_inches(value, units): """ Convert value to inches Parameters ---------- value : float Value to be converted units : str Units of value. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x/2.54, 'mm': lambda x: x/(2.54*10)} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
[ "def", "to_inches", "(", "value", ",", "units", ")", ":", "lookup", "=", "{", "'in'", ":", "lambda", "x", ":", "x", ",", "'cm'", ":", "lambda", "x", ":", "x", "/", "2.54", ",", "'mm'", ":", "lambda", "x", ":", "x", "/", "(", "2.54", "*", "10"...
Convert value to inches Parameters ---------- value : float Value to be converted units : str Units of value. Must be one of `['in', 'cm', 'mm']`.
[ "Convert", "value", "to", "inches" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1088-L1106
train
214,555
has2k1/plotnine
plotnine/utils.py
from_inches
def from_inches(value, units): """ Convert value in inches to given units Parameters ---------- value : float Value to be converted units : str Units to convert value to. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x*2.54, 'mm': lambda x: x*2.54*10} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
python
def from_inches(value, units): """ Convert value in inches to given units Parameters ---------- value : float Value to be converted units : str Units to convert value to. Must be one of `['in', 'cm', 'mm']`. """ lookup = {'in': lambda x: x, 'cm': lambda x: x*2.54, 'mm': lambda x: x*2.54*10} try: return lookup[units](value) except KeyError: raise PlotnineError("Unknown units '{}'".format(units))
[ "def", "from_inches", "(", "value", ",", "units", ")", ":", "lookup", "=", "{", "'in'", ":", "lambda", "x", ":", "x", ",", "'cm'", ":", "lambda", "x", ":", "x", "*", "2.54", ",", "'mm'", ":", "lambda", "x", ":", "x", "*", "2.54", "*", "10", "...
Convert value in inches to given units Parameters ---------- value : float Value to be converted units : str Units to convert value to. Must be one of `['in', 'cm', 'mm']`.
[ "Convert", "value", "in", "inches", "to", "given", "units" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1109-L1127
train
214,556
has2k1/plotnine
plotnine/utils.py
log
def log(x, base=None): """ Calculate the log Parameters ---------- x : float or array_like Input values base : int or float (Default: None) Base of the log. If `None`, the natural logarithm is computed (`base=np.e`). Returns ------- out : float or ndarray Calculated result """ if base == 10: return np.log10(x) elif base == 2: return np.log2(x) elif base is None or base == np.e: return np.log(x) else: return np.log(x)/np.log(base)
python
def log(x, base=None): """ Calculate the log Parameters ---------- x : float or array_like Input values base : int or float (Default: None) Base of the log. If `None`, the natural logarithm is computed (`base=np.e`). Returns ------- out : float or ndarray Calculated result """ if base == 10: return np.log10(x) elif base == 2: return np.log2(x) elif base is None or base == np.e: return np.log(x) else: return np.log(x)/np.log(base)
[ "def", "log", "(", "x", ",", "base", "=", "None", ")", ":", "if", "base", "==", "10", ":", "return", "np", ".", "log10", "(", "x", ")", "elif", "base", "==", "2", ":", "return", "np", ".", "log2", "(", "x", ")", "elif", "base", "is", "None", ...
Calculate the log Parameters ---------- x : float or array_like Input values base : int or float (Default: None) Base of the log. If `None`, the natural logarithm is computed (`base=np.e`). Returns ------- out : float or ndarray Calculated result
[ "Calculate", "the", "log" ]
566e579af705367e584fb27a74e6c5199624ca89
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L1174-L1198
train
214,557
cloudtools/stacker
stacker/lookups/handlers/hook_data.py
HookDataLookup.handle
def handle(cls, value, context, **kwargs): """Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key> """ try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value) return context.hook_data[hook_name][key]
python
def handle(cls, value, context, **kwargs): """Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key> """ try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value) return context.hook_data[hook_name][key]
[ "def", "handle", "(", "cls", ",", "value", ",", "context", ",", "*", "*", "kwargs", ")", ":", "try", ":", "hook_name", ",", "key", "=", "value", ".", "split", "(", "\"::\"", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid value...
Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key>
[ "Returns", "the", "value", "of", "a", "key", "for", "a", "given", "hook", "in", "hook_data", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/hook_data.py#L13-L26
train
214,558
cloudtools/stacker
stacker/variables.py
resolve_variables
def resolve_variables(variables, context, provider): """Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ for variable in variables: variable.resolve(context, provider)
python
def resolve_variables(variables, context, provider): """Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ for variable in variables: variable.resolve(context, provider)
[ "def", "resolve_variables", "(", "variables", ",", "context", ",", "provider", ")", ":", "for", "variable", "in", "variables", ":", "variable", ".", "resolve", "(", "context", ",", "provider", ")" ]
Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider
[ "Given", "a", "list", "of", "variables", "resolve", "all", "of", "them", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L23-L35
train
214,559
cloudtools/stacker
stacker/variables.py
Variable.value
def value(self): """Return the current value of the Variable. """ try: return self._value.value() except UnresolvedVariableValue: raise UnresolvedVariable("<unknown>", self) except InvalidLookupConcatenation as e: raise InvalidLookupCombination(e.lookup, e.lookups, self)
python
def value(self): """Return the current value of the Variable. """ try: return self._value.value() except UnresolvedVariableValue: raise UnresolvedVariable("<unknown>", self) except InvalidLookupConcatenation as e: raise InvalidLookupCombination(e.lookup, e.lookups, self)
[ "def", "value", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_value", ".", "value", "(", ")", "except", "UnresolvedVariableValue", ":", "raise", "UnresolvedVariable", "(", "\"<unknown>\"", ",", "self", ")", "except", "InvalidLookupConcatenation", ...
Return the current value of the Variable.
[ "Return", "the", "current", "value", "of", "the", "Variable", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L53-L61
train
214,560
cloudtools/stacker
stacker/variables.py
Variable.resolve
def resolve(self, context, provider): """Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ try: self._value.resolve(context, provider) except FailedLookup as e: raise FailedVariableLookup(self.name, e.lookup, e.error)
python
def resolve(self, context, provider): """Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider """ try: self._value.resolve(context, provider) except FailedLookup as e: raise FailedVariableLookup(self.name, e.lookup, e.error)
[ "def", "resolve", "(", "self", ",", "context", ",", "provider", ")", ":", "try", ":", "self", ".", "_value", ".", "resolve", "(", "context", ",", "provider", ")", "except", "FailedLookup", "as", "e", ":", "raise", "FailedVariableLookup", "(", "self", "."...
Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider
[ "Recursively", "resolve", "any", "lookups", "with", "the", "Variable", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/variables.py#L71-L84
train
214,561
cloudtools/stacker
stacker/plan.py
Step.run
def run(self): """Runs this step until it has completed successfully, or been skipped. """ stop_watcher = threading.Event() watcher = None if self.watch_func: watcher = threading.Thread( target=self.watch_func, args=(self.stack, stop_watcher) ) watcher.start() try: while not self.done: self._run_once() finally: if watcher: stop_watcher.set() watcher.join() return self.ok
python
def run(self): """Runs this step until it has completed successfully, or been skipped. """ stop_watcher = threading.Event() watcher = None if self.watch_func: watcher = threading.Thread( target=self.watch_func, args=(self.stack, stop_watcher) ) watcher.start() try: while not self.done: self._run_once() finally: if watcher: stop_watcher.set() watcher.join() return self.ok
[ "def", "run", "(", "self", ")", ":", "stop_watcher", "=", "threading", ".", "Event", "(", ")", "watcher", "=", "None", "if", "self", ".", "watch_func", ":", "watcher", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "watch_func", ",",...
Runs this step until it has completed successfully, or been skipped.
[ "Runs", "this", "step", "until", "it", "has", "completed", "successfully", "or", "been", "skipped", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L68-L89
train
214,562
cloudtools/stacker
stacker/plan.py
Graph.downstream
def downstream(self, step_name): """Returns the direct dependencies of the given step""" return list(self.steps[dep] for dep in self.dag.downstream(step_name))
python
def downstream(self, step_name): """Returns the direct dependencies of the given step""" return list(self.steps[dep] for dep in self.dag.downstream(step_name))
[ "def", "downstream", "(", "self", ",", "step_name", ")", ":", "return", "list", "(", "self", ".", "steps", "[", "dep", "]", "for", "dep", "in", "self", ".", "dag", ".", "downstream", "(", "step_name", ")", ")" ]
Returns the direct dependencies of the given step
[ "Returns", "the", "direct", "dependencies", "of", "the", "given", "step" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L272-L274
train
214,563
cloudtools/stacker
stacker/plan.py
Graph.transposed
def transposed(self): """Returns a "transposed" version of this graph. Useful for walking in reverse. """ return Graph(steps=self.steps, dag=self.dag.transpose())
python
def transposed(self): """Returns a "transposed" version of this graph. Useful for walking in reverse. """ return Graph(steps=self.steps, dag=self.dag.transpose())
[ "def", "transposed", "(", "self", ")", ":", "return", "Graph", "(", "steps", "=", "self", ".", "steps", ",", "dag", "=", "self", ".", "dag", ".", "transpose", "(", ")", ")" ]
Returns a "transposed" version of this graph. Useful for walking in reverse.
[ "Returns", "a", "transposed", "version", "of", "this", "graph", ".", "Useful", "for", "walking", "in", "reverse", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L276-L280
train
214,564
cloudtools/stacker
stacker/plan.py
Graph.filtered
def filtered(self, step_names): """Returns a "filtered" version of this graph.""" return Graph(steps=self.steps, dag=self.dag.filter(step_names))
python
def filtered(self, step_names): """Returns a "filtered" version of this graph.""" return Graph(steps=self.steps, dag=self.dag.filter(step_names))
[ "def", "filtered", "(", "self", ",", "step_names", ")", ":", "return", "Graph", "(", "steps", "=", "self", ".", "steps", ",", "dag", "=", "self", ".", "dag", ".", "filter", "(", "step_names", ")", ")" ]
Returns a "filtered" version of this graph.
[ "Returns", "a", "filtered", "version", "of", "this", "graph", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L282-L284
train
214,565
cloudtools/stacker
stacker/plan.py
Plan.execute
def execute(self, *args, **kwargs): """Walks each step in the underlying graph, and raises an exception if any of the steps fail. Raises: PlanFailed: Raised if any of the steps fail. """ self.walk(*args, **kwargs) failed_steps = [step for step in self.steps if step.status == FAILED] if failed_steps: raise PlanFailed(failed_steps)
python
def execute(self, *args, **kwargs): """Walks each step in the underlying graph, and raises an exception if any of the steps fail. Raises: PlanFailed: Raised if any of the steps fail. """ self.walk(*args, **kwargs) failed_steps = [step for step in self.steps if step.status == FAILED] if failed_steps: raise PlanFailed(failed_steps)
[ "def", "execute", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "walk", "(", "*", "args", ",", "*", "*", "kwargs", ")", "failed_steps", "=", "[", "step", "for", "step", "in", "self", ".", "steps", "if", "step", ...
Walks each step in the underlying graph, and raises an exception if any of the steps fail. Raises: PlanFailed: Raised if any of the steps fail.
[ "Walks", "each", "step", "in", "the", "underlying", "graph", "and", "raises", "an", "exception", "if", "any", "of", "the", "steps", "fail", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L358-L369
train
214,566
cloudtools/stacker
stacker/plan.py
Plan.walk
def walk(self, walker): """Walks each step in the underlying graph, in topological order. Args: walker (func): a walker function to be passed to :class:`stacker.dag.DAG` to walk the graph. """ def walk_func(step): # Before we execute the step, we need to ensure that it's # transitive dependencies are all in an "ok" state. If not, we # won't execute this step. for dep in self.graph.downstream(step.name): if not dep.ok: step.set_status(FailedStatus("dependency has failed")) return step.ok return step.run() return self.graph.walk(walker, walk_func)
python
def walk(self, walker): """Walks each step in the underlying graph, in topological order. Args: walker (func): a walker function to be passed to :class:`stacker.dag.DAG` to walk the graph. """ def walk_func(step): # Before we execute the step, we need to ensure that it's # transitive dependencies are all in an "ok" state. If not, we # won't execute this step. for dep in self.graph.downstream(step.name): if not dep.ok: step.set_status(FailedStatus("dependency has failed")) return step.ok return step.run() return self.graph.walk(walker, walk_func)
[ "def", "walk", "(", "self", ",", "walker", ")", ":", "def", "walk_func", "(", "step", ")", ":", "# Before we execute the step, we need to ensure that it's", "# transitive dependencies are all in an \"ok\" state. If not, we", "# won't execute this step.", "for", "dep", "in", "...
Walks each step in the underlying graph, in topological order. Args: walker (func): a walker function to be passed to :class:`stacker.dag.DAG` to walk the graph.
[ "Walks", "each", "step", "in", "the", "underlying", "graph", "in", "topological", "order", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/plan.py#L371-L390
train
214,567
cloudtools/stacker
stacker/blueprints/variables/types.py
TroposphereType.create
def create(self, value): """Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. Each dictionary will be passed to the `from_dict` method of the type. Returns: Union[list, type]: Returns the value converted to the troposphere type """ # Explicitly check with len such that non-sequence types throw. if self._optional and (value is None or len(value) == 0): return None if hasattr(self._type, 'resource_type'): # Our type is a resource, so ensure we have a dict of title to # parameters if not isinstance(value, dict): raise ValueError("Resources must be specified as a dict of " "title to parameters") if not self._many and len(value) > 1: raise ValueError("Only one resource can be provided for this " "TroposphereType variable") result = [ self._type.from_dict(title, v) for title, v in value.items() ] else: # Our type is for properties, not a resource, so don't use # titles if self._many: result = [self._type.from_dict(None, v) for v in value] elif not isinstance(value, dict): raise ValueError("TroposphereType for a single non-resource" "type must be specified as a dict of " "parameters") else: result = [self._type.from_dict(None, value)] if self._validate: for v in result: v._validate_props() return result[0] if not self._many else result
python
def create(self, value): """Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. Each dictionary will be passed to the `from_dict` method of the type. Returns: Union[list, type]: Returns the value converted to the troposphere type """ # Explicitly check with len such that non-sequence types throw. if self._optional and (value is None or len(value) == 0): return None if hasattr(self._type, 'resource_type'): # Our type is a resource, so ensure we have a dict of title to # parameters if not isinstance(value, dict): raise ValueError("Resources must be specified as a dict of " "title to parameters") if not self._many and len(value) > 1: raise ValueError("Only one resource can be provided for this " "TroposphereType variable") result = [ self._type.from_dict(title, v) for title, v in value.items() ] else: # Our type is for properties, not a resource, so don't use # titles if self._many: result = [self._type.from_dict(None, v) for v in value] elif not isinstance(value, dict): raise ValueError("TroposphereType for a single non-resource" "type must be specified as a dict of " "parameters") else: result = [self._type.from_dict(None, value)] if self._validate: for v in result: v._validate_props() return result[0] if not self._many else result
[ "def", "create", "(", "self", ",", "value", ")", ":", "# Explicitly check with len such that non-sequence types throw.", "if", "self", ".", "_optional", "and", "(", "value", "is", "None", "or", "len", "(", "value", ")", "==", "0", ")", ":", "return", "None", ...
Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. Each dictionary will be passed to the `from_dict` method of the type. Returns: Union[list, type]: Returns the value converted to the troposphere type
[ "Create", "the", "troposphere", "type", "from", "the", "value", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/variables/types.py#L61-L110
train
214,568
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_lookup_key_parse
def _lookup_key_parse(table_keys): """Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack depends on. This is used to generate the order in which the stacks should be executed. Returns: dict: includes a dict of lookup types with data types ('new_keys') and a list of the lookups with without ('clean_table_keys') """ # we need to parse the key lookup passed in regex_matcher = '\[([^\]]+)]' valid_dynamodb_datatypes = ['M', 'S', 'N', 'L'] clean_table_keys = [] new_keys = [] for key in table_keys: match = re.search(regex_matcher, key) if match: # the datatypes are pulled from the dynamodb docs if match.group(1) in valid_dynamodb_datatypes: match_val = str(match.group(1)) key = key.replace(match.group(0), '') new_keys.append({match_val: key}) clean_table_keys.append(key) else: raise ValueError( ('Stacker does not support looking up the datatype: {}') .format(str(match.group(1)))) else: new_keys.append({'S': key}) clean_table_keys.append(key) key_dict = {} key_dict['new_keys'] = new_keys key_dict['clean_table_keys'] = clean_table_keys return key_dict
python
def _lookup_key_parse(table_keys): """Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack depends on. This is used to generate the order in which the stacks should be executed. Returns: dict: includes a dict of lookup types with data types ('new_keys') and a list of the lookups with without ('clean_table_keys') """ # we need to parse the key lookup passed in regex_matcher = '\[([^\]]+)]' valid_dynamodb_datatypes = ['M', 'S', 'N', 'L'] clean_table_keys = [] new_keys = [] for key in table_keys: match = re.search(regex_matcher, key) if match: # the datatypes are pulled from the dynamodb docs if match.group(1) in valid_dynamodb_datatypes: match_val = str(match.group(1)) key = key.replace(match.group(0), '') new_keys.append({match_val: key}) clean_table_keys.append(key) else: raise ValueError( ('Stacker does not support looking up the datatype: {}') .format(str(match.group(1)))) else: new_keys.append({'S': key}) clean_table_keys.append(key) key_dict = {} key_dict['new_keys'] = new_keys key_dict['clean_table_keys'] = clean_table_keys return key_dict
[ "def", "_lookup_key_parse", "(", "table_keys", ")", ":", "# we need to parse the key lookup passed in", "regex_matcher", "=", "'\\[([^\\]]+)]'", "valid_dynamodb_datatypes", "=", "[", "'M'", ",", "'S'", ",", "'N'", ",", "'L'", "]", "clean_table_keys", "=", "[", "]", ...
Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack depends on. This is used to generate the order in which the stacks should be executed. Returns: dict: includes a dict of lookup types with data types ('new_keys') and a list of the lookups with without ('clean_table_keys')
[ "Return", "the", "order", "in", "which", "the", "stacks", "should", "be", "executed", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L85-L126
train
214,569
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_build_projection_expression
def _build_projection_expression(clean_table_keys): """Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup. """ projection_expression = '' for key in clean_table_keys[:-1]: projection_expression += ('{},').format(key) projection_expression += clean_table_keys[-1] return projection_expression
python
def _build_projection_expression(clean_table_keys): """Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup. """ projection_expression = '' for key in clean_table_keys[:-1]: projection_expression += ('{},').format(key) projection_expression += clean_table_keys[-1] return projection_expression
[ "def", "_build_projection_expression", "(", "clean_table_keys", ")", ":", "projection_expression", "=", "''", "for", "key", "in", "clean_table_keys", "[", ":", "-", "1", "]", ":", "projection_expression", "+=", "(", "'{},'", ")", ".", "format", "(", "key", ")"...
Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup.
[ "Given", "cleaned", "up", "keys", "this", "will", "return", "a", "projection", "expression", "for", "the", "dynamodb", "lookup", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L129-L143
train
214,570
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
_convert_ddb_list_to_list
def _convert_ddb_list_to_list(conversion_list): """Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes """ ret_list = [] for v in conversion_list: for v1 in v: ret_list.append(v[v1]) return ret_list
python
def _convert_ddb_list_to_list(conversion_list): """Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes """ ret_list = [] for v in conversion_list: for v1 in v: ret_list.append(v[v1]) return ret_list
[ "def", "_convert_ddb_list_to_list", "(", "conversion_list", ")", ":", "ret_list", "=", "[", "]", "for", "v", "in", "conversion_list", ":", "for", "v1", "in", "v", ":", "ret_list", ".", "append", "(", "v", "[", "v1", "]", ")", "return", "ret_list" ]
Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes
[ "Given", "a", "dynamodb", "list", "it", "will", "return", "a", "python", "list", "without", "the", "dynamodb", "datatypes" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L180-L195
train
214,571
cloudtools/stacker
stacker/lookups/handlers/dynamodb.py
DynamodbLookup.handle
def handle(cls, value, **kwargs): """Get a value from a dynamodb table dynamodb field types should be in the following format: [<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>... Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. """ value = read_value_from_path(value) table_info = None table_keys = None region = None table_name = None if '@' in value: table_info, table_keys = value.split('@', 1) if ':' in table_info: region, table_name = table_info.split(':', 1) else: table_name = table_info else: raise ValueError('Please make sure to include a tablename') if not table_name: raise ValueError('Please make sure to include a dynamodb table ' 'name') table_lookup, table_keys = table_keys.split(':', 1) table_keys = table_keys.split('.') key_dict = _lookup_key_parse(table_keys) new_keys = key_dict['new_keys'] clean_table_keys = key_dict['clean_table_keys'] projection_expression = _build_projection_expression(clean_table_keys) # lookup the data from dynamodb dynamodb = get_session(region).client('dynamodb') try: response = dynamodb.get_item( TableName=table_name, Key={ table_lookup: new_keys[0] }, ProjectionExpression=projection_expression ) except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': raise ValueError( 'Cannot find the dynamodb table: {}'.format(table_name)) elif e.response['Error']['Code'] == 'ValidationException': raise ValueError( 'No dynamodb record matched the partition key: ' '{}'.format(table_lookup)) else: raise ValueError('The dynamodb lookup {} had an error: ' '{}'.format(value, e)) # find and return the key from the dynamo data returned if 'Item' in response: return (_get_val_from_ddb_data(response['Item'], new_keys[1:])) else: raise ValueError( 'The dynamodb record could not be found using the following ' 'key: {}'.format(new_keys[0]))
python
def handle(cls, value, **kwargs): """Get a value from a dynamodb table dynamodb field types should be in the following format: [<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>... Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. """ value = read_value_from_path(value) table_info = None table_keys = None region = None table_name = None if '@' in value: table_info, table_keys = value.split('@', 1) if ':' in table_info: region, table_name = table_info.split(':', 1) else: table_name = table_info else: raise ValueError('Please make sure to include a tablename') if not table_name: raise ValueError('Please make sure to include a dynamodb table ' 'name') table_lookup, table_keys = table_keys.split(':', 1) table_keys = table_keys.split('.') key_dict = _lookup_key_parse(table_keys) new_keys = key_dict['new_keys'] clean_table_keys = key_dict['clean_table_keys'] projection_expression = _build_projection_expression(clean_table_keys) # lookup the data from dynamodb dynamodb = get_session(region).client('dynamodb') try: response = dynamodb.get_item( TableName=table_name, Key={ table_lookup: new_keys[0] }, ProjectionExpression=projection_expression ) except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': raise ValueError( 'Cannot find the dynamodb table: {}'.format(table_name)) elif e.response['Error']['Code'] == 'ValidationException': raise ValueError( 'No dynamodb record matched the partition key: ' '{}'.format(table_lookup)) else: raise ValueError('The dynamodb lookup {} had an error: ' '{}'.format(value, e)) # find and return the key from the dynamo data returned if 'Item' in response: return (_get_val_from_ddb_data(response['Item'], new_keys[1:])) else: raise ValueError( 'The dynamodb record could not be found using the following ' 'key: {}'.format(new_keys[0]))
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "read_value_from_path", "(", "value", ")", "table_info", "=", "None", "table_keys", "=", "None", "region", "=", "None", "table_name", "=", "None", "if", "'@'", ...
Get a value from a dynamodb table dynamodb field types should be in the following format: [<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>... Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified.
[ "Get", "a", "value", "from", "a", "dynamodb", "table" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/dynamodb.py#L17-L82
train
214,572
cloudtools/stacker
stacker/actions/base.py
plan
def plan(description, stack_action, context, tail=None, reverse=False): """A simple helper that builds a graph based plan from a set of stacks. Args: description (str): a description of the plan. action (func): a function to call for each stack. context (:class:`stacker.context.Context`): a :class:`stacker.context.Context` to build the plan from. tail (func): an optional function to call to tail the stack progress. reverse (bool): if True, execute the graph in reverse (useful for destroy actions). Returns: :class:`plan.Plan`: The resulting plan object """ def target_fn(*args, **kwargs): return COMPLETE steps = [ Step(stack, fn=stack_action, watch_func=tail) for stack in context.get_stacks()] steps += [ Step(target, fn=target_fn) for target in context.get_targets()] graph = build_graph(steps) return build_plan( description=description, graph=graph, targets=context.stack_names, reverse=reverse)
python
def plan(description, stack_action, context, tail=None, reverse=False): """A simple helper that builds a graph based plan from a set of stacks. Args: description (str): a description of the plan. action (func): a function to call for each stack. context (:class:`stacker.context.Context`): a :class:`stacker.context.Context` to build the plan from. tail (func): an optional function to call to tail the stack progress. reverse (bool): if True, execute the graph in reverse (useful for destroy actions). Returns: :class:`plan.Plan`: The resulting plan object """ def target_fn(*args, **kwargs): return COMPLETE steps = [ Step(stack, fn=stack_action, watch_func=tail) for stack in context.get_stacks()] steps += [ Step(target, fn=target_fn) for target in context.get_targets()] graph = build_graph(steps) return build_plan( description=description, graph=graph, targets=context.stack_names, reverse=reverse)
[ "def", "plan", "(", "description", ",", "stack_action", ",", "context", ",", "tail", "=", "None", ",", "reverse", "=", "False", ")", ":", "def", "target_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "COMPLETE", "steps", "=", "["...
A simple helper that builds a graph based plan from a set of stacks. Args: description (str): a description of the plan. action (func): a function to call for each stack. context (:class:`stacker.context.Context`): a :class:`stacker.context.Context` to build the plan from. tail (func): an optional function to call to tail the stack progress. reverse (bool): if True, execute the graph in reverse (useful for destroy actions). Returns: :class:`plan.Plan`: The resulting plan object
[ "A", "simple", "helper", "that", "builds", "a", "graph", "based", "plan", "from", "a", "set", "of", "stacks", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L64-L97
train
214,573
cloudtools/stacker
stacker/actions/base.py
stack_template_key_name
def stack_template_key_name(blueprint): """Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint. """ name = blueprint.name return "stack_templates/%s/%s-%s.json" % (blueprint.context.get_fqn(name), name, blueprint.version)
python
def stack_template_key_name(blueprint): """Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint. """ name = blueprint.name return "stack_templates/%s/%s-%s.json" % (blueprint.context.get_fqn(name), name, blueprint.version)
[ "def", "stack_template_key_name", "(", "blueprint", ")", ":", "name", "=", "blueprint", ".", "name", "return", "\"stack_templates/%s/%s-%s.json\"", "%", "(", "blueprint", ".", "context", ".", "get_fqn", "(", "name", ")", ",", "name", ",", "blueprint", ".", "ve...
Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint.
[ "Given", "a", "blueprint", "produce", "an", "appropriate", "key", "name", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L100-L113
train
214,574
cloudtools/stacker
stacker/actions/base.py
stack_template_url
def stack_template_url(bucket_name, blueprint, endpoint): """Produces an s3 url for a given blueprint. Args: bucket_name (string): The name of the S3 bucket where the resulting templates are stored. blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the URL to. endpoint (string): The s3 endpoint used for the bucket. Returns: string: S3 URL. """ key_name = stack_template_key_name(blueprint) return "%s/%s/%s" % (endpoint, bucket_name, key_name)
python
def stack_template_url(bucket_name, blueprint, endpoint): """Produces an s3 url for a given blueprint. Args: bucket_name (string): The name of the S3 bucket where the resulting templates are stored. blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the URL to. endpoint (string): The s3 endpoint used for the bucket. Returns: string: S3 URL. """ key_name = stack_template_key_name(blueprint) return "%s/%s/%s" % (endpoint, bucket_name, key_name)
[ "def", "stack_template_url", "(", "bucket_name", ",", "blueprint", ",", "endpoint", ")", ":", "key_name", "=", "stack_template_key_name", "(", "blueprint", ")", "return", "\"%s/%s/%s\"", "%", "(", "endpoint", ",", "bucket_name", ",", "key_name", ")" ]
Produces an s3 url for a given blueprint. Args: bucket_name (string): The name of the S3 bucket where the resulting templates are stored. blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the URL to. endpoint (string): The s3 endpoint used for the bucket. Returns: string: S3 URL.
[ "Produces", "an", "s3", "url", "for", "a", "given", "blueprint", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L116-L130
train
214,575
cloudtools/stacker
stacker/actions/base.py
BaseAction.ensure_cfn_bucket
def ensure_cfn_bucket(self): """The CloudFormation bucket where templates will be stored.""" if self.bucket_name: ensure_s3_bucket(self.s3_conn, self.bucket_name, self.bucket_region)
python
def ensure_cfn_bucket(self): """The CloudFormation bucket where templates will be stored.""" if self.bucket_name: ensure_s3_bucket(self.s3_conn, self.bucket_name, self.bucket_region)
[ "def", "ensure_cfn_bucket", "(", "self", ")", ":", "if", "self", ".", "bucket_name", ":", "ensure_s3_bucket", "(", "self", ".", "s3_conn", ",", "self", ".", "bucket_name", ",", "self", ".", "bucket_region", ")" ]
The CloudFormation bucket where templates will be stored.
[ "The", "CloudFormation", "bucket", "where", "templates", "will", "be", "stored", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L159-L164
train
214,576
cloudtools/stacker
stacker/actions/base.py
BaseAction.s3_stack_push
def s3_stack_push(self, blueprint, force=False): """Pushes the rendered blueprint's template to S3. Verifies that the template doesn't already exist in S3 before pushing. Returns the URL to the template in S3. """ key_name = stack_template_key_name(blueprint) template_url = self.stack_template_url(blueprint) try: template_exists = self.s3_conn.head_object( Bucket=self.bucket_name, Key=key_name) is not None except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': template_exists = False else: raise if template_exists and not force: logger.debug("Cloudformation template %s already exists.", template_url) return template_url self.s3_conn.put_object(Bucket=self.bucket_name, Key=key_name, Body=blueprint.rendered, ServerSideEncryption='AES256', ACL='bucket-owner-full-control') logger.debug("Blueprint %s pushed to %s.", blueprint.name, template_url) return template_url
python
def s3_stack_push(self, blueprint, force=False): """Pushes the rendered blueprint's template to S3. Verifies that the template doesn't already exist in S3 before pushing. Returns the URL to the template in S3. """ key_name = stack_template_key_name(blueprint) template_url = self.stack_template_url(blueprint) try: template_exists = self.s3_conn.head_object( Bucket=self.bucket_name, Key=key_name) is not None except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': template_exists = False else: raise if template_exists and not force: logger.debug("Cloudformation template %s already exists.", template_url) return template_url self.s3_conn.put_object(Bucket=self.bucket_name, Key=key_name, Body=blueprint.rendered, ServerSideEncryption='AES256', ACL='bucket-owner-full-control') logger.debug("Blueprint %s pushed to %s.", blueprint.name, template_url) return template_url
[ "def", "s3_stack_push", "(", "self", ",", "blueprint", ",", "force", "=", "False", ")", ":", "key_name", "=", "stack_template_key_name", "(", "blueprint", ")", "template_url", "=", "self", ".", "stack_template_url", "(", "blueprint", ")", "try", ":", "template...
Pushes the rendered blueprint's template to S3. Verifies that the template doesn't already exist in S3 before pushing. Returns the URL to the template in S3.
[ "Pushes", "the", "rendered", "blueprint", "s", "template", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L171-L201
train
214,577
cloudtools/stacker
stacker/hooks/aws_lambda.py
_zip_files
def _zip_files(files, root): """Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files. """ zip_data = StringIO() with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) # Fix file permissions to avoid any issues - only care whether a file # is executable or not, choosing between modes 755 and 644 accordingly. for zip_entry in zip_file.filelist: perms = (zip_entry.external_attr & ZIP_PERMS_MASK) >> 16 if perms & stat.S_IXUSR != 0: new_perms = 0o755 else: new_perms = 0o644 if new_perms != perms: logger.debug("lambda: fixing perms: %s: %o => %o", zip_entry.filename, perms, new_perms) new_attr = ((zip_entry.external_attr & ~ZIP_PERMS_MASK) | (new_perms << 16)) zip_entry.external_attr = new_attr contents = zip_data.getvalue() zip_data.close() content_hash = _calculate_hash(files, root) return contents, content_hash
python
def _zip_files(files, root): """Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files. """ zip_data = StringIO() with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) # Fix file permissions to avoid any issues - only care whether a file # is executable or not, choosing between modes 755 and 644 accordingly. for zip_entry in zip_file.filelist: perms = (zip_entry.external_attr & ZIP_PERMS_MASK) >> 16 if perms & stat.S_IXUSR != 0: new_perms = 0o755 else: new_perms = 0o644 if new_perms != perms: logger.debug("lambda: fixing perms: %s: %o => %o", zip_entry.filename, perms, new_perms) new_attr = ((zip_entry.external_attr & ~ZIP_PERMS_MASK) | (new_perms << 16)) zip_entry.external_attr = new_attr contents = zip_data.getvalue() zip_data.close() content_hash = _calculate_hash(files, root) return contents, content_hash
[ "def", "_zip_files", "(", "files", ",", "root", ")", ":", "zip_data", "=", "StringIO", "(", ")", "with", "ZipFile", "(", "zip_data", ",", "'w'", ",", "ZIP_DEFLATED", ")", "as", "zip_file", ":", "for", "fname", "in", "files", ":", "zip_file", ".", "writ...
Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files.
[ "Generates", "a", "ZIP", "file", "in", "-", "memory", "from", "a", "list", "of", "files", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L33-L75
train
214,578
cloudtools/stacker
stacker/hooks/aws_lambda.py
_calculate_hash
def _calculate_hash(files, root): """ Returns a hash of all of the given files at the given root. Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files. """ file_hash = hashlib.md5() for fname in sorted(files): f = os.path.join(root, fname) file_hash.update((fname + "\0").encode()) with open(f, "rb") as fd: for chunk in iter(lambda: fd.read(4096), ""): if not chunk: break file_hash.update(chunk) file_hash.update("\0".encode()) return file_hash.hexdigest()
python
def _calculate_hash(files, root): """ Returns a hash of all of the given files at the given root. Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files. """ file_hash = hashlib.md5() for fname in sorted(files): f = os.path.join(root, fname) file_hash.update((fname + "\0").encode()) with open(f, "rb") as fd: for chunk in iter(lambda: fd.read(4096), ""): if not chunk: break file_hash.update(chunk) file_hash.update("\0".encode()) return file_hash.hexdigest()
[ "def", "_calculate_hash", "(", "files", ",", "root", ")", ":", "file_hash", "=", "hashlib", ".", "md5", "(", ")", "for", "fname", "in", "sorted", "(", "files", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "f...
Returns a hash of all of the given files at the given root. Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files.
[ "Returns", "a", "hash", "of", "all", "of", "the", "given", "files", "at", "the", "given", "root", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L78-L100
train
214,579
cloudtools/stacker
stacker/hooks/aws_lambda.py
_find_files
def _find_files(root, includes, excludes, follow_symlinks): """List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html """ root = os.path.abspath(root) file_set = formic.FileSet( directory=root, include=includes, exclude=excludes, symlinks=follow_symlinks, ) for filename in file_set.qualified_files(absolute=False): yield filename
python
def _find_files(root, includes, excludes, follow_symlinks): """List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html """ root = os.path.abspath(root) file_set = formic.FileSet( directory=root, include=includes, exclude=excludes, symlinks=follow_symlinks, ) for filename in file_set.qualified_files(absolute=False): yield filename
[ "def", "_find_files", "(", "root", ",", "includes", ",", "excludes", ",", "follow_symlinks", ")", ":", "root", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "file_set", "=", "formic", ".", "FileSet", "(", "directory", "=", "root", ",", "inc...
List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html
[ "List", "files", "inside", "a", "directory", "based", "on", "include", "and", "exclude", "rules", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L103-L134
train
214,580
cloudtools/stacker
stacker/hooks/aws_lambda.py
_zip_from_file_patterns
def _zip_from_file_patterns(root, includes, excludes, follow_symlinks): """Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file See Also: :func:`_zip_files`, :func:`_find_files`. Raises: RuntimeError: when the generated archive would be empty. """ logger.info('lambda: base directory: %s', root) files = list(_find_files(root, includes, excludes, follow_symlinks)) if not files: raise RuntimeError('Empty list of files for Lambda payload. Check ' 'your include/exclude options for errors.') logger.info('lambda: adding %d files:', len(files)) for fname in files: logger.debug('lambda: + %s', fname) return _zip_files(files, root)
python
def _zip_from_file_patterns(root, includes, excludes, follow_symlinks): """Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file See Also: :func:`_zip_files`, :func:`_find_files`. Raises: RuntimeError: when the generated archive would be empty. """ logger.info('lambda: base directory: %s', root) files = list(_find_files(root, includes, excludes, follow_symlinks)) if not files: raise RuntimeError('Empty list of files for Lambda payload. Check ' 'your include/exclude options for errors.') logger.info('lambda: adding %d files:', len(files)) for fname in files: logger.debug('lambda: + %s', fname) return _zip_files(files, root)
[ "def", "_zip_from_file_patterns", "(", "root", ",", "includes", ",", "excludes", ",", "follow_symlinks", ")", ":", "logger", ".", "info", "(", "'lambda: base directory: %s'", ",", "root", ")", "files", "=", "list", "(", "_find_files", "(", "root", ",", "includ...
Generates a ZIP file in-memory from file search patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file See Also: :func:`_zip_files`, :func:`_find_files`. Raises: RuntimeError: when the generated archive would be empty.
[ "Generates", "a", "ZIP", "file", "in", "-", "memory", "from", "file", "search", "patterns", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L137-L169
train
214,581
cloudtools/stacker
stacker/hooks/aws_lambda.py
_head_object
def _head_object(s3_conn, bucket, key): """Retrieve information about an object in S3 if it exists. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket containing the key. key (str): name of the key to lookup. Returns: dict: S3 object information, or None if the object does not exist. See the AWS documentation for explanation of the contents. Raises: botocore.exceptions.ClientError: any error from boto3 other than key not found is passed through. """ try: return s3_conn.head_object(Bucket=bucket, Key=key) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': return None else: raise
python
def _head_object(s3_conn, bucket, key): """Retrieve information about an object in S3 if it exists. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket containing the key. key (str): name of the key to lookup. Returns: dict: S3 object information, or None if the object does not exist. See the AWS documentation for explanation of the contents. Raises: botocore.exceptions.ClientError: any error from boto3 other than key not found is passed through. """ try: return s3_conn.head_object(Bucket=bucket, Key=key) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == '404': return None else: raise
[ "def", "_head_object", "(", "s3_conn", ",", "bucket", ",", "key", ")", ":", "try", ":", "return", "s3_conn", ".", "head_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as",...
Retrieve information about an object in S3 if it exists. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket containing the key. key (str): name of the key to lookup. Returns: dict: S3 object information, or None if the object does not exist. See the AWS documentation for explanation of the contents. Raises: botocore.exceptions.ClientError: any error from boto3 other than key not found is passed through.
[ "Retrieve", "information", "about", "an", "object", "in", "S3", "if", "it", "exists", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L172-L194
train
214,582
cloudtools/stacker
stacker/hooks/aws_lambda.py
_upload_code
def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash, payload_acl): """Upload a ZIP file to S3 for use by Lambda. The key used for the upload will be unique based on the checksum of the contents. No changes will be made if the contents in S3 already match the expected contents. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to create. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. contents (str): byte string with the content of the file upload. content_hash (str): md5 hash of the contents to be uploaded. payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation Lambda Code object, pointing to the uploaded payload in S3. Raises: botocore.exceptions.ClientError: any error from boto3 is passed through. """ logger.debug('lambda: ZIP hash: %s', content_hash) key = '{}lambda-{}-{}.zip'.format(prefix, name, content_hash) if _head_object(s3_conn, bucket, key): logger.info('lambda: object %s already exists, not uploading', key) else: logger.info('lambda: uploading object %s', key) s3_conn.put_object(Bucket=bucket, Key=key, Body=contents, ContentType='application/zip', ACL=payload_acl) return Code(S3Bucket=bucket, S3Key=key)
python
def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash, payload_acl): """Upload a ZIP file to S3 for use by Lambda. The key used for the upload will be unique based on the checksum of the contents. No changes will be made if the contents in S3 already match the expected contents. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to create. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. contents (str): byte string with the content of the file upload. content_hash (str): md5 hash of the contents to be uploaded. payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation Lambda Code object, pointing to the uploaded payload in S3. Raises: botocore.exceptions.ClientError: any error from boto3 is passed through. """ logger.debug('lambda: ZIP hash: %s', content_hash) key = '{}lambda-{}-{}.zip'.format(prefix, name, content_hash) if _head_object(s3_conn, bucket, key): logger.info('lambda: object %s already exists, not uploading', key) else: logger.info('lambda: uploading object %s', key) s3_conn.put_object(Bucket=bucket, Key=key, Body=contents, ContentType='application/zip', ACL=payload_acl) return Code(S3Bucket=bucket, S3Key=key)
[ "def", "_upload_code", "(", "s3_conn", ",", "bucket", ",", "prefix", ",", "name", ",", "contents", ",", "content_hash", ",", "payload_acl", ")", ":", "logger", ".", "debug", "(", "'lambda: ZIP hash: %s'", ",", "content_hash", ")", "key", "=", "'{}lambda-{}-{}....
Upload a ZIP file to S3 for use by Lambda. The key used for the upload will be unique based on the checksum of the contents. No changes will be made if the contents in S3 already match the expected contents. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to create. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. contents (str): byte string with the content of the file upload. content_hash (str): md5 hash of the contents to be uploaded. payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation Lambda Code object, pointing to the uploaded payload in S3. Raises: botocore.exceptions.ClientError: any error from boto3 is passed through.
[ "Upload", "a", "ZIP", "file", "to", "S3", "for", "use", "by", "Lambda", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L197-L237
train
214,583
cloudtools/stacker
stacker/hooks/aws_lambda.py
_check_pattern_list
def _check_pattern_list(patterns, key, default=None): """Validates file search patterns from user configuration. Acceptable input is a string (which will be converted to a singleton list), a list of strings, or anything falsy (such as None or an empty dictionary). Empty or unset input will be converted to a default. Args: patterns: input from user configuration (YAML). key (str): name of the configuration key the input came from, used for error display purposes. Keyword Args: default: value to return in case the input is empty or unset. Returns: list[str]: validated list of patterns Raises: ValueError: if the input is unacceptable. """ if not patterns: return default if isinstance(patterns, basestring): return [patterns] if isinstance(patterns, list): if all(isinstance(p, basestring) for p in patterns): return patterns raise ValueError("Invalid file patterns in key '{}': must be a string or " 'list of strings'.format(key))
python
def _check_pattern_list(patterns, key, default=None): """Validates file search patterns from user configuration. Acceptable input is a string (which will be converted to a singleton list), a list of strings, or anything falsy (such as None or an empty dictionary). Empty or unset input will be converted to a default. Args: patterns: input from user configuration (YAML). key (str): name of the configuration key the input came from, used for error display purposes. Keyword Args: default: value to return in case the input is empty or unset. Returns: list[str]: validated list of patterns Raises: ValueError: if the input is unacceptable. """ if not patterns: return default if isinstance(patterns, basestring): return [patterns] if isinstance(patterns, list): if all(isinstance(p, basestring) for p in patterns): return patterns raise ValueError("Invalid file patterns in key '{}': must be a string or " 'list of strings'.format(key))
[ "def", "_check_pattern_list", "(", "patterns", ",", "key", ",", "default", "=", "None", ")", ":", "if", "not", "patterns", ":", "return", "default", "if", "isinstance", "(", "patterns", ",", "basestring", ")", ":", "return", "[", "patterns", "]", "if", "...
Validates file search patterns from user configuration. Acceptable input is a string (which will be converted to a singleton list), a list of strings, or anything falsy (such as None or an empty dictionary). Empty or unset input will be converted to a default. Args: patterns: input from user configuration (YAML). key (str): name of the configuration key the input came from, used for error display purposes. Keyword Args: default: value to return in case the input is empty or unset. Returns: list[str]: validated list of patterns Raises: ValueError: if the input is unacceptable.
[ "Validates", "file", "search", "patterns", "from", "user", "configuration", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L240-L272
train
214,584
cloudtools/stacker
stacker/hooks/aws_lambda.py
_upload_function
def _upload_function(s3_conn, bucket, prefix, name, options, follow_symlinks, payload_acl): """Builds a Lambda payload from user configuration and uploads it to S3. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to upload to. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. options (dict): configuration for how to build the payload. Consists of the following keys: * path: base path to retrieve files from (mandatory). If not absolute, it will be interpreted as relative to the stacker configuration file directory, then converted to an absolute path. See :func:`stacker.util.get_config_directory`. * include: file patterns to include in the payload (optional). * exclude: file patterns to exclude from the payload (optional). follow_symlinks (bool): If true, symlinks will be included in the resulting zip file payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation AWS Lambda Code object, pointing to the uploaded object in S3. Raises: ValueError: if any configuration is invalid. botocore.exceptions.ClientError: any error from boto3 is passed through. """ try: root = os.path.expanduser(options['path']) except KeyError as e: raise ValueError( "missing required property '{}' in function '{}'".format( e.args[0], name)) includes = _check_pattern_list(options.get('include'), 'include', default=['**']) excludes = _check_pattern_list(options.get('exclude'), 'exclude', default=[]) logger.debug('lambda: processing function %s', name) # os.path.join will ignore other parameters if the right-most one is an # absolute path, which is exactly what we want. if not os.path.isabs(root): root = os.path.abspath(os.path.join(get_config_directory(), root)) zip_contents, content_hash = _zip_from_file_patterns(root, includes, excludes, follow_symlinks) return _upload_code(s3_conn, bucket, prefix, name, zip_contents, content_hash, payload_acl)
python
def _upload_function(s3_conn, bucket, prefix, name, options, follow_symlinks, payload_acl): """Builds a Lambda payload from user configuration and uploads it to S3. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to upload to. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. options (dict): configuration for how to build the payload. Consists of the following keys: * path: base path to retrieve files from (mandatory). If not absolute, it will be interpreted as relative to the stacker configuration file directory, then converted to an absolute path. See :func:`stacker.util.get_config_directory`. * include: file patterns to include in the payload (optional). * exclude: file patterns to exclude from the payload (optional). follow_symlinks (bool): If true, symlinks will be included in the resulting zip file payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation AWS Lambda Code object, pointing to the uploaded object in S3. Raises: ValueError: if any configuration is invalid. botocore.exceptions.ClientError: any error from boto3 is passed through. """ try: root = os.path.expanduser(options['path']) except KeyError as e: raise ValueError( "missing required property '{}' in function '{}'".format( e.args[0], name)) includes = _check_pattern_list(options.get('include'), 'include', default=['**']) excludes = _check_pattern_list(options.get('exclude'), 'exclude', default=[]) logger.debug('lambda: processing function %s', name) # os.path.join will ignore other parameters if the right-most one is an # absolute path, which is exactly what we want. if not os.path.isabs(root): root = os.path.abspath(os.path.join(get_config_directory(), root)) zip_contents, content_hash = _zip_from_file_patterns(root, includes, excludes, follow_symlinks) return _upload_code(s3_conn, bucket, prefix, name, zip_contents, content_hash, payload_acl)
[ "def", "_upload_function", "(", "s3_conn", ",", "bucket", ",", "prefix", ",", "name", ",", "options", ",", "follow_symlinks", ",", "payload_acl", ")", ":", "try", ":", "root", "=", "os", ".", "path", ".", "expanduser", "(", "options", "[", "'path'", "]",...
Builds a Lambda payload from user configuration and uploads it to S3. Args: s3_conn (botocore.client.S3): S3 connection to use for operations. bucket (str): name of the bucket to upload to. prefix (str): S3 prefix to prepend to the constructed key name for the uploaded file name (str): desired name of the Lambda function. Will be used to construct a key name for the uploaded file. options (dict): configuration for how to build the payload. Consists of the following keys: * path: base path to retrieve files from (mandatory). If not absolute, it will be interpreted as relative to the stacker configuration file directory, then converted to an absolute path. See :func:`stacker.util.get_config_directory`. * include: file patterns to include in the payload (optional). * exclude: file patterns to exclude from the payload (optional). follow_symlinks (bool): If true, symlinks will be included in the resulting zip file payload_acl (str): The canned S3 object ACL to be applied to the uploaded payload Returns: troposphere.awslambda.Code: CloudFormation AWS Lambda Code object, pointing to the uploaded object in S3. Raises: ValueError: if any configuration is invalid. botocore.exceptions.ClientError: any error from boto3 is passed through.
[ "Builds", "a", "Lambda", "payload", "from", "user", "configuration", "and", "uploads", "it", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L275-L335
train
214,585
cloudtools/stacker
stacker/hooks/aws_lambda.py
select_bucket_region
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, provider_region): """Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. stacker_bucket_region (str): The contents of the `stacker_bucket_region` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string. """ region = None if custom_bucket: region = hook_region else: region = stacker_bucket_region return region or provider_region
python
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, provider_region): """Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. stacker_bucket_region (str): The contents of the `stacker_bucket_region` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string. """ region = None if custom_bucket: region = hook_region else: region = stacker_bucket_region return region or provider_region
[ "def", "select_bucket_region", "(", "custom_bucket", ",", "hook_region", ",", "stacker_bucket_region", ",", "provider_region", ")", ":", "region", "=", "None", "if", "custom_bucket", ":", "region", "=", "hook_region", "else", ":", "region", "=", "stacker_bucket_regi...
Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str): The contents of the `bucket_region` argument to the hook. stacker_bucket_region (str): The contents of the `stacker_bucket_region` global setting. provider_region (str): The region being used by the provider. Returns: str: The appropriate region string.
[ "Returns", "the", "appropriate", "region", "to", "use", "when", "uploading", "functions", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L338-L361
train
214,586
cloudtools/stacker
stacker/hooks/aws_lambda.py
upload_lambda_functions
def upload_lambda_functions(context, provider, **kwargs): """Builds Lambda payloads from user configuration and uploads them to S3. Constructs ZIP archives containing files matching specified patterns for each function, uploads the result to Amazon S3, then stores objects (of type :class:`troposphere.awslambda.Code`) in the context's hook data, ready to be referenced in blueprints. Configuration consists of some global options, and a dictionary of function specifications. In the specifications, each key indicating the name of the function (used for generating names for artifacts), and the value determines what files to include in the ZIP (see more details below). Payloads are uploaded to either a custom bucket or stackers default bucket, with the key containing it's checksum, to allow repeated uploads to be skipped in subsequent runs. The configuration settings are documented as keyword arguments below. Keyword Arguments: bucket (str, optional): Custom bucket to upload functions to. Omitting it will cause the default stacker bucket to be used. bucket_region (str, optional): The region in which the bucket should exist. If not given, the region will be either be that of the global `stacker_bucket_region` setting, or else the region in use by the provider. prefix (str, optional): S3 key prefix to prepend to the uploaded zip name. follow_symlinks (bool, optional): Will determine if symlinks should be followed and included with the zip artifact. Default: False payload_acl (str, optional): The canned S3 object ACL to be applied to the uploaded payload. Default: private functions (dict): Configurations of desired payloads to build. Keys correspond to function names, used to derive key names for the payload. Each value should itself be a dictionary, with the following data: * path (str): Base directory of the Lambda function payload content. If it not an absolute path, it will be considered relative to the directory containing the stacker configuration file in use. Files in this directory will be added to the payload ZIP, according to the include and exclude patterns. If not patterns are provided, all files in this directory (respecting default exclusions) will be used. Files are stored in the archive with path names relative to this directory. So, for example, all the files contained directly under this directory will be added to the root of the ZIP file. * include(str or list[str], optional): Pattern or list of patterns of files to include in the payload. If provided, only files that match these patterns will be included in the payload. Omitting it is equivalent to accepting all files that are not otherwise excluded. * exclude(str or list[str], optional): Pattern or list of patterns of files to exclude from the payload. If provided, any files that match will be ignored, regardless of whether they match an inclusion pattern. Commonly ignored files are already excluded by default, such as ``.git``, ``.svn``, ``__pycache__``, ``*.pyc``, ``.gitignore``, etc. Examples: .. Hook configuration. .. code-block:: yaml pre_build: - path: stacker.hooks.aws_lambda.upload_lambda_functions required: true enabled: true data_key: lambda args: bucket: custom-bucket follow_symlinks: true prefix: cloudformation-custom-resources/ payload_acl: authenticated-read functions: MyFunction: path: ./lambda_functions include: - '*.py' - '*.txt' exclude: - '*.pyc' - test/ .. Blueprint usage .. code-block:: python from troposphere.awslambda import Function from stacker.blueprints.base import Blueprint class LambdaBlueprint(Blueprint): def create_template(self): code = self.context.hook_data['lambda']['MyFunction'] self.template.add_resource( Function( 'MyFunction', Code=code, Handler='my_function.handler', Role='...', Runtime='python2.7' ) ) """ custom_bucket = kwargs.get('bucket') if not custom_bucket: bucket_name = context.bucket_name logger.info("lambda: using default bucket from stacker: %s", bucket_name) else: bucket_name = custom_bucket logger.info("lambda: using custom bucket: %s", bucket_name) custom_bucket_region = kwargs.get("bucket_region") if not custom_bucket and custom_bucket_region: raise ValueError("Cannot specify `bucket_region` without specifying " "`bucket`.") bucket_region = select_bucket_region( custom_bucket, custom_bucket_region, context.config.stacker_bucket_region, provider.region ) # Check if we should walk / follow symlinks follow_symlinks = kwargs.get('follow_symlinks', False) if not isinstance(follow_symlinks, bool): raise ValueError('follow_symlinks option must be a boolean') # Check for S3 object acl. Valid values from: # https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl payload_acl = kwargs.get('payload_acl', 'private') # Always use the global client for s3 session = get_session(bucket_region) s3_client = session.client('s3') ensure_s3_bucket(s3_client, bucket_name, bucket_region) prefix = kwargs.get('prefix', '') results = {} for name, options in kwargs['functions'].items(): results[name] = _upload_function(s3_client, bucket_name, prefix, name, options, follow_symlinks, payload_acl) return results
python
def upload_lambda_functions(context, provider, **kwargs): """Builds Lambda payloads from user configuration and uploads them to S3. Constructs ZIP archives containing files matching specified patterns for each function, uploads the result to Amazon S3, then stores objects (of type :class:`troposphere.awslambda.Code`) in the context's hook data, ready to be referenced in blueprints. Configuration consists of some global options, and a dictionary of function specifications. In the specifications, each key indicating the name of the function (used for generating names for artifacts), and the value determines what files to include in the ZIP (see more details below). Payloads are uploaded to either a custom bucket or stackers default bucket, with the key containing it's checksum, to allow repeated uploads to be skipped in subsequent runs. The configuration settings are documented as keyword arguments below. Keyword Arguments: bucket (str, optional): Custom bucket to upload functions to. Omitting it will cause the default stacker bucket to be used. bucket_region (str, optional): The region in which the bucket should exist. If not given, the region will be either be that of the global `stacker_bucket_region` setting, or else the region in use by the provider. prefix (str, optional): S3 key prefix to prepend to the uploaded zip name. follow_symlinks (bool, optional): Will determine if symlinks should be followed and included with the zip artifact. Default: False payload_acl (str, optional): The canned S3 object ACL to be applied to the uploaded payload. Default: private functions (dict): Configurations of desired payloads to build. Keys correspond to function names, used to derive key names for the payload. Each value should itself be a dictionary, with the following data: * path (str): Base directory of the Lambda function payload content. If it not an absolute path, it will be considered relative to the directory containing the stacker configuration file in use. Files in this directory will be added to the payload ZIP, according to the include and exclude patterns. If not patterns are provided, all files in this directory (respecting default exclusions) will be used. Files are stored in the archive with path names relative to this directory. So, for example, all the files contained directly under this directory will be added to the root of the ZIP file. * include(str or list[str], optional): Pattern or list of patterns of files to include in the payload. If provided, only files that match these patterns will be included in the payload. Omitting it is equivalent to accepting all files that are not otherwise excluded. * exclude(str or list[str], optional): Pattern or list of patterns of files to exclude from the payload. If provided, any files that match will be ignored, regardless of whether they match an inclusion pattern. Commonly ignored files are already excluded by default, such as ``.git``, ``.svn``, ``__pycache__``, ``*.pyc``, ``.gitignore``, etc. Examples: .. Hook configuration. .. code-block:: yaml pre_build: - path: stacker.hooks.aws_lambda.upload_lambda_functions required: true enabled: true data_key: lambda args: bucket: custom-bucket follow_symlinks: true prefix: cloudformation-custom-resources/ payload_acl: authenticated-read functions: MyFunction: path: ./lambda_functions include: - '*.py' - '*.txt' exclude: - '*.pyc' - test/ .. Blueprint usage .. code-block:: python from troposphere.awslambda import Function from stacker.blueprints.base import Blueprint class LambdaBlueprint(Blueprint): def create_template(self): code = self.context.hook_data['lambda']['MyFunction'] self.template.add_resource( Function( 'MyFunction', Code=code, Handler='my_function.handler', Role='...', Runtime='python2.7' ) ) """ custom_bucket = kwargs.get('bucket') if not custom_bucket: bucket_name = context.bucket_name logger.info("lambda: using default bucket from stacker: %s", bucket_name) else: bucket_name = custom_bucket logger.info("lambda: using custom bucket: %s", bucket_name) custom_bucket_region = kwargs.get("bucket_region") if not custom_bucket and custom_bucket_region: raise ValueError("Cannot specify `bucket_region` without specifying " "`bucket`.") bucket_region = select_bucket_region( custom_bucket, custom_bucket_region, context.config.stacker_bucket_region, provider.region ) # Check if we should walk / follow symlinks follow_symlinks = kwargs.get('follow_symlinks', False) if not isinstance(follow_symlinks, bool): raise ValueError('follow_symlinks option must be a boolean') # Check for S3 object acl. Valid values from: # https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl payload_acl = kwargs.get('payload_acl', 'private') # Always use the global client for s3 session = get_session(bucket_region) s3_client = session.client('s3') ensure_s3_bucket(s3_client, bucket_name, bucket_region) prefix = kwargs.get('prefix', '') results = {} for name, options in kwargs['functions'].items(): results[name] = _upload_function(s3_client, bucket_name, prefix, name, options, follow_symlinks, payload_acl) return results
[ "def", "upload_lambda_functions", "(", "context", ",", "provider", ",", "*", "*", "kwargs", ")", ":", "custom_bucket", "=", "kwargs", ".", "get", "(", "'bucket'", ")", "if", "not", "custom_bucket", ":", "bucket_name", "=", "context", ".", "bucket_name", "log...
Builds Lambda payloads from user configuration and uploads them to S3. Constructs ZIP archives containing files matching specified patterns for each function, uploads the result to Amazon S3, then stores objects (of type :class:`troposphere.awslambda.Code`) in the context's hook data, ready to be referenced in blueprints. Configuration consists of some global options, and a dictionary of function specifications. In the specifications, each key indicating the name of the function (used for generating names for artifacts), and the value determines what files to include in the ZIP (see more details below). Payloads are uploaded to either a custom bucket or stackers default bucket, with the key containing it's checksum, to allow repeated uploads to be skipped in subsequent runs. The configuration settings are documented as keyword arguments below. Keyword Arguments: bucket (str, optional): Custom bucket to upload functions to. Omitting it will cause the default stacker bucket to be used. bucket_region (str, optional): The region in which the bucket should exist. If not given, the region will be either be that of the global `stacker_bucket_region` setting, or else the region in use by the provider. prefix (str, optional): S3 key prefix to prepend to the uploaded zip name. follow_symlinks (bool, optional): Will determine if symlinks should be followed and included with the zip artifact. Default: False payload_acl (str, optional): The canned S3 object ACL to be applied to the uploaded payload. Default: private functions (dict): Configurations of desired payloads to build. Keys correspond to function names, used to derive key names for the payload. Each value should itself be a dictionary, with the following data: * path (str): Base directory of the Lambda function payload content. If it not an absolute path, it will be considered relative to the directory containing the stacker configuration file in use. Files in this directory will be added to the payload ZIP, according to the include and exclude patterns. If not patterns are provided, all files in this directory (respecting default exclusions) will be used. Files are stored in the archive with path names relative to this directory. So, for example, all the files contained directly under this directory will be added to the root of the ZIP file. * include(str or list[str], optional): Pattern or list of patterns of files to include in the payload. If provided, only files that match these patterns will be included in the payload. Omitting it is equivalent to accepting all files that are not otherwise excluded. * exclude(str or list[str], optional): Pattern or list of patterns of files to exclude from the payload. If provided, any files that match will be ignored, regardless of whether they match an inclusion pattern. Commonly ignored files are already excluded by default, such as ``.git``, ``.svn``, ``__pycache__``, ``*.pyc``, ``.gitignore``, etc. Examples: .. Hook configuration. .. code-block:: yaml pre_build: - path: stacker.hooks.aws_lambda.upload_lambda_functions required: true enabled: true data_key: lambda args: bucket: custom-bucket follow_symlinks: true prefix: cloudformation-custom-resources/ payload_acl: authenticated-read functions: MyFunction: path: ./lambda_functions include: - '*.py' - '*.txt' exclude: - '*.pyc' - test/ .. Blueprint usage .. code-block:: python from troposphere.awslambda import Function from stacker.blueprints.base import Blueprint class LambdaBlueprint(Blueprint): def create_template(self): code = self.context.hook_data['lambda']['MyFunction'] self.template.add_resource( Function( 'MyFunction', Code=code, Handler='my_function.handler', Role='...', Runtime='python2.7' ) )
[ "Builds", "Lambda", "payloads", "from", "user", "configuration", "and", "uploads", "them", "to", "S3", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L364-L523
train
214,587
cloudtools/stacker
stacker/lookups/handlers/kms.py
KmsLookup.handle
def handle(cls, value, **kwargs): """Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. For example: # We use the aws cli to get the encrypted value for the string # "PASSWORD" using the master key called "myStackerKey" in # us-east-1 $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \ --plaintext "PASSWORD" --output text --query CiphertextBlob CiD6bC8t2Y<...encrypted blob...> # In stacker we would reference the encrypted value like: conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>} You can optionally store the encrypted value in a file, ie: kms_value.txt us-east-1@CiD6bC8t2Y<...encrypted blob...> and reference it within stacker (NOTE: the path should be relative to the stacker config file): conf_key: ${kms file://kms_value.txt} # Both of the above would resolve to conf_key: PASSWORD """ value = read_value_from_path(value) region = None if "@" in value: region, value = value.split("@", 1) kms = get_session(region).client('kms') # encode str value as an utf-8 bytestring for use with codecs.decode. value = value.encode('utf-8') # get raw but still encrypted value from base64 version. decoded = codecs.decode(value, 'base64') # decrypt and return the plain text raw value. return kms.decrypt(CiphertextBlob=decoded)["Plaintext"]
python
def handle(cls, value, **kwargs): """Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. For example: # We use the aws cli to get the encrypted value for the string # "PASSWORD" using the master key called "myStackerKey" in # us-east-1 $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \ --plaintext "PASSWORD" --output text --query CiphertextBlob CiD6bC8t2Y<...encrypted blob...> # In stacker we would reference the encrypted value like: conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>} You can optionally store the encrypted value in a file, ie: kms_value.txt us-east-1@CiD6bC8t2Y<...encrypted blob...> and reference it within stacker (NOTE: the path should be relative to the stacker config file): conf_key: ${kms file://kms_value.txt} # Both of the above would resolve to conf_key: PASSWORD """ value = read_value_from_path(value) region = None if "@" in value: region, value = value.split("@", 1) kms = get_session(region).client('kms') # encode str value as an utf-8 bytestring for use with codecs.decode. value = value.encode('utf-8') # get raw but still encrypted value from base64 version. decoded = codecs.decode(value, 'base64') # decrypt and return the plain text raw value. return kms.decrypt(CiphertextBlob=decoded)["Plaintext"]
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "read_value_from_path", "(", "value", ")", "region", "=", "None", "if", "\"@\"", "in", "value", ":", "region", ",", "value", "=", "value", ".", "split", "(", ...
Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if not specified. For example: # We use the aws cli to get the encrypted value for the string # "PASSWORD" using the master key called "myStackerKey" in # us-east-1 $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \ --plaintext "PASSWORD" --output text --query CiphertextBlob CiD6bC8t2Y<...encrypted blob...> # In stacker we would reference the encrypted value like: conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>} You can optionally store the encrypted value in a file, ie: kms_value.txt us-east-1@CiD6bC8t2Y<...encrypted blob...> and reference it within stacker (NOTE: the path should be relative to the stacker config file): conf_key: ${kms file://kms_value.txt} # Both of the above would resolve to conf_key: PASSWORD
[ "Decrypt", "the", "specified", "value", "with", "a", "master", "key", "in", "KMS", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/kms.py#L15-L67
train
214,588
cloudtools/stacker
stacker/actions/diff.py
diff_dictionaries
def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [DictValue] """ old_set = set(old_dict) new_set = set(new_dict) added_set = new_set - old_set removed_set = old_set - new_set common_set = old_set & new_set changes = 0 output = [] for key in added_set: changes += 1 output.append(DictValue(key, None, new_dict[key])) for key in removed_set: changes += 1 output.append(DictValue(key, old_dict[key], None)) for key in common_set: output.append(DictValue(key, old_dict[key], new_dict[key])) if str(old_dict[key]) != str(new_dict[key]): changes += 1 output.sort(key=attrgetter("key")) return [changes, output]
python
def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [DictValue] """ old_set = set(old_dict) new_set = set(new_dict) added_set = new_set - old_set removed_set = old_set - new_set common_set = old_set & new_set changes = 0 output = [] for key in added_set: changes += 1 output.append(DictValue(key, None, new_dict[key])) for key in removed_set: changes += 1 output.append(DictValue(key, old_dict[key], None)) for key in common_set: output.append(DictValue(key, old_dict[key], new_dict[key])) if str(old_dict[key]) != str(new_dict[key]): changes += 1 output.sort(key=attrgetter("key")) return [changes, output]
[ "def", "diff_dictionaries", "(", "old_dict", ",", "new_dict", ")", ":", "old_set", "=", "set", "(", "old_dict", ")", "new_set", "=", "set", "(", "new_dict", ")", "added_set", "=", "new_set", "-", "old_set", "removed_set", "=", "old_set", "-", "new_set", "c...
Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [DictValue]
[ "Diffs", "two", "single", "dimension", "dictionaries" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L73-L111
train
214,589
cloudtools/stacker
stacker/actions/diff.py
diff_parameters
def diff_parameters(old_params, new_params): """Compares the old vs. new parameters and returns a "diff" If there are no changes, we return an empty list. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences """ [changes, diff] = diff_dictionaries(old_params, new_params) if changes == 0: return [] return diff
python
def diff_parameters(old_params, new_params): """Compares the old vs. new parameters and returns a "diff" If there are no changes, we return an empty list. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences """ [changes, diff] = diff_dictionaries(old_params, new_params) if changes == 0: return [] return diff
[ "def", "diff_parameters", "(", "old_params", ",", "new_params", ")", ":", "[", "changes", ",", "diff", "]", "=", "diff_dictionaries", "(", "old_params", ",", "new_params", ")", "if", "changes", "==", "0", ":", "return", "[", "]", "return", "diff" ]
Compares the old vs. new parameters and returns a "diff" If there are no changes, we return an empty list. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences
[ "Compares", "the", "old", "vs", ".", "new", "parameters", "and", "returns", "a", "diff" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L133-L148
train
214,590
cloudtools/stacker
stacker/actions/diff.py
normalize_json
def normalize_json(template): """Normalize our template for diffing. Args: template(str): string representing the template Returns: list: json representation of the parameters """ obj = parse_cloudformation_template(template) json_str = json.dumps( obj, sort_keys=True, indent=4, default=str, separators=(',', ': '), ) result = [] lines = json_str.split("\n") for line in lines: result.append(line + "\n") return result
python
def normalize_json(template): """Normalize our template for diffing. Args: template(str): string representing the template Returns: list: json representation of the parameters """ obj = parse_cloudformation_template(template) json_str = json.dumps( obj, sort_keys=True, indent=4, default=str, separators=(',', ': '), ) result = [] lines = json_str.split("\n") for line in lines: result.append(line + "\n") return result
[ "def", "normalize_json", "(", "template", ")", ":", "obj", "=", "parse_cloudformation_template", "(", "template", ")", "json_str", "=", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "default", "=", "str", ...
Normalize our template for diffing. Args: template(str): string representing the template Returns: list: json representation of the parameters
[ "Normalize", "our", "template", "for", "diffing", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L151-L168
train
214,591
cloudtools/stacker
stacker/actions/diff.py
DictValue.changes
def changes(self): """Returns a list of changes to represent the diff between old and new value. Returns: list: [string] representation of the change (if any) between old and new value """ output = [] if self.status() is self.UNMODIFIED: output = [self.formatter % (' ', self.key, self.old_value)] elif self.status() is self.ADDED: output.append(self.formatter % ('+', self.key, self.new_value)) elif self.status() is self.REMOVED: output.append(self.formatter % ('-', self.key, self.old_value)) elif self.status() is self.MODIFIED: output.append(self.formatter % ('-', self.key, self.old_value)) output.append(self.formatter % ('+', self.key, self.new_value)) return output
python
def changes(self): """Returns a list of changes to represent the diff between old and new value. Returns: list: [string] representation of the change (if any) between old and new value """ output = [] if self.status() is self.UNMODIFIED: output = [self.formatter % (' ', self.key, self.old_value)] elif self.status() is self.ADDED: output.append(self.formatter % ('+', self.key, self.new_value)) elif self.status() is self.REMOVED: output.append(self.formatter % ('-', self.key, self.old_value)) elif self.status() is self.MODIFIED: output.append(self.formatter % ('-', self.key, self.old_value)) output.append(self.formatter % ('+', self.key, self.new_value)) return output
[ "def", "changes", "(", "self", ")", ":", "output", "=", "[", "]", "if", "self", ".", "status", "(", ")", "is", "self", ".", "UNMODIFIED", ":", "output", "=", "[", "self", ".", "formatter", "%", "(", "' '", ",", "self", ".", "key", ",", "self", ...
Returns a list of changes to represent the diff between old and new value. Returns: list: [string] representation of the change (if any) between old and new value
[ "Returns", "a", "list", "of", "changes", "to", "represent", "the", "diff", "between", "old", "and", "new", "value", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L42-L60
train
214,592
cloudtools/stacker
stacker/actions/diff.py
Action._diff_stack
def _diff_stack(self, stack, **kwargs): """Handles the diffing a stack in CloudFormation vs our config""" if self.cancel.wait(0): return INTERRUPTED if not build.should_submit(stack): return NotSubmittedStatus() if not build.should_update(stack): return NotUpdatedStatus() provider = self.build_provider(stack) provider_stack = provider.get_stack(stack.fqn) # get the current stack template & params from AWS try: [old_template, old_params] = provider.get_stack_info( provider_stack) except exceptions.StackDoesNotExist: old_template = None old_params = {} stack.resolve(self.context, provider) # generate our own template & params parameters = self.build_parameters(stack) new_params = dict() for p in parameters: new_params[p['ParameterKey']] = p['ParameterValue'] new_template = stack.blueprint.rendered new_stack = normalize_json(new_template) output = ["============== Stack: %s ==============" % (stack.name,)] # If this is a completely new template dump our params & stack if not old_template: output.extend(self._build_new_template(new_stack, parameters)) else: # Diff our old & new stack/parameters old_template = parse_cloudformation_template(old_template) if isinstance(old_template, str): # YAML templates returned from CFN need parsing again # "AWSTemplateFormatVersion: \"2010-09-09\"\nParam..." # -> # AWSTemplateFormatVersion: "2010-09-09" old_template = parse_cloudformation_template(old_template) old_stack = normalize_json( json.dumps(old_template, sort_keys=True, indent=4, default=str) ) output.extend(build_stack_changes(stack.name, new_stack, old_stack, new_params, old_params)) ui.info('\n' + '\n'.join(output)) stack.set_outputs( provider.get_output_dict(provider_stack)) return COMPLETE
python
def _diff_stack(self, stack, **kwargs): """Handles the diffing a stack in CloudFormation vs our config""" if self.cancel.wait(0): return INTERRUPTED if not build.should_submit(stack): return NotSubmittedStatus() if not build.should_update(stack): return NotUpdatedStatus() provider = self.build_provider(stack) provider_stack = provider.get_stack(stack.fqn) # get the current stack template & params from AWS try: [old_template, old_params] = provider.get_stack_info( provider_stack) except exceptions.StackDoesNotExist: old_template = None old_params = {} stack.resolve(self.context, provider) # generate our own template & params parameters = self.build_parameters(stack) new_params = dict() for p in parameters: new_params[p['ParameterKey']] = p['ParameterValue'] new_template = stack.blueprint.rendered new_stack = normalize_json(new_template) output = ["============== Stack: %s ==============" % (stack.name,)] # If this is a completely new template dump our params & stack if not old_template: output.extend(self._build_new_template(new_stack, parameters)) else: # Diff our old & new stack/parameters old_template = parse_cloudformation_template(old_template) if isinstance(old_template, str): # YAML templates returned from CFN need parsing again # "AWSTemplateFormatVersion: \"2010-09-09\"\nParam..." # -> # AWSTemplateFormatVersion: "2010-09-09" old_template = parse_cloudformation_template(old_template) old_stack = normalize_json( json.dumps(old_template, sort_keys=True, indent=4, default=str) ) output.extend(build_stack_changes(stack.name, new_stack, old_stack, new_params, old_params)) ui.info('\n' + '\n'.join(output)) stack.set_outputs( provider.get_output_dict(provider_stack)) return COMPLETE
[ "def", "_diff_stack", "(", "self", ",", "stack", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "cancel", ".", "wait", "(", "0", ")", ":", "return", "INTERRUPTED", "if", "not", "build", ".", "should_submit", "(", "stack", ")", ":", "return", ...
Handles the diffing a stack in CloudFormation vs our config
[ "Handles", "the", "diffing", "a", "stack", "in", "CloudFormation", "vs", "our", "config" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/diff.py#L220-L278
train
214,593
cloudtools/stacker
stacker/actions/graph.py
each_step
def each_step(graph): """Returns an iterator that yields each step and it's direct dependencies. """ steps = graph.topological_sort() steps.reverse() for step in steps: deps = graph.downstream(step.name) yield (step, deps)
python
def each_step(graph): """Returns an iterator that yields each step and it's direct dependencies. """ steps = graph.topological_sort() steps.reverse() for step in steps: deps = graph.downstream(step.name) yield (step, deps)
[ "def", "each_step", "(", "graph", ")", ":", "steps", "=", "graph", ".", "topological_sort", "(", ")", "steps", ".", "reverse", "(", ")", "for", "step", "in", "steps", ":", "deps", "=", "graph", ".", "downstream", "(", "step", ".", "name", ")", "yield...
Returns an iterator that yields each step and it's direct dependencies.
[ "Returns", "an", "iterator", "that", "yields", "each", "step", "and", "it", "s", "direct", "dependencies", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L14-L24
train
214,594
cloudtools/stacker
stacker/actions/graph.py
dot_format
def dot_format(out, graph, name="digraph"): """Outputs the graph using the graphviz "dot" format.""" out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
python
def dot_format(out, graph, name="digraph"): """Outputs the graph using the graphviz "dot" format.""" out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
[ "def", "dot_format", "(", "out", ",", "graph", ",", "name", "=", "\"digraph\"", ")", ":", "out", ".", "write", "(", "\"digraph %s {\\n\"", "%", "name", ")", "for", "step", ",", "deps", "in", "each_step", "(", "graph", ")", ":", "for", "dep", "in", "d...
Outputs the graph using the graphviz "dot" format.
[ "Outputs", "the", "graph", "using", "the", "graphviz", "dot", "format", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L27-L35
train
214,595
cloudtools/stacker
stacker/actions/graph.py
json_format
def json_format(out, graph): """Outputs the graph in a machine readable JSON format.""" steps = {} for step, deps in each_step(graph): steps[step.name] = {} steps[step.name]["deps"] = [dep.name for dep in deps] json.dump({"steps": steps}, out, indent=4) out.write("\n")
python
def json_format(out, graph): """Outputs the graph in a machine readable JSON format.""" steps = {} for step, deps in each_step(graph): steps[step.name] = {} steps[step.name]["deps"] = [dep.name for dep in deps] json.dump({"steps": steps}, out, indent=4) out.write("\n")
[ "def", "json_format", "(", "out", ",", "graph", ")", ":", "steps", "=", "{", "}", "for", "step", ",", "deps", "in", "each_step", "(", "graph", ")", ":", "steps", "[", "step", ".", "name", "]", "=", "{", "}", "steps", "[", "step", ".", "name", "...
Outputs the graph in a machine readable JSON format.
[ "Outputs", "the", "graph", "in", "a", "machine", "readable", "JSON", "format", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L38-L46
train
214,596
cloudtools/stacker
stacker/actions/graph.py
Action.run
def run(self, format=None, reduce=False, *args, **kwargs): """Generates the underlying graph and prints it. """ plan = self._generate_plan() if reduce: # This will performa a transitive reduction on the underlying # graph, producing less edges. Mostly useful for the "dot" format, # when converting to PNG, so it creates a prettier/cleaner # dependency graph. plan.graph.transitive_reduction() fn = FORMATTERS[format] fn(sys.stdout, plan.graph) sys.stdout.flush()
python
def run(self, format=None, reduce=False, *args, **kwargs): """Generates the underlying graph and prints it. """ plan = self._generate_plan() if reduce: # This will performa a transitive reduction on the underlying # graph, producing less edges. Mostly useful for the "dot" format, # when converting to PNG, so it creates a prettier/cleaner # dependency graph. plan.graph.transitive_reduction() fn = FORMATTERS[format] fn(sys.stdout, plan.graph) sys.stdout.flush()
[ "def", "run", "(", "self", ",", "format", "=", "None", ",", "reduce", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plan", "=", "self", ".", "_generate_plan", "(", ")", "if", "reduce", ":", "# This will performa a transitive reducti...
Generates the underlying graph and prints it.
[ "Generates", "the", "underlying", "graph", "and", "prints", "it", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/graph.py#L63-L77
train
214,597
cloudtools/stacker
stacker/hooks/iam.py
get_cert_contents
def get_cert_contents(kwargs): """Builds parameters with server cert file contents. Args: kwargs(dict): The keyword args passed to ensure_server_cert_exists, optionally containing the paths to the cert, key and chain files. Returns: dict: A dictionary containing the appropriate parameters to supply to upload_server_certificate. An empty dictionary if there is a problem. """ paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.items(): if value is not None: continue path = input("Path to %s (skip): " % (key,)) if path == "skip" or not path.strip(): continue paths[key] = path parameters = { "ServerCertificateName": kwargs.get("cert_name"), } for key, path in paths.items(): if not path: continue # Allow passing of file like object for tests try: contents = path.read() except AttributeError: with open(utils.full_path(path)) as read_file: contents = read_file.read() if key == "certificate": parameters["CertificateBody"] = contents elif key == "private_key": parameters["PrivateKey"] = contents elif key == "chain": parameters["CertificateChain"] = contents return parameters
python
def get_cert_contents(kwargs): """Builds parameters with server cert file contents. Args: kwargs(dict): The keyword args passed to ensure_server_cert_exists, optionally containing the paths to the cert, key and chain files. Returns: dict: A dictionary containing the appropriate parameters to supply to upload_server_certificate. An empty dictionary if there is a problem. """ paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.items(): if value is not None: continue path = input("Path to %s (skip): " % (key,)) if path == "skip" or not path.strip(): continue paths[key] = path parameters = { "ServerCertificateName": kwargs.get("cert_name"), } for key, path in paths.items(): if not path: continue # Allow passing of file like object for tests try: contents = path.read() except AttributeError: with open(utils.full_path(path)) as read_file: contents = read_file.read() if key == "certificate": parameters["CertificateBody"] = contents elif key == "private_key": parameters["PrivateKey"] = contents elif key == "chain": parameters["CertificateChain"] = contents return parameters
[ "def", "get_cert_contents", "(", "kwargs", ")", ":", "paths", "=", "{", "\"certificate\"", ":", "kwargs", ".", "get", "(", "\"path_to_certificate\"", ")", ",", "\"private_key\"", ":", "kwargs", ".", "get", "(", "\"path_to_private_key\"", ")", ",", "\"chain\"", ...
Builds parameters with server cert file contents. Args: kwargs(dict): The keyword args passed to ensure_server_cert_exists, optionally containing the paths to the cert, key and chain files. Returns: dict: A dictionary containing the appropriate parameters to supply to upload_server_certificate. An empty dictionary if there is a problem.
[ "Builds", "parameters", "with", "server", "cert", "file", "contents", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/iam.py#L74-L124
train
214,598
cloudtools/stacker
stacker/blueprints/raw.py
get_template_path
def get_template_path(filename): """Find raw template in working directory or in sys.path. template_path from config may refer to templates colocated with the Stacker config, or files in remote package_sources. Here, we emulate python module loading to find the path to the template. Args: filename (str): Template filename. Returns: Optional[str]: Path to file, or None if no file found """ if os.path.isfile(filename): return os.path.abspath(filename) for i in sys.path: if os.path.isfile(os.path.join(i, filename)): return os.path.abspath(os.path.join(i, filename)) return None
python
def get_template_path(filename): """Find raw template in working directory or in sys.path. template_path from config may refer to templates colocated with the Stacker config, or files in remote package_sources. Here, we emulate python module loading to find the path to the template. Args: filename (str): Template filename. Returns: Optional[str]: Path to file, or None if no file found """ if os.path.isfile(filename): return os.path.abspath(filename) for i in sys.path: if os.path.isfile(os.path.join(i, filename)): return os.path.abspath(os.path.join(i, filename)) return None
[ "def", "get_template_path", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "filename", ")", "for", "i", "in", "sys", ".", "path", ":", "if", "os", ".",...
Find raw template in working directory or in sys.path. template_path from config may refer to templates colocated with the Stacker config, or files in remote package_sources. Here, we emulate python module loading to find the path to the template. Args: filename (str): Template filename. Returns: Optional[str]: Path to file, or None if no file found
[ "Find", "raw", "template", "in", "working", "directory", "or", "in", "sys", ".", "path", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/raw.py#L18-L38
train
214,599