Udacity Machine Learning Engineer Nanodegree: Project 3
Author: Ke Zhang
Submission Date: 2017-04-30 (Revision 1)
In this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in monetary units) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.
The dataset for this project can be found on the UCI Machine Learning Repository. For the purposes of this project, the features 'Channel'
and 'Region'
will be excluded in the analysis — with focus instead on the six product categories recorded for customers.
Run the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported.
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
import matplotlib.pyplot as plt
import seaborn as sns
# Import supplementary visualizations code visuals.py
import visuals as vs
#sklearn makes lots of deprecation warnings...
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Pretty display for notebooks
%matplotlib inline
sns.set(style='white', palette='muted', color_codes=True)
sns.set_context('notebook', font_scale=1.2, rc={'lines.linewidth': 1.2})
# Load the wholesale customers dataset
try:
data = pd.read_csv("customers.csv")
data.drop(['Region', 'Channel'], axis = 1, inplace = True)
print "Wholesale customers dataset has {} samples with {} features each.".format(*data.shape)
except:
print "Dataset could not be loaded. Is the dataset missing?"
In this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project.
Run the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: 'Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', and 'Delicatessen'. Consider what each category represents in terms of products you could purchase.
# Display a description of the dataset
display(data.describe())
To get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add three indices of your choice to the indices
list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another.
# Select three indices of your choice you wish to sample from the dataset
indices = [370, 181, 183]
# Create a DataFrame of the chosen samples
samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)
print "Chosen samples of wholesale customers dataset:"
display(samples)
# Display a description of the samples
display(samples.describe())
# Plot heatmap
from sklearn.preprocessing import MinMaxScaler
rel_data = MinMaxScaler().fit_transform(data)
sns.heatmap(
pd.DataFrame(rel_data[indices], columns = data.keys()),
yticklabels=['Client-1', 'Client-2', 'Client-3'],
linewidth=2
)
sns.plt.title("Sample Client Relative Purchases")
Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers.
What kind of establishment (customer) could each of the three samples you've chosen represent?
Hint: Examples of establishments include places like markets, cafes, and retailers, among many others. Avoid using names for establishments, such as saying "McDonalds" when describing a sample customer as a restaurant.
Answer:
| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|
| 39679 | 3944 | 4955 | 1364 | 523 | 2235 |
| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|
| 112151 | 29627 | 18148 | 16745 | 4948 | 8550 |
| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|
| 36847 | 43950 | 20170 | 36534 | 239 | 47943 |
One interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.
In the code block below, you will need to implement the following:
new_data
a copy of the data by removing a feature of your choice using the DataFrame.drop
function.sklearn.cross_validation.train_test_split
to split the dataset into training and testing sets.test_size
of 0.25
and set a random_state
.random_state
, and fit the learner to the training data.score
function.# Import libraries
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
# Make a copy of the DataFrame, using the 'drop' function to drop the given feature
target_feature = 'Delicatessen'
new_data = data.drop([target_feature], axis=1)
# Split the data into training and testing sets using the given feature as the target
X_train, X_test, y_train, y_test = train_test_split(
new_data,
data[target_feature],
test_size=.25,
random_state=42
)
# Create a decision tree regressor and fit it to the training set
regressor = DecisionTreeRegressor(random_state=42)
regressor.fit(X_train, y_train)
# Report the score of the prediction using the testing set
score = regressor.score(X_test, y_test)
# print top features importances ordered by importance
def rank_features(features, scores, descending=True, n=10):
"""
sorts and cuts features by scores.
:return: array of [feature name, score] tuples
"""
return sorted(
[[f, s] for f, s in zip(features, scores) if s],
key=lambda x: x[1],
reverse=descending
)[:n]
print("Regressor feature importances: \n{}\n".format(
rank_features(new_data.columns, regressor.feature_importances_)
))
print("Testing set score for 'Delicatessen': {}".format(score))
Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?
Hint: The coefficient of determination, R^2
, is scored between 0 and 1, with 1 being a perfect fit. A negative R^2
implies the model fails to fit the data.
Answer:
We attempted to predict the feature Delicatessen. The reported prediction R² score was -2.25 and negative thus implies that the model failed to fit the data. This indicates that the feature is necessary and could not determined from the other categories.
To get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix.
# Produce a scatter matrix for each pair of features in the data
pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
# plot correlation matrix
sns.heatmap(data.corr(),linewidths=1)
sns.plt.title('Correlation Matrix')
# print correlation in numbers
display(data.corr().round(2))
Are there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?
Hint: Is the data normally distributed? Where do most of the data points lie?
Answer:
The top 3 pairs with strong correlations are:
| corr | |
|---|---|
| Grocery and Detergents_Paper | .92 |
| Grocery and Milk | .73 |
| Milk and Detergents_Paper | .66 |
The others have all a correlation below 0.5 and confirms my suspicion that the selected feature Delicatessen is relevant.
The data is not normally distributed. The diagonal of the scatter matrix shows that the features are all right skewed and most of the data points lie on the left side of the plots.
In this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful.
If data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most often appropriate to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a Box-Cox test, which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.
In the code block below, you will need to implement the following:
log_data
after applying logarithmic scaling. Use the np.log
function for this.log_samples
after applying logarithmic scaling. Again, use np.log
.# Scale the data using the natural logarithm
log_data = np.log(data)
# Scale the sample data using the natural logarithm
log_samples = np.log(samples)
# Produce a scatter matrix for each pair of newly-transformed features
pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
After applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).
Run the code below to see how the sample data has changed after having the natural logarithm applied to it.
# Display the log-transformed sample data
display(log_samples)
# print correlation in numbers
# all strong correlations remained strong
display(log_data.corr().round(2))
Detecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we will use Tukey's Method for identfying outliers: An outlier step is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.
In the code block below, you will need to implement the following:
Q1
. Use np.percentile
for this.Q3
. Again, use np.percentile
.step
.outliers
list.NOTE: If you choose to remove any outliers, ensure that the sample data does not contain any of these points!
Once you have performed this implementation, the dataset will be stored in the variable good_data
.
from scipy.stats import itemfreq
# For each feature find the data points with extreme high or low values
iqr_filtered_ids = []
for feature in log_data.keys():
# Calculate Q1 (25th percentile of the data) for the given feature
Q1 = np.percentile(log_data[feature], 25)
# Calculate Q3 (75th percentile of the data) for the given feature
Q3 = np.percentile(log_data[feature], 75)
# Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)
step = (Q3 - Q1) * 1.5
# Display the outliers
print "Data points considered outliers for the feature '{}':".format(feature)
filtered = log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]
iqr_filtered_ids.extend(filtered.index.values)
display(filtered)
# Select the indices for data points you wish to remove
filtered_freq = itemfreq(iqr_filtered_ids)
print('Data points outside IQR: {}\n{}'.format(
len(filtered_freq),
filtered_freq
))
# Remove records filtered by at least 2 IQR filters
outliers = [x[0] for x in filtered_freq if x[1] >= 3]
print('Data points with more than three outliers: {}'.format(
outliers
))
display(data.iloc[outliers])
# Remove the outliers, if any were specified
good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)
# print new data
good_data.describe()
Are there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the outliers
list to be removed, explain why.
Answer:
In the dataset there are 42 data points having values outside of the IQR filter in one of the features. Five of them have outliers in more than one features.
Outliers should be removed from the dataset when they could harm the correctness of the learning algorithms which are prone to outliers. In our case we decided to remove only the data points with extreme values extreme values in more than one features. They are [65, 66, 75, 128, 154]. As we looked at the other data points manually, each of them are actually reasonable and makes valid interpretations. Furthermore as we have only 440 data points in total, removing 42 of them (~10%) could have negative distoring effects on the prediction results.
No additional data points were added to the outliers list.
In this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers.
Now that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the good_data
to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the explained variance ratio of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new "feature" of the space, however it is a composition of the original features present in the data.
In the code block below, you will need to implement the following:
sklearn.decomposition.PCA
and assign the results of fitting PCA in six dimensions with good_data
to pca
.log_samples
using pca.transform
, and assign the results to pca_samples
.# Apply PCA by fitting the good data with the same number of dimensions as features
from sklearn.decomposition import PCA
pca = PCA(n_components=6)
pca.fit(good_data)
# Transform log_samples using the PCA fit above
pca_samples = pca.transform(log_samples)
# Generate PCA results plot
pca_results = vs.pca_results(good_data, pca)
print('Variance expained by the first 2 PCs: {}'.format(
pca_results['Explained Variance'].round(2).cumsum()[1]
))
print('Variance expained by the first 4 PCs: {}'.format(
pca_results['Explained Variance'].round(2).cumsum()[3]
))
display(pca_results[:4].round(2))
How much variance in the data is explained in total by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.
Hint: A positive increase in a specific dimension corresponds with an increase of the positive-weighted features and a decrease of the negative-weighted features. The rate of increase or decrease is based on the indivdual feature weights.
Answer:
In total .71 of the variance is expained by the first and second principal component and .92 by the first four principal components.
The visualization above shows the customer spending patterns divided in six dimensions. Each dimension is identified by the high positive or negative features weights of the different categories.
| Explained Variance | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0.44 | 0.21 | -0.38 | -0.45 | 0.20 | -0.74 | -0.12 |
| Explained Variance | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0.27 | -0.68 | -0.18 | -0.09 | -0.47 | -0.08 | -0.51 |
| Explained Variance | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0.12 | -0.66 | 0.04 | -0.03 | 0.28 | -0.21 | 0.66 |
| Explained Variance | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0.10 | -0.22 | 0.02 | 0.07 | 0.81 | 0.19 | -0.50 |
Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points.
# Display sample log-data after having a PCA transformation applied
display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))
Interpretations:
When using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the cumulative explained variance ratio is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.
In the code block below, you will need to implement the following:
good_data
to pca
.good_data
using pca.transform
, and assign the results to reduced_data
.log_samples
using pca.transform
, and assign the results to pca_samples
.from sklearn.decomposition import PCA
# Apply PCA by fitting the good data with only two dimensions
pca = PCA(n_components=2)
pca.fit(good_data)
# Transform the good data using the PCA fit above
reduced_data = pca.transform(good_data)
# Transform log_samples using the PCA fit above
pca_samples = pca.transform(log_samples)
# Create a DataFrame for the reduced data
reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])
# plot scatter mattrix of the 2 dimensions
pd.scatter_matrix(reduced_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.
# Display sample log-data after applying PCA transformation in two dimensions
display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))
A biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case Dimension 1
and Dimension 2
). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features.
Run the code cell below to produce a biplot of the reduced-dimension data.
vs.pca_results(reduced_data, pca, keys=good_data.keys())
# Create a biplot
vs.biplot(good_data, reduced_data, pca)
Once we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on 'Milk'
, 'Grocery'
and 'Detergents_Paper'
, but not so much on the other product categories.
From the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier?
In this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale.
What are the advantages to using a K-Means clustering algorithm? What are the advantages to using a Gaussian Mixture Model clustering algorithm? Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?
Answer:
| Clustering Algorithm | Advantages | Disadvantages |
|---|---|---|
| K-Means |
|
|
| Gaussian Mixture Model (GMM) |
|
|
Based on our observations so far, we prefer to use the GMM algorithm since it is unclear what structure exists in the data. The GMM algorithm is more flexible than the K-Means algorithm, performs soft clustering and handles non-spherical clusters. Moreover, there's no obsiously problems with high dimensionality after running the dimensionality reduction with PCA.
Depending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known a priori, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the "goodness" of a clustering by calculating each data point's silhouette coefficient. The silhouette coefficient for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the mean silhouette coefficient provides for a simple scoring method of a given clustering.
In the code block below, you will need to implement the following:
reduced_data
and assign it to clusterer
.reduced_data
using clusterer.predict
and assign them to preds
.centers
.pca_samples
and assign them sample_preds
.sklearn.metrics.silhouette_score
and calculate the silhouette score of reduced_data
against preds
.score
and print the result.from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
def calculate_gaussian_mixture(n):
# Apply your clustering algorithm of choice to the reduced data
clusterer = GaussianMixture(n_components=n, random_state=42)
clusterer.fit(reduced_data)
# Predict the cluster for each data point
preds = clusterer.predict(reduced_data)
# Find the cluster centers
centers = clusterer.means_
# Predict the cluster for each transformed sample data point
sample_preds = clusterer.predict(pca_samples)
# Calculate the mean silhouette coefficient for the number of clusters chosen
score = silhouette_score(reduced_data, preds)
return (clusterer, centers, preds, sample_preds, score)
for n in range(2, 11):
_, _, _, _, score = calculate_gaussian_mixture(n)
print('# clusters={0}, silhouette score={1:.3f}'.format(
n,
score
))
Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?
Answer:
Silhouette score is at highest with 2 clusters.
| # Clusters | Silhouette Score |
|---|---|
| 2 | .412 |
| 3 | .409 |
| 4 | .288 |
| 5 | .186 |
| 6 | .322 |
| 7 | .276 |
| 8 | .348 |
| 9 | .339 |
| 10 | .322 |
Once you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters.
# Display the results of 8 clusters
clusterer, centers, preds, _, _ = calculate_gaussian_mixture(8)
vs.cluster_results(reduced_data, preds, centers, pca_samples)
# Display the results of 3 clusters
clusterer, centers, preds, _, _ = calculate_gaussian_mixture(3)
vs.cluster_results(reduced_data, preds, centers, pca_samples)
# Display the results of 2 clusters (final)
clusterer, centers, preds, sample_preds, _ = calculate_gaussian_mixture(2)
vs.cluster_results(reduced_data, preds, centers, pca_samples[:2])
Each cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the averages of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to the average customer of that segment. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.
In the code block below, you will need to implement the following:
centers
using pca.inverse_transform
and assign the new centers to log_centers
.np.log
to log_centers
using np.exp
and assign the true centers to true_centers
.# Inverse transform the centers
log_centers = pca.inverse_transform(centers)
# Exponentiate the centers
true_centers = np.exp(log_centers)
# Display the true centers
segments = ['Segment {}'.format(i) for i in range(0,len(centers))]
true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())
true_centers.index = segments
display(true_centers)
# show descriptive statistics of data with outliers removed
data.drop(data.index[outliers]).describe()
Consider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. What set of establishments could each of the customer segments represent?
Hint: A customer who is assigned to 'Cluster X'
should best identify with the establishments represented by the feature set of 'Segment X'
.
Answer:
For each sample point, which customer segment from Question 8 best represents it? Are the predictions for each sample point consistent with this?
Run the code block below to find which cluster each sample point is predicted to be.
# Display the predictions
for i, pred in enumerate(sample_preds):
print "Sample point", i, "predicted to be in Cluster", pred
Answer:
| Cluster | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 1 | 39679 | 3944 | 4955 | 1364 | 523 | 2235 |
| Cluster | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0 | 112151 | 29627 | 18148 | 16745 | 4948 | 8550 |
| Cluster | Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen |
|---|---|---|---|---|---|---|
| 0 | 36847 | 43950 | 20170 | 36534 | 239 | 47943 |
In this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the customer segments, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which segment that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the customer segments to a hidden variable present in the data, to see whether the clustering identified certain relationships.
Companies will often run A/B tests when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?
Hint: Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most?
Answer: The wholesale distributor should perform separate tests in each of the customer segments because the change in the delivery schedule may affect the segments differently.
Intuitively we would assume a different behavior between the two customer segments. Fresh fruits and Frozen food or Detergents_Paper have definitely different expiry dates which implies different level of effects on the customer segments.
We would conduct two separate experiments each with one of the segments. We'll choose the invariant and evaluation metrics, estimate the proper sizing and durations and setup the control and treatment groups. After the test period we can then check which group of customer it affected the most by comparing the the effect sizes and significances.
Additional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a customer segment it best identifies with (depending on the clustering algorithm applied), we can consider 'customer segment' as an engineered feature for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a customer segment to determine the most appropriate delivery service.
How can the wholesale distributor label the new customers using only their estimated product spending and the customer segment data?
Hint: A supervised learner could be used to train on the original customers. What would be the target variable?
Answer:
Once trained the GMM algorithm can utilize the estimated product spending data of the new customers to predict their customer segments. And from the conducted A/B testing we know which delivery service is appropriate for which customer segment and can make the our decisions on that basis.
At the beginning of this project, it was discussed that the 'Channel'
and 'Region'
features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the 'Channel'
feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.
Run the code block below to see how each data point is labeled either 'HoReCa'
(Hotel/Restaurant/Cafe) or 'Retail'
the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling.
# Display the clustering results based on 'Channel' data
vs.channel_results(reduced_data, outliers, pca_samples)
# Display the results of the clustering from implementation
vs.cluster_results(reduced_data, preds, centers, pca_samples)
How well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? Would you consider these classifications as consistent with your previous definition of the customer segments?
Answer:
Our analysis produced the same number of clusteres. What's more, the customer segments predicted by the GMM clustering algorithm match with the underlying distributions of Hotel/Restaurant/Cafe and Retailer for the most part as we can see in the last two cluster results.
However we failed to label the customer segments previously. The first customer segment what we marked as resturants or coffee shops is actually Retailer. And the second should be Hotel/Restaurant/Cafe but was supermarkets. Last but not least it's really a coincidence that our sample points were correctly labeled. The first sample was a Retailer but lies in the middle of Hotel/Restuarant/Cafe cluster. And the other two samples were inbetween of the two clusters and were assigned to the wrong cluster by the GMM algorithm.
import IPython
print IPython.sys_info()
!pip freeze


