desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Apply transformers/samplers, and predict_proba of the final
estimator
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
y_proba : array-like, shape = [n_samples, n_classes]'
| @if_delegate_has_method(delegate='_final_estimator')
def predict_proba(self, X):
| Xt = X
for (_, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
pass
else:
Xt = transform.transform(Xt)
return self.steps[(-1)][(-1)].predict_proba(Xt)
|
'Apply transformers/samplers, and decision_function of the final
estimator
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
y_score : array-like, shape = [n_samples, n_classes]'
| @if_delegate_has_method(delegate='_final_estimator')
def decision_function(self, X):
| Xt = X
for (_, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
pass
else:
Xt = transform.transform(Xt)
return self.steps[(-1)][(-1)].decision_function(Xt)
|
'Apply transformers/samplers, and predict_log_proba of the final
estimator
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
y_score : array-like, shape = [n_samples, n_classes]'
| @if_delegate_has_method(delegate='_final_estimator')
def predict_log_proba(self, X):
| Xt = X
for (_, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
pass
else:
Xt = transform.transform(Xt)
return self.steps[(-1)][(-1)].predict_log_proba(Xt)
|
'Apply transformers/samplers, and transform with the final estimator
This also works where final estimator is ``None``: all prior
transformations are applied.
Parameters
X : iterable
Data to transform. Must fulfill input requirements of first step
of the pipeline.
Returns
Xt : array-like, shape = [n_samples, n_transfor... | @property
def transform(self):
| if (self._final_estimator is not None):
self._final_estimator.transform
return self._transform
|
'Apply inverse transformations in reverse order
All estimators in the pipeline must support ``inverse_transform``.
Parameters
Xt : array-like, shape = [n_samples, n_transformed_features]
Data samples, where ``n_samples`` is the number of samples and
``n_features`` is the number of features. Must fulfill
input requireme... | @property
def inverse_transform(self):
| for (name, transform) in self.steps:
if (transform is not None):
transform.inverse_transform
return self._inverse_transform
|
'Apply transformers/samplers, and score with the final estimator
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=None
Targets used for scoring. Must fulfill label requirements for all
steps of the pipeline.
sample_weight : array-like, defa... | @if_delegate_has_method(delegate='_final_estimator')
def score(self, X, y=None, sample_weight=None):
| Xt = X
for (_, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
pass
else:
Xt = transform.transform(Xt)
score_params = {}
if (sample_weight is not None):
score_params['sample_weight'... |
'Create the objects required by NCR.'
| def _validate_estimator(self):
| self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors, additional_neighbor=1)
self.nn_.set_params(**{'n_jobs': self.n_jobs})
if (self.kind_sel not in SEL_KIND):
raise NotImplementedError
if ((self.threshold_cleaning > 1) or (self.threshold_cleaning < 0)):
raise ValueError("'t... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
enn = EditedNearestNeighbours(ratio=self.ratio, return_indices=True, random_state=self.random_state, size_ngh=self.size_ngh, n_neighbors=self.n_neighbors, kind_sel='mode', n_jobs=self.n_jobs)
(_, _, index_not_a1) = enn.fit_sample(X, y)
index_a1 = np.ones(y.shape, dtype=bool)
... |
'is_tomek uses the target vector and the first neighbour of every
sample point and looks for Tomek pairs. Returning a boolean vector with
True for majority Tomek links.
Parameters
y : ndarray, shape (n_samples, )
Target vector of the data set, necessary to keep track of whether a
sample belongs to minority or not
nn_in... | @staticmethod
def is_tomek(y, nn_index, class_type):
| links = np.zeros(len(y), dtype=bool)
class_excluded = [c for c in np.unique(y) if (c not in class_type)]
for (index_sample, target_sample) in enumerate(y):
if (target_sample in class_excluded):
continue
if (y[nn_index[index_sample]] != target_sample):
if (nn_index[nn_... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| nn = NearestNeighbors(n_neighbors=2, n_jobs=self.n_jobs)
nn.fit(X)
nns = nn.kneighbors(X, return_distance=False)[:, 1]
links = self.is_tomek(y, nns, self.ratio_)
if self.return_indices:
return (X[np.logical_not(links)], y[np.logical_not(links)], np.flatnonzero(np.logical_not(links)))
els... |
'Select the appropriate samples depending of the strategy selected.
Parameters
X : ndarray, shape (n_samples, n_features)
Original samples.
y : ndarray, shape (n_samples, )
Associated label to X.
dist_vec : ndarray, shape (n_samples, )
The distance matrix to the nearest neigbour.
num_samples: int
The desired number of ... | def _selection_dist_based(self, X, y, dist_vec, num_samples, key, sel_strategy='nearest'):
| dist_avg_vec = np.sum(dist_vec[:, (- self.nn_.n_neighbors):], axis=1)
if (dist_vec.shape[0] != X[(y == key)].shape[0]):
raise RuntimeError('The samples to be selected do not correspond to the distance matrix given. Ensure that both `X[y == key]` a... |
'Private function to create the NN estimator'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'size_ngh', 'n_neighbors')
if (self.version == 3):
deprecate_parameter(self, '0.2', 'ver3_samp_ngh', 'n_neighbors_ver3')
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors)
self.nn_.set_params(**{'n_jobs': self.n_jobs})
if (self.version == 3):
... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
if self.return_indices:
idx_under = np.empty((0,), dtype=int)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
self.nn_.fit(... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampled : ndarra... | def _sample(self, X, y):
| random_state = check_random_state(self.random_state)
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
if self.return_indices:
idx_under = np.empty((0,), dtype=int)
for target_class in np.unique(y):
if (target_class in self.ratio_.keys... |
'Validate the estimator created in the ENN.'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'size_ngh', 'n_neighbors')
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors, additional_neighbor=1)
self.nn_.set_params(**{'n_jobs': self.n_jobs})
if (self.kind_sel not in SEL_KIND):
raise NotImplementedError
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
if self.return_indices:
idx_under = np.empty((0,), dtype=int)
self.nn_.fit(X)
for target_class in np.unique(y):
if (target_class in self.ratio_.keys()):
... |
'Private function to create the NN estimator'
| def _validate_estimator(self):
| if (self.max_iter < 2):
raise ValueError('max_iter must be greater than 1. Got {} instead.'.format(type(self.max_iter)))
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors, additional_neighbor=1)
self.enn_ = EditedNearestNeighbours(ratio=self.ratio, return_indi... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
(X_, y_) = (X, y)
if self.return_indices:
idx_under = np.arange(X.shape[0], dtype=int)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
prev_len = y.shape[0]
for n_iter in range(self.max_iter):
prev_len = y_.shape[0... |
'Create objects required by AllKNN'
| def _validate_estimator(self):
| if (self.kind_sel not in SEL_KIND):
raise NotImplementedError
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors, additional_neighbor=1)
self.enn_ = EditedNearestNeighbours(ratio=self.ratio, return_indices=self.return_indices, random_state=self.random_state, n_neighbors=self.nn_, kind... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
(X_, y_) = (X, y)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
if self.return_indices:
idx_under = np.arange(X.shape[0], dtype=int)
for curr_size_ngh in range(1, self.nn_.n_neighbors):
self.enn_.n_neighbors = curr_s... |
'Private function to create the NN estimator'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'size_ngh', 'n_neighbors')
if (self.n_neighbors is None):
self.estimator_ = KNeighborsClassifier(n_neighbors=1, n_jobs=self.n_jobs)
elif isinstance(self.n_neighbors, int):
self.estimator_ = KNeighborsClassifier(n_neighbors=self.n_neighbors, n_jobs=self.n_jobs... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
random_state = check_random_state(self.random_state)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
if self.return_indices:
... |
'Private function to create the NN estimator'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'size_ngh', 'n_neighbors')
if (self.n_neighbors is None):
self.estimator_ = KNeighborsClassifier(n_neighbors=1, n_jobs=self.n_jobs)
elif isinstance(self.n_neighbors, int):
self.estimator_ = KNeighborsClassifier(n_neighbors=self.n_neighbors, n_jobs=self.n_jobs... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
random_state = check_random_state(self.random_state)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
if self.return_indices:
... |
'Private function to create the classifier'
| def _validate_estimator(self):
| if ((self.estimator is not None) and isinstance(self.estimator, ClassifierMixin) and hasattr(self.estimator, 'predict_proba')):
self.estimator_ = self.estimator
elif (self.estimator is None):
self.estimator_ = RandomForestClassifier(random_state=self.random_state, n_jobs=self.n_jobs)
elif ((... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
target_stats = Counter(y)
skf = _get_cv_splits(X, y, self.cv, self.random_state)
probabilities = np.zeros(y.shape[0], dtype=float)
for (train_index, test_index) in skf:
(X_train, X_test) = (X[train_index], X[test_index])
(y_train, y_test) = (y[train_index],... |
'Private function to create the KMeans estimator'
| def _validate_estimator(self):
| if (self.estimator is None):
self.estimator_ = KMeans(random_state=self.random_state, n_jobs=self.n_jobs)
elif isinstance(self.estimator, KMeans):
self.estimator_ = self.estimator
else:
raise ValueError('`estimator` has to be a KMeans clustering. Got {} ins... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype)
y_resampled = np.empty((0,), dtype=y.dtype)
for target_class in np.unique(y):
if (target_class in self.ratio_.keys()):
n_samples = self.ratio_[target_class]
self.estimator_.set_params(**{'n_... |
'Constructor.
Args:
request: The webapp2.Request object that contains information about the
current web request.
response: The webapp2.Response object that contains the response to be
sent back to the browser.'
| def __init__(self, request, response):
| self.initialize(request, response)
self.helper = AppDashboardHelper()
self.dstore = AppDashboardData(self.helper)
|
'Renders a template file with all variables loaded.
Args:
template_file: A str with the relative path to template file.
values: A dict with key/value pairs used as variables in the jinja
template files.
Returns:
A str with the rendered template.'
| def render_template(self, template_file, values=None):
| if (values is None):
values = {}
is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_application_info()
if (not is_cloud_admin):
apps_user_owns = self.helper.get_owned_apps()
new_app_dict = {}
for app_name in apps_user_owns:
... |
'Renders the shared navigation.
Returns:
A str with the navigation bar rendered.'
| def get_shared_navigation(self, page):
| show_create_account = True
if AppDashboardHelper.USE_SHIBBOLETH:
show_create_account = False
return self.render_template(template_file='shared/navigation.html', values={'show_create_account': show_create_account, 'page_name': page})
|
'Renders a template with the main layout and nav bar.'
| def render_page(self, page, template_file, values=None):
| if (values is None):
values = {}
self.response.headers['Content-Type'] = 'text/html'
template = jinja_environment.get_template('layouts/main.html')
self.response.out.write(template.render(page_name=page, page_body=self.render_template(template_file, values), shared_navigation=self.get_shared_nav... |
'Handler for GET requests.'
| def get(self):
| self.render_page(page='landing', template_file=self.TEMPLATE, values={'monitoring_url': self.dstore.get_monitoring_url()})
|
'Handler for GET requests.'
| def get(self):
| if self.request.get('forcerefresh'):
self.dstore.update_all()
self.render_page(page='dash', template_file=self.TEMPLATE, values={'server_info': self.helper.get_status_info(), 'dbinfo': self.dstore.get_database_info(), 'apps': self.helper.get_application_info().keys(), 'monitoring_url': self.dstore.get_m... |
'Handler for GET requests. Updates all the datastore values with
information from the AppController and UserAppServer.'
| def get(self):
| self.dstore.update_all()
self.response.out.write('datastore updated')
|
'Handler for POST requests. Updates all the datastore values with
information from the AppController and UserAppServer.'
| def post(self):
| self.dstore.update_all()
self.response.out.write('datastore updated')
|
'Handler for GET requests.'
| def get(self):
| if self.request.get('forcerefresh'):
self.dstore.update_all()
self.render_app_page(page='status', values={'server_info': self.helper.get_status_info(), 'dbinfo': self.dstore.get_database_info(), 'apps': self.helper.get_application_info(), 'monitoring_url': self.dstore.get_monitoring_url(), 'page_content... |
'Retrieves the cached information about machine-level statistics as a
JSON-encoded dict.'
| def get(self):
| self.response.out.write(json.dumps(AppDashboardHelper().get_status_info()))
|
'Parse the input from the create user form.
Returns:
A dict that maps the form fields on the user creation page to None (if
they pass our validation) or a str indicating why they fail our
validation.'
| def parse_new_user_post(self):
| users = {}
error_msgs = {}
users['email'] = cgi.escape(self.request.get('user_email'))
if re.match(self.USER_EMAIL_REGEX, users['email']):
error_msgs['email'] = None
else:
error_msgs['email'] = 'Format must be foo@boo.goo.'
users['password'] = cgi.escape(self.request.get... |
'Creates new user if parse was successful.
Args:
errors: A dict with True/False values for errors in each of the users
fields.
Returns:
True if user was created, and False otherwise.'
| def process_new_user_post(self, errors):
| if (errors['email'] or errors['password'] or errors['password_confirmation']):
return False
else:
return self.helper.create_new_user(cgi.escape(self.request.get('user_email')), cgi.escape(self.request.get('user_password')), self.response)
|
'Handler for POST requests.'
| def post(self):
| err_msgs = self.parse_new_user_post()
try:
user_created = self.process_new_user_post(err_msgs)
continue_url = self.request.get('continue')
if (user_created and continue_url):
self.redirect(str(continue_url), self.response)
return
elif user_created:
... |
'Handler for GET requests.'
| def get(self):
| self.render_page(page='users', template_file=self.TEMPLATE, values={'continue': self.request.get('continue'), 'user': {}, 'error_message_content': {}})
|
'Handler for POST requests.'
| def post(self):
| if ((self.request.get('continue') != '') and (self.request.get('commit') == 'Yes')):
self.redirect(self.request.get('continue').encode('ascii', 'ignore'), self.response)
elif AppDashboardHelper.USE_SHIBBOLETH:
self.redirect(AppDashboardHelper.SHIBBOLETH_CONNECTOR, self.response)
else:
... |
'Handler for GET requests.'
| def get(self):
| continue_url = urllib.unquote(self.request.get('continue'))
url_match = re.search(self.CONTINUE_URL_REGEX, continue_url)
if url_match:
continue_url = url_match.group(1)
self.render_page(page='users', template_file=self.TEMPLATE, values={'continue': continue_url})
|
'Handler for GET requests. Removes the AppScale login cookie and
redirects the user to the landing page.'
| def get(self):
| self.helper.logout_user(self.response)
continue_url = self.request.get('continue')
if continue_url:
self.redirect(str(continue_url), self.response)
elif AppDashboardHelper.USE_SHIBBOLETH:
self.redirect(AppDashboardHelper.SHIBBOLETH_CONNECTOR, self.response)
else:
self.redirec... |
'Handler for POST requests.'
| def post(self):
| user_email = self.request.get('user_email').lstrip().rstrip()
if self.helper.login_user(user_email, self.request.get('user_password'), self.response):
if (self.request.get('continue') != ''):
continue_url = self.request.get('continue').encode('ascii', 'ignore')
self.redirect(cont... |
'Handler for GET requests.'
| def get(self):
| show_create_account = True
if AppDashboardHelper.USE_SHIBBOLETH:
show_create_account = False
self.render_page(page='users', template_file=self.TEMPLATE, values={'continue': self.request.get('continue'), 'show_create_account': show_create_account})
|
'Handler for GET requests.'
| def get(self):
| logging.info('LoginPage: continue -> {0}'.format(self.request.get('continue')))
user_email = self.request.get('HTTP_SHIB_INETORGPERSON_MAIL').strip().lower()
logging.info('LoginPage: user_email: {0}'.format(user_email))
if user_email:
self.redirect('{1}/users/shibboleth?continue={... |
'Handler for GET requests.'
| def get(self):
| user_email = os.environ.get('HTTP_SHIB_INETORGPERSON_MAIL').strip().lower()
self.helper.create_token(user_email, user_email)
user_app_list = self.helper.get_user_app_list(user_email)
self.helper.set_appserver_cookie(user_email, user_app_list, self.response)
if (self.request.get('continue') != ''):
... |
'Update authorization matrix from form submission.
Returns:
A str with message to be displayed to the user.'
| def parse_update_user_permissions(self):
| perms = self.helper.get_all_permission_items()
req_keys = self.request.POST.keys()
response = ''
for (fieldname, email) in self.request.POST.iteritems():
if re.match(self.USER_PERMISSION_REGEX, fieldname):
for perm in perms:
key = '{0}-{1}'.format(email, perm)
... |
'Handler for POST requests.'
| def post(self):
| if self.dstore.is_user_cloud_admin():
try:
taskqueue.add(url='/status/refresh')
except Exception as err:
logging.exception(err)
self.render_app_page(page='authorize', values={'flash_message': self.parse_update_user_permissions(), 'user_perm_list': self.helper.list_all... |
'Handler for GET requests.'
| def get(self):
| if self.dstore.is_user_cloud_admin():
self.render_app_page(page='authorize', values={'user_perm_list': self.helper.list_all_users_permissions(), 'page_content': self.TEMPLATE})
else:
self.render_app_page(page='authorize', values={'flash_message': 'Only the cloud administrator can ... |
'Handler for POST requests.'
| def post(self):
| email = self.request.get('email')
password = self.request.get('password')
if self.dstore.is_user_cloud_admin():
(success, message) = self.helper.change_password(cgi.escape(email), cgi.escape(password))
else:
success = False
message = 'Only the cloud administrator can ... |
'Handler for GET requests.'
| def get(self):
| if self.dstore.is_user_cloud_admin():
self.render_app_page(page='authorize', values={'user_perm_list': self.helper.list_all_users_permissions(), 'page_content': self.TEMPLATE})
else:
self.render_app_page(page='authorize', values={'flash_message': 'Only the cloud administrator can ... |
'Handler for POST requests.'
| def post(self):
| success_msg = ''
err_msg = ''
if ((not self.request.POST.multi) or ('app_file_data' not in self.request.POST.multi) or (not hasattr(self.request.POST.multi['app_file_data'], 'file'))):
self.render_app_page(page='apps', values={'error_message': 'You must specify a file to upload.', ... |
'Handler for GET requests.'
| def get(self):
| self.render_app_page(page='apps', values={'page_content': self.TEMPLATE})
|
'Handler for POST requests.'
| def post(self):
| appname = self.request.POST.get('appname')
if (self.dstore.is_user_cloud_admin() or (appname in self.dstore.get_owned_apps())):
message = self.helper.delete_app(appname)
self.dstore.delete_app_from_datastore(appname)
try:
taskqueue.add(url='/status/refresh')
taskq... |
'Handler for GET requests.'
| def get(self):
| self.render_app_page(page='apps', values={'page_content': self.TEMPLATE})
|
'Handler for POST requests.'
| def post(self):
| success_msg = ''
err_msg = ''
if ((not self.request.POST.multi) or ('app_id' not in self.request.POST.multi)):
self.render_app_page(page='apps', values={'error_message': 'You must specify an app to relocate.', 'success_message': '', 'page_content': self.TEMPLATE})
return
... |
'Handler for GET requests.'
| def get(self):
| self.render_app_page(page='apps', values={'page_content': self.TEMPLATE})
|
'Retrieves the cached information about applications running in this
AppScale deployment as a JSON-encoded dict.'
| def get(self):
| is_cloud_admin = AppDashboardHelper().is_user_cloud_admin()
apps_user_is_admin_on = AppDashboardHelper().get_application_info()
if (not is_cloud_admin):
apps_user_owns = AppDashboardHelper().get_owned_apps()
new_app_dict = {}
for app_name in apps_user_owns:
if (app_name i... |
'Handler for GET requests.'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
if ((not is_cloud_admin) and (not apps_user_is_admin_on)):
self.redirect(DashPage.PATH, self.response)
query = ndb.gql('SELECT * FROM LoggedService')
all_services = []
for ent... |
'Displays a list of hosts that have logs for the given service.'
| def get(self, service_name):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
if ((not is_cloud_admin) and (service_name not in apps_user_is_admin_on)):
self.redirect(DashPage.PATH, self.response)
service = LoggedService.get_by_id(service_name)
if service:
e... |
'Displays all logs accumulated for the given service, on the named host.
Specifying \'all\' as the host indicates that we shouldn\'t restrict ourselves
to a single machine.'
| def get(self, service_name, host):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
if ((not is_cloud_admin) and (service_name not in apps_user_is_admin_on)):
self.redirect(DashPage.PATH, self.response)
encoded_cursor = self.request.get('next_cursor')
if (encoded_cursor a... |
'Saves logs records to the Datastore for later viewing.'
| def post(self):
| encoded_data = self.request.body
data = json.loads(encoded_data)
service_name = data['service_name']
host = data['host']
log_lines = data['logs']
service = LoggedService.get_by_id(service_name)
if (service is None):
service = LoggedService(id=service_name)
service.hosts = [ho... |
'Instructs the AppController to collect logs across all machines, place
it in this app\'s static file directory, and renders a page that will wait
for the logs to become available before downloading it.'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
if (not is_cloud_admin):
self.redirect(DashPage.PATH)
(success, uuid) = self.helper.gather_logs()
self.render_app_page(page='logs', values={'success': success, 'uuid': uuid, 'page_content': self.TEMPLATE})
|
'Shows deployed user applications that contain cron.yaml'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
if is_cloud_admin:
apps_user_is_admin_on = self.helper.get_application_info().keys()
else:
apps_user_is_admin_on = self.helper.get_owned_apps()
apps_with_cron_yaml = []
for app_id in apps_user_is_admin_on:
cron_info = self.he... |
'Shows active cron entries for given appid'
| def get(self):
| app_id = self.request.get('appid')
mail_to = []
cron_jobs = []
warnings = []
cron_info = self.helper.get_application_cron_info(app_id)
yaml_file = cron_info.get('cron_yaml_file', [])
etc_crond_file = cron_info.get('etc_crond_file', '')
try:
crond_file = crontab.CronTab(tab=etc_cr... |
'Runs specific cron job according to url param and
redirects user back to previous page.'
| def get(self):
| api_url = urllib.unquote(self.request.get('url'))
app_id = urllib.unquote(self.request.get('appid'))
if ((not api_url) or (not app_id)):
return
app_url = self.helper.get_application_info()[app_id][1]
response = urllib.urlopen((app_url + api_url))
self.redirect(('/cron/view?' + urllib.url... |
'Handler for GET request for the datastore statistics.
Returns:
The JSON output for testing.'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
app_name = self.request.get('appid')
if ((not is_cloud_admin) and (app_name not in apps_user_is_admin_on)):
response = json.dumps({'error': True, 'message': 'Not authorized'})
self.... |
'Converts KindStat entities to a json string.
Args:
kind_entities: A list of stats.KindStat.
Returns:
A JSON string containing kind statistic information.'
| def convert_to_json(self, kind_entities):
| items = []
for ent in kind_entities:
items.append({time.mktime(ent.timestamp.timetuple()): {ent.kind_name: {'bytes': ent.bytes, 'count': ent.count}}})
return json.dumps(items)
|
'Handler for GET request for the requests statistics.'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
app_name = self.request.get('appid')
if ((not is_cloud_admin) and (app_name not in apps_user_is_admin_on)):
response = json.dumps({'error': True, 'message': 'Not authorized'})
self.... |
'Fetches request per second information from the datastore for
a given application.
Args:
app_id: A str, the application identifier.
Returns:
A list of dictionaries filled with timestamps and number of
requests per second.'
| @staticmethod
def fetch_request_info(app_id):
| query = RequestInfo.query((RequestInfo.app_id == app_id))
request_info = []
for request in query.iter():
request_info.append({'timestamp': int(request.timestamp.strftime('%s')), 'num_of_requests': request.num_of_requests, 'avg_request_rate': request.avg_request_rate})
return request_info
|
'Handler for GET request for the requests statistics.'
| def get(self):
| for app_id in self.helper.get_application_info().keys():
self.dstore.update_request_info(app_id=app_id)
self.response.out.write('request info updated')
|
'Makes sure the user is allowed to see instance data for the named
application, and if so, retrieves it for them.'
| def get(self):
| is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
app_name = self.request.get('appid')
if ((not is_cloud_admin) and (app_name not in apps_user_is_admin_on)):
response = json.dumps({'error': True, 'message': 'Not authorized'})
self.... |
'Handler for GET request for the memcache statistics.'
| def get(self):
| if (not self.helper.is_user_cloud_admin()):
response = json.dumps({'error': True, 'message': 'Not authorized'})
self.response.out.write(response)
return
mem_stats = memcache.get_stats()
self.response.out.write(json.dumps(mem_stats))
|
'Calls the groomer and tells it that Kind statistics need to be
updated.'
| def get(self):
| self.response.out.write(json.dumps({'result': self.helper.run_groomer()}))
|
'Calls render_template to return the correct panel'
| def get(self):
| key_val = self.request.get('key_val')
self.response.out.write(self.render_template(template_file='layouts/panel.html', values={'page_info': self.dstore.get_panel_key_info(key_val), 'id': key_val}))
|
'sets the dashboard layout settings'
| def post(self):
| nav = self.request.get('nav')
panel = self.request.get('panel')
saved_dict = {'nav': json.loads(nav), 'panel': json.loads(panel)}
try:
self.dstore.set_dash_layout_settings(values=saved_dict)
self.response.set_status(200)
self.response.out.write('Saved')
except Exception as er... |
'sets the dashboard layout settings'
| def post(self):
| try:
self.dstore.set_dash_layout_settings()
self.response.set_status(200)
self.response.out.write('Layout Reset')
except Exception as err:
logging.exception(err)
self.response.set_status(500)
self.response.out.write('Try Again')
|
'Salts the given password with the provided username and encrypts it.
Args:
username: A str representing the username whose password we wish to
encrypt.
password: A str representing the password to encrypt.
Returns:
The SHA1-encrypted password.'
| @classmethod
def encrypt_password(cls, username, password):
| return hashlib.sha1('{0}{1}'.format(username, password)).hexdigest()
|
'Sets up SOAP client fields, to avoid creating a new SOAP connection for
every SOAP call.
Fields:
appcontroller: A AppControllerClient, which is a SOAP client connected to
the AppController running on this machine, responsible for service
deployment and configuration.
uaserver: A SOAP client connected to the UserAppSer... | def __init__(self):
| self.appcontroller = None
self.uaserver = None
self.cache = {'get_role_info': [], 'query_user_data': {}, 'user_caps': {}}
|
'Retrieves our saved AppController connection, creating a new one if none
currently exist.
Args:
server_ip: An IP address specifying which machine to make AppController
calls to.
Returns:
An AppControllerClient, representing a connection to the AppController.'
| def get_appcontroller_client(self, server_ip=MY_PUBLIC_IP):
| if (self.appcontroller is None):
self.appcontroller = AppControllerClient(server_ip, GLOBAL_SECRET_KEY)
return self.appcontroller
|
'Retrieves our saved UserAppServer connection, creating a new one if none
currently exist.
Returns:
An SOAPpy object, representing a connection to the UserAppServer.'
| def get_uaserver(self):
| if (self.uaserver is None):
self.uaserver = SOAPpy.SOAPProxy('https://{0}:{1}'.format(UA_SERVER_IP, self.UA_SERVER_PORT))
return self.uaserver
|
'Queries the UserAppServer to learn what actions the named user is
authorized to perform in this AppScale deployment.
Args:
email: A str containing the email of the user whose authorizations we want
to retrieve.
Returns:
A list, where each item is a str corresponding to an action this user is
authorized to perform in t... | def get_user_capabilities(self, email):
| if (email in self.cache['user_caps']):
return self.cache['user_caps'][email]
try:
capabilities = self.get_uaserver().get_capabilities(email, GLOBAL_SECRET_KEY).split(self.USER_CAPABILITIES_DELIMITER)
self.cache['user_caps'][email] = capabilities
return capabilities
except Exc... |
'Queries our local AppController to get server-level information about
every server running in this AppScale deployment.
Returns:
A list of dicts, where each dict contains VM-level info (e.g., CPU,
memory, disk usage) about that machine. The empty list is returned if
there was a problem retrieving this information.'
| def get_status_info(self):
| try:
nodes = self.get_appcontroller_client().get_cluster_stats()
statuses = []
for node in nodes:
cpu_usage = (100.0 - node['cpu']['idle'])
total_memory = (node['memory']['available'] + node['memory']['used'])
memory_usage = round(((100.0 * node['memory'][... |
'Queries the AppController to get instance information for a given app_id
Returns:
A list of dicts containing host, port, and language information for
each instance hosting the given application.'
| def get_instance_info(self, app_id):
| try:
instances = self.get_appcontroller_client().get_instance_info()
instance_infos = [{'host': instance.get('host'), 'port': instance.get('port'), 'language': instance.get('language')} for instance in instances if (instance.get('appid') == app_id)]
return instance_infos
except Exception... |
'Queries the AppController for information about which Google App Engine
applications are currently running, and if they are done loading, the URL
that they can be accessed at.
Returns:
A dict, where each key is a str indicating the name of a Google App Engine
application running in this deployment, and each value is e... | def get_application_info(self):
| try:
status_on_all_nodes = self.get_appcontroller_client().get_cluster_stats()
app_names_and_urls = {}
if (not status_on_all_nodes):
return {}
for status in status_on_all_nodes:
for (app, done_loading) in status['apps'].iteritems():
if (app == ... |
'Get an application cron info
Args:
app_name: A str containing the name of the app to be removed.
Returns:
A dict that contains the cron.yaml and /etc/cron.d/appscale-#app_id files content'
| def get_application_cron_info(self, app_name):
| try:
acc = self.get_appcontroller_client()
cron_info = acc.get_application_cron_info(app_name)
except Exception as err:
logging.exception(err)
return {}
return cron_info
|
'Queries the AppController to find a host running the named role.
Args:
role: A str indicating the name of the role we wish to find a hoster of.
Returns:
A str containing the publicly accessible hostname (IP address or FQDN)
of one machine that runs the specified service. Note that if multiple
services host the named r... | def get_host_with_role(self, role):
| acc = self.get_appcontroller_client()
if self.cache['get_role_info']:
nodes = self.cache['get_role_info']
else:
try:
nodes = acc.get_role_info()
self.cache['get_role_info'] = nodes
except Exception as err:
logging.exception(err)
return ... |
'Queries the AppController to learn which machine runs the shadow
service in this AppScale deployment.
Returns:
A str containing the hostname (an IP address or FQDN) of the machine
running the shadow service.'
| def get_head_node_ip(self):
| return self.get_host_with_role('shadow')
|
'Queries the AppController to learn the public IP of this
deployment.
Returns:
A str containing the hostname (an IP address or FQDN) of the machine
running the login service.'
| def get_login_ip(self):
| login_property = ''
acc = self.get_appcontroller_client()
try:
login_property = acc.get_property('login')
except Exception as err:
logging.exception(err)
return ''
return login_property.get('login')
|
'Queries the UserAppServer to learn which port the named application runs
on.
Note that we don\'t need to query the UserAppServer to learn which host the
application runs on, as it is always full proxied by the machine running the
login service.
Args:
appname: A str that indicates which application we want to find a ho... | def get_app_ports(self, appname):
| app_data = self.get_uaserver().get_app_data(appname, GLOBAL_SECRET_KEY)
result = json.loads(app_data)
if ((not result) or ('hosts' not in result) or (not result['hosts'].values())):
raise AppHelperException('{} does not have a port number.'.format(appname))
return [int(result['... |
'Checks for special characters in arguments that are part of shell
commands.
Args:
argument: A str, the argument to be checked.
Raises:
BadConfigurationException if single quotes are present in argument.'
| def shell_check(self, argument):
| if ("'" in argument):
raise BadConfigurationException(("Single quotes (') are not allowed " + 'in filenames.'))
|
'Uploads an Google App Engine application into this AppScale deployment.
Args:
filename: The name of the file that the user uploaded (used so that the
tempfile we write has the same extension).
upload_file: A file object containing the uploaded file\'s data.
Returns:
A str indicating that the application was uploaded s... | def upload_app(self, filename, upload_file):
| user = users.get_current_user()
if (not user):
raise AppHelperException('There was an error uploading your application. You must be logged in to upload applications.')
try:
self.shell_check(filename)
file_suffix = re.search('\\.(.*)\\Z', file... |
'Relocates a Google App Engine application to different ports.
Args:
appid: The application to be relocated
http_port: The HTTP Port to relocate the application to
https_port: The HTTPS Port to relocate the application to
Returns:
A str indicating that the application was relocated successfully.
Raises:
AppHelperExcept... | def relocate_app(self, appid, http_port, https_port):
| acc = self.get_appcontroller_client()
try:
relocate_info = acc.relocate_app(appid, http_port, https_port)
if (relocate_info != 'OK'):
logging.error('AppController returned: {0}'.format(relocate_info))
return 'Error attempting to relocate Application: ... |
'Removes a Google App Engine application from this AppScale deployment.
Args:
appname: A str containing the name of the app to be removed.
Returns:
A str indicating whether or not the application was successfully removed
from this AppScale deployment.'
| def delete_app(self, appname):
| try:
if (not self.does_app_exist(appname)):
return 'The given application is not currently running.'
acc = self.get_appcontroller_client()
ret = acc.stop_app(appname)
if (ret != 'true'):
logging.error('AppController returned: {0}'.forma... |
'Queries the UserAppServer to see if the named application id has been
registered.
Args:
appname: A str containing the name of the application we wish to query.
Returns:
True if the app id has been registered, and False otherwise.'
| def does_app_exist(self, appname):
| result = self.get_uaserver().does_app_exist(appname, GLOBAL_SECRET_KEY)
return (result.lower() == 'true')
|
'Checks to see if this user is logged in.
Returns:
True if the user is logged in, and False otherwise.'
| def is_user_logged_in(self):
| return (users.get_current_user() is not None)
|
'Get the logged in user\'s email.
Returns:
A str with the user\'s email, or \'\' if the user is not logged in.'
| def get_user_email(self):
| user = users.get_current_user()
if user:
return user.email()
else:
return ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.