|
| Local Properties | ||
| Managed Object Types | Data Object Types | All Properties | All Methods |
The virtual disk backing object types describe the different virtual disk backings available. The disk format version in each case describes the version of the format that is used.
Supported virtual disk backings:
Properties
| Name | Type | Description |
|---|---|---|
| capacityInBytes* | xsd:long |
Capacity of this virtual disk in bytes.
Server will always populate this property. Clients must initialize it when
creating a new non -RDM disk or in case they want to change the current
capacity of an existing virtual disk, but can omit it otherwise.
If the disk is on a Virtual Volume datastore the disk size must be a multiple
of a megabyte.
Since vSphere API 5.5 |
| capacityInKB | xsd:long | Deprecated.
As of vSphere API 5.5, use capacityInBytes.
Capacity of this virtual disk in kilobytes.
Information might be lost when actual disk size is rounded off to kilobytes.
If the disk is on a Virtual Volume datastore the disk size must be a multiple
of a megabyte.
|
| diskObjectId* | xsd:string | Deprecated.
As of vSphere API 2016, use vDiskId.
Virtual disk durable and unmutable identifier.
Virtual disk has a UUID field but that can be set through
VirtualDiskManager APIs.
This identifier is a universally unique identifier which is not settable.
VirtualDisk can remain in existence even if it is not associated with VM.
Since vSphere API 5.5 |
| iofilter* | xsd:string[] |
IDs of the IO Filters associated with the virtual disk.
See id. This information
is provided when retrieving configuration information for
an existing virtual machine. The client cannot modify this information
on a virtual machine.
Since vSphere API 6.0 |
| nativeUnmanagedLinkedClone* | xsd:boolean |
Indicates whether a disk with
VirtualDiskFlatVer2BackingInfo backing is a linked
clone from an unmanaged delta disk and hence the
parent chain to
this delta disk will not be available.
Since vSphere API 6.7 |
| shares* | SharesInfo | Deprecated.
As of vSphere API 4.1, use
shares.
Disk shares, used for resource scheduling.
|
| storageIOAllocation* | StorageIOAllocationInfo | Deprecated.
As of vSphere API 6.5, use
Resource allocation for storage I/O.
Since vSphere API 4.1 |
| vDiskId* | ID |
ID of the virtual disk object as the first class entity.
See ID
The ID is a universally unique identifier for the disk lifecycle,
even if the virtual disk is not associated with VM.
Since vSphere API 6.5 |
| vFlashCacheConfigInfo* | VirtualDiskVFlashCacheConfigInfo |
vFlash cache configuration supported on this virtual disk
Since vSphere API 5.5 |
| Properties inherited from VirtualDevice | ||
| backing, connectable, controllerKey, deviceInfo, key, slotInfo, unitNumber | ||
| Properties inherited from DynamicData | ||
| None |
| Top of page | Local Properties | ||
| Managed Object Types | Data Object Types | All Properties | All Methods |


This namespace should not have a global include either.
Because it has a class inside.
-
void foo()
- This function should also have a local include.
Function documentation
void ContainsNamespace::ContainsClass::foo()
This function should also have a local include.


Click below to view your complete account profile, and to update your address or contact details.
A non-medical cannabis retail store licence allows licensees to sell non-medical cannabis and cannabis accessories in British Columbia.
To apply for a non-medical cannabis retail store licence, applicants must submit a completed application form and completed business financial integrity form. A separate application and business financial integrity form is required for each proposed establishment.
The Liquor and Cannabis Regulation Branch (LCRB) will only process complete applications. The checklist accompanying the application form can assist in completing all required documentation.
Please note that applications which are submitted without all required information or documents will not be processed. Applicants will be contacted and provided the opportunity to submit missing information. Once applicants provide all required documents to the LCRB, the application will be submitted for processing.
Inquires related to your application can be directed to<EMAIL_ADDRESS>Click below to view your complete account profile, and to update your address or contact details.
An applicant that is a Private Corporation may have associates that are required to consent to security screening and financial integrity assessments as part of the application for a non-medical cannabis retail store licence. Applicants are required to provide associates with the Parcel Identifier (PID) or proposed retail store location address.
Parcel Identifier (PID):Applicants should direct associates to the LCRB non-medical cannabis webpage to download required forms and instructions for submitting documentation.
Associates will submit documentation for security screening and financial integrity assessments directly to the LCRB. Applicants should not delay submitting a completed application form and business financial integrity form. It is the applicant's responsibility to direct all associates to the link provided.
Associates of Private Corporation include:Corporations, societies and/or partnerships that are shareholders in the Private Corporation are considered associates of the Applicant and are required to submit an associate organization assessment form.
An applicant that is a Public Corporation may have associates that are required to consent to security screening and financial integrity assessments as part of the application for a non-medical cannabis retail store licence. Applicants are required to provide associates with the Parcel Identifier (PID) or proposed retail store location address.
Parcel Identifier (PID):Applicants should direct associates to the LCRB non-medical cannabis webpage to download required forms and instructions for submitting documentation.
Associates will submit documentation for security screening and financial integrity assessments directly to the LCRB. Applicants should not delay submitting a completed application form and business financial integrity form. It is the applicant's responsibility to direct all associates to the link provided.
Associates of Public Corporation include:Corporations, societies and/or partnerships that are shareholders in the Public Corporation are considered associates of the Applicant and are required to submit an associate organization assessment form.
An applicant that is a Partnership may have associates that are required to consent to security screening and financial integrity assessments as part of the application for a non-medical cannabis retail store licence. Applicants are required to provide associates with the Parcel Identifier (PID) or proposed retail store location address.
Parcel Identifier (PID):Applicants should direct associates to the LCRB non-medical cannabis webpage to download required forms and instructions for submitting documentation.
Associates will submit documentation for security screening and financial integrity assessments directly to the LCRB. Applicants should not delay submitting a completed application form and business financial integrity form. It is the applicant's responsibility to direct all associates to the link provided.
Associates of Partnership include:Corporations, societies and/or partnerships that are themselves partners in the Partnership are considered associates of the Applicant and are required to submit an associate organization assessment form.
An applicant that is a Sole Proprietorship must consent to a security screening as part of the application for a non-medical cannabis retail store licence.
Please visit the LCRB non-medical cannabis webpage to download required forms and instructions for submitting documentation for the security screening directly to the LCRB.
An applicant that is a Society may have associates that are required to consent to security screening and financial integrity assessments as part of the application for a non-medical cannabis retail store licence. Applicants are required to provide associates with the Parcel Identifier (PID) or proposed retail store location address.
Parcel Identifier (PID):Applicants should direct associates to the LCRB non-medical cannabis webpage to download required forms and instructions for submitting documentation.
Associates will submit documentation for security screening and financial integrity assessments directly to the LCRB. Applicants should not delay submitting a completed application form and business financial integrity form. It is the applicant's responsibility to direct all associates to the link provided.
Associates of Society include:Please note: While they are not normally required as part of the licence application process, the Liquor and Cannabis Regulation Branch reserves the right to ask for a society’s membership lists.
All cannabis retail store licence holders must follow the terms and conditions of their licence as set out in the Retail Store Licence Terms and Conditions Handbook .


Avg. of ROICs and Equities (weighted towards ROIC)The smaller of these two
Double Rule 1 Growth RateThe smaller or the average of these two.
Current EPS grown for 10yrs at Rule 1 Growth RateEst EPS in 10 yrs * Rule 1 PE
Est Future Stock Price / 4 (Allows for a 15% growth rate)Half Stock Sticker Price(Positive is good. Negative is bad.)Years for Cummulative Net Income (grown at Rule 1 growth rate) to exceed Market Cap


# Substitution Cipher # scratch work by John Reyner # I looked up a basic code for encryption/decryption online to replicate as practice. # To add in some personal work I added in a means to accept a non-case sensitive input of 'Encrypt' or 'Decrypt' instead of just the numeric inputs. # There also is a means to set any integer as an encryption code. result = '' choice = '' message = '' while choice != '0': choice = input("\n Choose to encrypt or decrypt.\n 1 to encrypt, 2 to decrypt, 0 to cancel.") if choice.lower() == 'encrypt': choice = '1' if choice.lower() == 'decrypt': choice = '2' if choice == '1': message = input('\nEnter message to encrypt: ') iseed = input('\nInput an integer to use as a seed.') seed = int(iseed) for i in range(0, len(message)): result = result + chr(ord(message[i]) - seed) print(result + '\n\n') result = '' elif choice == '2': message = input('\nEnter message to decrypt: ') iseed = input('\nInput the integer that was used as the seed.') seed = int(iseed) for i in range(0, len(message)): result = result + chr(ord(message[i]) + seed) print(result + '\n\n') result = '' elif choice != '0': print('Invalid input, please try again. \n\n')


How to add comment to static Jekyll webpage
Why do we need the comment?
Comments are one of the undoubtedly effective methods to increase interaction between blog's author and viewer since the first day of Web 2.0. Comments raise the revisiting frequency of viewer, giving useful feedback to the writer to create better content for the future blog. However, there's a problem with our previous blog architecture Jekyll
generates static webpage to Github pages. How do we solve the dynamic content problem of this design?
Disqus
is my answer to the difficulty raise above. The reason I chose Disqus
over other alternatives are:
- Easy to set up, just register an account at Disqus, and you then have everything
- The viewer has multiple choice of login, well organized and well interacted with other social accounts as well.
- Pretty good UI and easy to use, also SPAM control with
Disqus
behave exceptionally well; almost you do not have to do anything. - Free, it cost nothing to set up.
Here are the step to set it up:
Step 1. Register a Disqus account
Go to Disqus
website and sign up an account, then create a webpage. You need to note the short name
that Disqus
asks you to enter.
Step 2. Set up the configuration
Go to file _config.yml
and add or overwriting the following
disqus:
shortname: tonnyme
site_url: https://tonny.me
Remember the short name in Step 1? Replace tonnyme
with yours. Also, replace site_url
with your site URL, this is important to prevent duplicated comments.
Step 3
Replace file _includes/common/disqus.html
completely with the following content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Please enable JavaScript to view the comments powered by Disqus.
That is it
Deploy and enjoy comment :)


Introduction¶
Summary¶
Jenni (JENkins New Interface) provides a Python-based system for configuring and running Jenkins jobs.
Why use Jenni?¶
It allows programmatic generation of Jenkins Jobs using the flexibility and familiarity of the Python language.
Using class-based models for defining jobs allows for template-like instantiation of jobs.
It provides a flexible framework for iterative development of Jenkins jobs.
Jenkins Pipeline Groovy has several (surprising) restrictions.
Many engineers know and love Python.
Python has excellent IDE support.
How does it work?¶
Each Jenkins job is defined by a class called
Job
in a Python module.Each Jenkins folder is defined by a class named
Folder
in a Python package module.Job parameters are defined by instances of a
ParamBase
sub-class.A
python -m jenni seed
generates an intermediate JobDSL file.In Jenkins a
seed
job can process this JobDSL file to create/update folders and jobs.As a developer in your own workspace, the JobDSL file can also be processed to generate a directory tree with Jenkins folder&job xml files.
This generated directory tree can be compared with a reference directory tree, to check if the changes are as expected.
One or more folder&job xml files can be uploaded to Jenkins to modify specific folders&jobs.
A Gradle build file handles these local-workspace activities.
What will be next?¶
The Jenni package is far from complete. The ultimate goal is both generate and execute jobs using Python, without using any Groovy pipeline code directly. The beginnings of this has been implemented as a proof of concept:
Various Python methods provide functionality equivalent to corresponding pipeline steps (eg sofar mostly the basic steps like stash/unstash, archiveArtifact, copyArtifact, git, unstable, stage, etc etc).
These methods effectively perform a Remote Procedure Call to a Groovy listener, which executes the requested pipeline step, and returns the result.
Help for the following would be much appreciated:
improving the Folder and Job creation api
allow creating Views
implementation of many more steps
implementation of a plugin for a pipeline step RPC listener (replacing the prototype scripted approach).
Sample Directory Structure¶
jobs/ # a directory called "jobs" is required.
__init__.py # defines a "Folder" class derived from RootFolderBase
folder1/
__init__.py
job1.py
CLI¶
The python3 -m jenni
command has this usage:
jenni [-h] [-q] -c CONFIG_DIR [-l LOG_FILE] {run,seed} ...
It has two sub-commands, seed
and run
.
Seed Command¶
The python3 -m jenni seed
command processes a directory containing the "jobs" directory and writes a Groovy file with JobDSL code.
See Seed Job.
jenni seed -o OUTPUT_FILE [--append]
optional arguments:
-h, --help show this help message and exit
-o OUTPUT_FILE, --output OUTPUT_FILE
Output jobdsl filename
--append Append rather than overwrite output jobdsl file
Run Command¶
The python -m jenni run
command runs a Jenkins job. This is work in progress.
jenni run [-j JOB_NAME] [param_assignment [param_assignment ...]]
positional arguments:
param_assignment name=value for each job parameter
optional arguments:
-j JOB_NAME, --job JOB_NAME
Name of job to run. Default is $JOB_NAME
Seed Job¶
A job like this can be used to update the folders/jobs on a Jenkins server after a commit to the code using Jenni.
pipeline {
agent { label 'master' }
options {
disableConcurrentBuilds()
}
stages {
stage('Checkout') { checkout ... }
stage('Generate') { sh script: 'python -m jenni seed >jobdsl.groovy' }
stage('Execute') {
jobDsl(
lookupStrategy: 'SEED_JOB',
removedConfigFilesAction: 'DELETE',
removedJobAction: 'DISABLE',
removedViewAction: 'IGNORE',
scriptText: readFile(file:'jobdsl.groovy')
)
}
}
}
Testing¶
Run make test
to run the unittests located in the test
folder.
Running Bandit¶
Bandit is a Security oriented static analyser for python code.
Run it using make bandit
(it will automatically create a local venv folder).
Implementation Details¶
Jenkins folders and jobs are defined by singleton instances of classes. Each class can define exactly one folder or job. Each class also resides in a unique module.
The root folder normally is defined in a jobs/__init__.py
file
with a class named Folder
derived from jenni.models.RootFolderBase
.
Other Jenkins folders are defined as Folder
classes
derived from jenni.models.FolderBase
.
Jenkins jobs are defined as Job
classes
derived from jenni.models.JobBase
; however in practice they are normally derived from
jenni.models.GroovyJobBase
or
jenni.models.PythonPipelineJobBase
.
After this, these classes and modules can be statically defined in Python source code files, or can be programmatically generated, or any combination of this.
A Jenkins folder normally maps to a __init__.py
file in a directory that is the same as the Jenkins folder path,
except hyphens are changed to underscores.
Programmatic Job Generation¶
A folder can programmatically generate new sub-items (jobs/folders) by overriding the yield_items
method,
instead of by creating a new Python file for each sub-item.
The new sub-item is created and added by calling yield from self.yield_sub_item(sub_item_name, sub_item_class)
.
For example:
# jobs/__init__.py
from jenni.models import RootFolderBase, GroovyJobBase
class Folder(RootFolderBase):
def yield_items(self):
yield from super().yield_items()
yield from self.yield_sub_item("job1", Job)
class Job(GroovyJobBase):
def __init__(self):
super().__init__()
self.code(f"echo 'hello from {self.name}';")
There are various method names that start with yield
, which can all be used to create additional jobs/folder
at various points, and if overriding them they must always call
yield from super().<method_name>(...)
, and use yield
something themselves.
Please see the customisation hooks below for further information.
Customisation Hooks¶
FolderBase.add_new_job¶
The jenni.models.FolderBase.add_new_job()
is
executed after the Python job instance has been created (__init__
completed).
It can be used by the parent folder to customise the newly added job.
For example, you want to repeat the description of the Jenkins folder at the end of the description of every job in it:
import jenni
class Folder(jenni.models.FolderBase):
def __init__...
def add_new_job(self, job: "jenni.models.jobbase.JobBase"):
super().add_new_job(job)
job.description = f"{job.description}
{self.description}"
FolderBase.add_new_folder¶
The jenni.models.FolderBase.add_new_folder()
is
executed after the Python Folder instance has been created (__init__
completed).
It can be used by the parent folder to customise the newly added sub-folder.
It is similar to jenni.models.FolderBase.add_new_job()
method.
For example, you want to add a link to a url in every sub-folder description, but the url depends on the parent folder:
import jenni
class Folder(jenni.models.FolderBase):
def __init__...
def add_new_folder(self, sub_folder: "FolderBase"):
super().add_new_folder(sub_folder)
if self.should_i_add_link():
sub_folder.description = f"{sub_folder.descripton}
See also {jenni.utils.html_link(sub_folder.the_link_url)}"""
FolderBase.yield_items_pre_sub_item¶
The jenni.models.FolderBase.yield_items_pre_sub_item()
is
called before jenni.models.itembase.ItemBase.yield_items()
is called.
It allows you to yield additional items, before the sub-item will yield any items.
EG you may want to create additional jobs/folders, such that the sub-item can find/use these.
FolderBase.yield_items_post_sub_item¶
The jenni.models.FolderBase.yield_items_post_sub_item()
is
called before jenni.models.itembase.ItemBase.yield_items()
is called.
It allows you to yield additional items, after the sub-item has yielded any items.
EG you may want to create additional jobs/folders, that find/use the sub-item just created.
FolderBase.sub_item_completed_handler¶
The jenni.models.FolderBase.sub_item_completed_handler()
is
called after a sub-item has completed yielding any items.
The sub-item can be customised by overriding this method.
Summary¶
Let folder be a FolderBase
instance, and sub_item a (new)
FolderBase
or JobBase
instance to be created,
then this shows the sequence of calls:
sub_item.__init__(...)
super().__init__(...)
if isinstance(sub_item, JobBase):
folder.add_new_job(sub_item)
if isinstance(sub_item, FolderBase):
folder.add_new_folder(sub_item)
yield from folder.yield_items_pre_sub_item(sub_item)
yield from sub_item.yield_items()
yield from folder.yield_items_post_sub_item(sub_item)
folder.sub_item_completed_handler(sub_item)


Swift Info.
Storage Containers
Total Files
Storage Consumed
| File Name | |
| File Path | |
| Type | |
| Size | |
| Last modified |


{: .-three-column}
FROM ruby:2.2.2
ENV APP_HOME /myapp
RUN mkdir $APP_HOME
ARG APP_HOME=""
RUN mkdir $APP_HOME
RUN bundle install
WORKDIR /myapp
VOLUME ["/data"]
# Specification for mount point
ADD file.xyz /file.xyz
COPY --chown=user:group host_file.xyz /path/container_file.xyz
ONBUILD RUN bundle install
# when used with another file
EXPOSE 5900
CMD ["bundle", "exec", "rails", "server"]
ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2
Configures a container that will run as an executable.
ENTRYPOINT exec top -b
This will use shell processing to substitute shell variables, and will
ignore any CMD
or docker run
command line
arguments.
LABEL version="1.0"
LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL description="This text illustrates \
that label-values can span multiple lines."
{: .-one-column}


Open the menu with a link.
the menu with a button.
the menu with javascript.
Lo-fi narwhal Schlitz plaid tofu. Selvage wolf Williamsburg hoodie typewriter. Chambray jean shorts single-origin coffee deep v, raw denim 8-bit heirloom authentic irony banjo XOXO. Chia artisan selvage Williamsburg direct trade flexitarian, scenester Neutra selfies locavore chambray. Squid butcher mumblecore mlkshk Marfa, crucifix post-ironic single-origin coffee. Marfa crucifix Wes Anderson, tattooed 8-bit readymade 90's biodiesel chia PBR&B chambray Banksy small batch. High Life occupy umami Pitchfork, jean shorts roof party sartorial mlkshk leggings normcore flexitarian Vice kitsch irony.
Synth asymmetrical paleo wayfarers 90's, kitsch art party irony mumblecore church-key pop-up. Mumblecore Vice mixtape McSweeney's cray. IPhone gluten-free Wes Anderson kale chips mixtape, stumptown you probably haven't heard of them Neutra organic fingerstache. Cosby sweater tofu Brooklyn, lo-fi Godard Schlitz cliche. Neutra freegan sartorial, skateboard polaroid mumblecore gastropub fanny pack twee distillery lo-fi Schlitz semiotics Helvetica. Drinking vinegar messenger bag Bushwick VHS High Life lomo. Deep v authentic trust fund, organic semiotics four loko quinoa Blue Bottle asymmetrical Bushwick pug.
Fap flexitarian meh literally. Thundercats Carles flexitarian Wes Anderson ethical kale chips. Chambray hashtag literally bicycle rights. Disrupt pour-over squid selfies, Wes Anderson mustache iPhone small batch. Cardigan direct trade distillery, gastropub photo booth High Life Truffaut literally fixie. Pitchfork flannel Blue Bottle, authentic ugh scenester readymade meh meggings Echo Park asymmetrical hella Pinterest. Tonx bespoke Etsy, High Life Intelligentsia pop-up Blue Bottle Shoreditch Neutra Helvetica +1 street art.
Quinoa food truck pickled direct trade lomo, VHS umami biodiesel. Keffiyeh Shoreditch distillery DIY, iPhone four loko dreamcatcher hashtag wolf. Keytar PBR try-hard you probably haven't heard of them, blog butcher pug. Cred heirloom hashtag organic forage vegan Thundercats fixie, leggings craft beer pork belly art party church-key. Schlitz normcore tousled, distillery mustache iPhone fap. Blog chia Carles letterpress Tumblr, organic tattooed yr tilde. Skateboard selfies salvia cornhole beard.
Blue Bottle kogi asymmetrical, Brooklyn irony PBR four loko wayfarers food truck put a bird on it Cosby sweater keffiyeh heirloom Portland High Life. Roof party fashion axe sartorial locavore mumblecore. Mlkshk Schlitz pour-over jean shorts gastropub, slow-carb Shoreditch forage pork belly small batch disrupt quinoa PBR&B Kickstarter photo booth. Lo-fi wayfarers mustache flannel Neutra, brunch Carles retro art party. Shabby chic organic Thundercats, gluten-free Williamsburg normcore tousled bitters drinking vinegar readymade cardigan mumblecore gastropub. Hella hoodie fanny pack, yr squid pug chambray Carles lo-fi photo booth tattooed sriracha pour-over stumptown before they sold out. Squid butcher YOLO artisan Pinterest shabby chic, bitters asymmetrical Echo Park PBR Brooklyn lo-fi sustainable.


Click here to enter the compatition
Click here to see more
Buck Rogers-"Past and Present"
Jim C.Kanel-"Birds watch"


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__init__(self,
*args)
__init__(lldb::SBBreakpoint self) -> SBBreakpoint
__init__(lldb::SBBreakpoint self, SBBreakpoint rhs) ->
SBBreakpoint |
source code
|
|
|
|
__swig_destroy__(...)
delete_SBBreakpoint(SBBreakpoint self) |
|
|
|
|
|
|
|
GetID(self)
GetID(SBBreakpoint self) -> lldb::break_id_t |
source code
|
|
|
|
|
|
|
IsValid(self)
IsValid(SBBreakpoint self) -> bool |
source code
|
|
|
|
ClearAllBreakpointSites(self)
ClearAllBreakpointSites(SBBreakpoint self) |
source code
|
|
|
|
FindLocationByAddress(self,
*args)
FindLocationByAddress(SBBreakpoint self, lldb::addr_t vm_addr) ->
SBBreakpointLocation |
source code
|
|
|
|
FindLocationIDByAddress(self,
*args)
FindLocationIDByAddress(SBBreakpoint self, lldb::addr_t vm_addr)
-> lldb::break_id_t |
source code
|
|
|
|
FindLocationByID(self,
*args)
FindLocationByID(SBBreakpoint self, lldb::break_id_t bp_loc_id) ->
SBBreakpointLocation |
source code
|
|
|
|
GetLocationAtIndex(self,
*args)
GetLocationAtIndex(SBBreakpoint self, uint32_t index) ->
SBBreakpointLocation |
source code
|
|
|
|
SetEnabled(self,
*args)
SetEnabled(SBBreakpoint self, bool enable) |
source code
|
|
|
|
IsEnabled(self)
IsEnabled(SBBreakpoint self) -> bool |
source code
|
|
|
|
SetOneShot(self,
*args)
SetOneShot(SBBreakpoint self, bool one_shot) |
source code
|
|
|
|
IsOneShot(self)
IsOneShot(SBBreakpoint self) -> bool |
source code
|
|
|
|
IsInternal(self)
IsInternal(SBBreakpoint self) -> bool |
source code
|
|
|
|
GetHitCount(self)
GetHitCount(SBBreakpoint self) -> uint32_t |
source code
|
|
|
|
SetIgnoreCount(self,
*args)
SetIgnoreCount(SBBreakpoint self, uint32_t count) |
source code
|
|
|
|
GetIgnoreCount(self)
GetIgnoreCount(SBBreakpoint self) -> uint32_t |
source code
|
|
|
|
|
|
|
|
|
|
SetThreadID(self,
*args)
SetThreadID(SBBreakpoint self, lldb::tid_t sb_thread_id) |
source code
|
|
|
|
GetThreadID(self)
GetThreadID(SBBreakpoint self) -> lldb::tid_t |
source code
|
|
|
|
SetThreadIndex(self,
*args)
SetThreadIndex(SBBreakpoint self, uint32_t index) |
source code
|
|
|
|
GetThreadIndex(self)
GetThreadIndex(SBBreakpoint self) -> uint32_t |
source code
|
|
|
|
SetThreadName(self,
*args)
SetThreadName(SBBreakpoint self, str const * thread_name) |
source code
|
|
|
|
GetThreadName(self)
GetThreadName(SBBreakpoint self) -> str const * |
source code
|
|
|
|
SetQueueName(self,
*args)
SetQueueName(SBBreakpoint self, str const * queue_name) |
source code
|
|
|
|
GetQueueName(self)
GetQueueName(SBBreakpoint self) -> str const * |
source code
|
|
|
|
SetCallback(self,
*args)
SetCallback(SBBreakpoint self,
lldb::SBBreakpoint::BreakpointHitCallback callback, void * baton) |
source code
|
|
|
|
GetNumResolvedLocations(self)
GetNumResolvedLocations(SBBreakpoint self) -> size_t |
source code
|
|
|
|
GetNumLocations(self)
GetNumLocations(SBBreakpoint self) -> size_t |
source code
|
|
|
|
GetDescription(self,
*args)
GetDescription(SBBreakpoint self, SBStream description) -> bool |
source code
|
|
|
|
|
|
|
|
|
|
|
|
Inherited from object :
__delattr__ ,
__format__ ,
__getattribute__ ,
__hash__ ,
__new__ ,
__reduce__ ,
__reduce_ex__ ,
__sizeof__ ,
__subclasshook__
|


Local community of Go programmers and enthusiasts
Check out our Meetup page for details on talks, speakers and to RSVP for the next meeting.
Talk proposals are welcomed. Submit at PaperCall.


{% extends "layout.html" %} {% block body %}
{{flight_count}} Flights on {{flight_date}}
| Airline | Flight Number | Origin | Destination | Departure Time | Tail Number | Air Time | Distance | {% for flight in flights %}
|---|---|---|---|---|---|---|---|
| {{flight.Carrier}} | {{flight.FlightNum}} | {{flight.Origin}} | {{flight.Dest}} | {{flight.DepTime}} | {{flight.TailNum}} | {{flight.AirTime}} | {{flight.Distance}} |


package extras
Extra Utilities
Extra utilities for Scala developers.
Some things it might have been nice to see in the standard Scala libraries, but are offered here instead. For example:
object Main extends App with Configuration with Environment with Logging { // Safest way to indicate something is happening, don't rely on logging yet println(s"Starting ${getClass.getName}...") println("Reporting environment and configuration for troubleshooting purposes") println(environment.getEnvironmentReport()) println(config.getConfigurationReport()) // If logging is broken, hopefully there is enough output now for a diagnosis logger.info("Logging started") }
Base 64 URL Identifiers
Sometimes it's nice to encode a 128-bit UUID as a 22-character Base 64 URL String, such as "keAoZQECSwm0h7v6yw_3WQ". Normally a UUID is expressed as a 36-character string such as "91e02865-0102-4b09-b487-bbfacb0ff759", so this is a simple way of saving 14 characters in URL encoding. For example
curl http://localhost/foo/keAoZQECSwm0h7v6yw_3WQ
Would internally refer to a resource for "foo/91e02865-0102-4b09-b487-bbfacb0ff759"
- Alphabetic
- By Inheritance
- extras
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
-
trait
Configuration extends Logging
Extra features for Typesafe Config
Enhanced Typesafe Config
Extra features for Typesafe Config
It is recommended that you extend this trait in your app, in the same style, but for local configuration. For example:
trait Configuration extends net.kolotyluk.scala.extras.Configuration { config.setPathBase("net.flybynight.myapp") implicit class LocalConfiguration(val config: com.typesafe.config.Config) extends Logging { import com.typesafe.config.Config // net.flybynight.myapp.akka.system.name def getAkkaSystemName(default: Some[String] = Some("myapp")): String = config.getDefaultString("akka.system.name", default) def getRestAddress(default: Some[String] = Some("<IP_ADDRESS>")) : String = config.getDefaultString("rest.address", default) def getRestPort(default: Some[Int] = Some(8080)) : Int = config.getDefaultInt("rest.port", default, 0 to 65535) } }
Good Separation of Concerns practice would be to make your configuration code as robust as possible. You main application should not handle any configuration problems, rather all configuration troubleshooting should be in your Configuration trait. In the main body of code you might use:
val akkaSystemName = config.getAkkaSystemName() val restAddress = config.getRestAddress() val restPort = config.getRestPort()
-
trait
Environment extends AnyRef
Some extra utilities for accessing the local system environment variables.
Scala Environment Extras
Some extra utilities for accessing the local system environment variables.
-
class
Internalized[T] extends AnyRef
Because there are no duplicates in this class, obj1 eq obj2 is sufficient
Class of Internalized Objects
Because there are no duplicates in this class, obj1 eq obj2 is sufficient
Behaves similar to java.lang.String#intern
- class InvalidBase64UrlToUuidException extends Exception
-
trait
Logging extends AnyRef
It is recommended that you extend this trait in your app, in the same style, but for local configuration.
Extra Logging Behavior
It is recommended that you extend this trait in your app, in the same style, but for local configuration.
Value Members
-
def
base64UrlIdToUuid(base64UrlId: String): UUID
Parse UUID from Base 64 URL String
- returns
Unique Universal Identifier
- Exceptions thrown
InvalidBase64UrlToUuidException
when parsing fails
-
def
getFutureResult[I, O](input: Any, output: (I) ⇒ O)(implicit executor: ExecutionContext): Future[O]
Given a input value which can return either a value or a Future(value), this function always returns a Future output value.
Return a Future Result
Given a input value which can return either a value or a Future(value), this function always returns a Future output value.
Examples
getFutureResult[Int,LeaderboardStatusResponse]( leaderboard.getCount, count => LeaderboardStatusResponse(leaderboardUrlId, count))
- I
Input Type
- O
Output Type
- input
value
- output
function
- executor
ExecutionContext for running Futures
- returns
Future with Output Result
-
def
uuidToBase64UrlId(uuid: UUID): String
Generate Base 64 URL String from UUID
- uuid
Unique Universal Identifier
- returns
Base 64 URL String
- object Identity
-
object
Internalized
Behaves similar to java.lang.String#intern
Maintain a Manifest of Objects
Behaves similar to java.lang.String#intern
This code is thread-safe
Examples
val id1 = UUID.fromString("02b9670c-afd4-4c39-b4d3-3c46ac4f1a9c") val id2 = UUID.fromString("02b9670c-afd4-4c39-b4d3-3c46ac4f1a9c") val id3 = UUID.fromString("02b9670c-afd4-4c39-b4d3-3c46ac4f1a9c") assert(id1 == id2) assert(! (id1 eq id2)) assert(id1 == id3) assert(! (id1 eq id3)) assert(id2 == id3) assert(! (id2 eq id3)) assert(Internalized(id1) eq Internalized(id1)) assert(Internalized(id2) eq Internalized(id3))
Uses
- See also
net.kolotyluk.scala.extras.InternalizedSpec
Leaderboard Micro Service
Akka based micro service proving general leaderboard functionality for applications such as back-end game servers.
Overview


|
WiseLoop JavaScript Premium Weather Widget 2.1.1
Weather Condition & Forecast Script
|
Along with the directive that displays the weather widget, the module offers a service that is able to provide raw weather data and forecast also.
The service can be used to build other directives or it can be used to make a standalone application that presents the weather conditions in own UI or use it in any other scenarios.
Bottom line is that the service will offer raw weather data on demand without any UI, leaving the developer the freedom of choice to decide what to do with the data.
In this section, we will build a simple JavaScript AngularJS application that will get the weather conditions using the data service.
To keep the things as simple as possible, the data will be displayed inside a classical alert box without any other UI or DOM elements. Also, please visit https://developer.forecast.io to get a forecast.io API key in order to configure the script properly. It's free and very easy. After getting the key, just replace the your-developer.forecast.io-key with your actual key.
The following file structure is assumed to exists on the server as this is the default structure that the package comes with.
The file we are editing is /sample/index.html
A very basic JavaScript AngularJS app using the weather forecast data service should look like:
<html ng-app="demo-app" ng-controller="demoAppController"> <head> <link rel="stylesheet" href="../bins/lib/bootstrap/css/bootstrap.min.css"/> <script type="text/javascript" src="../bins/lib/skycons/skycons.js"></script> <script type="text/javascript" src="../bins/lib/angular/angular.min.js"></script> <script type="text/javascript" src="../bins/lib/angular/angular-animate.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script> <script type="text/javascript" src="../bins/wl-ng-weather.js"></script> <script type="text/javascript"> //configuration angular.module('wl-ng-weather').value('bins', '../bins'); angular.module('wl-ng-weather').value('apikey', 'your-forecast.io-key'); //create an AngularJS module with a dependency to our weather forecast module var demoApp = angular.module('demo-app', ['wl-ng-weather']); //declare a controller with a dependency on the data service (wlNgWForecastIo) demoApp.controller('demoAppController', function(wlNgWForecastIo) { //get the weather for the North Pole (latitude = 90, longitude = 0) wlNgWForecastIo.get(90, 0) .then(function(weather) { //on success, display the weather alert(JSON.stringify(weather)); }, function(error) { //on error ... alert(error); }); }); </script> </head> </html>
Looking at the JavaScript code above, after configuring the module, we created a basic AngularJS module (application) called demo-app with a dependency to the weather data service wl-ng-weather:
var demoApp = angular.module('demo-app', ['wl-ng-weather']);
Then, we created a controller inside the demo application having a dependency to the weather data service (wlNgWForecastIo):
demoApp.controller('demoAppController', function(wlNgWForecastIo) { //get the weather for the North Pole (latitude = 90, longitude = 0) wlNgWForecastIo.get(90, 0) .then(function(weather) { alert(JSON.stringify(weather)); }, function(error) { alert(error); }); });
The code above is pretty much self explanatory: get() method of the service is called and if everything goes fine, the weather taken from forecast.io is displayed inside an alert box.


phot2lc¶
phot2lc is a pure-Python interactive tool for extracting light curves from time-series photometric data.
phot2lc is largely inspired by WQED (Thompson & Mullally 2009, 2013), and is designed to work with the outputs from both MAESTRO (Dalessio 2010, 2013) and ccd_hsp (Kanaan et al. 2002).
Installation¶
You can install phot2lc with pip:
pip install phot2lc
The phot2lc project can also be found at GitHub and at PyPI.
Requirements¶
Python 3.6 (or later)
Matplotlib 3.1.3 (or later)
Astropy 4.0 (or later)
LMFIT 1.0.1