1603263600

# Building a Plotly Dash App from Google Sheets

## Introduction

1. Design and ETL Process using Google and code.gsConnect the Google Sheets Data to pythonBuild a Plotly Dash appHost it on Heroku [coming soon]

#dash #dashboard #data-science #plotly

1652748716

## Exploratory Data Analysis Tutorial | Basics of EDA with Python

Exploratory data analysis is used by data scientists to analyze and investigate data sets and summarize their main characteristics, often employing data visualization methods. It helps determine how best to manipulate data sources to get the answers you need, making it easier for data scientists to discover patterns, spot anomalies, test a hypothesis, or check assumptions. EDA is primarily used to see what data can reveal beyond the formal modeling or hypothesis testing task and provides a better understanding of data set variables and the relationships between them. It can also help determine if the statistical techniques you are considering for data analysis are appropriate or not.

🔹 Topics Covered:
00:00:00 Basics of EDA with Python
01:40:10 Multiple Variate Analysis
02:30:26 Outlier Detection
03:44:48 Cricket World Cup Analysis using Exploratory Data Analysis

## What is Exploratory Data Analysis(EDA)?

If we want to explain EDA in simple terms, it means trying to understand the given data much better, so that we can make some sense out of it.

We can find a more formal definition in Wikipedia.

In statistics, exploratory data analysis is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. A statistical model can be used or not, but primarily EDA is for seeing what the data can tell us beyond the formal modeling or hypothesis testing task.

EDA in Python uses data visualization to draw meaningful patterns and insights. It also involves the preparation of data sets for analysis by removing irregularities in the data.

Based on the results of EDA, companies also make business decisions, which can have repercussions later.

• If EDA is not done properly then it can hamper the further steps in the machine learning model building process.
• If done well, it may improve the efficacy of everything we do next.

1. Data Sourcing
2. Data Cleaning
3. Univariate analysis
4. Bivariate analysis
5. Multivariate analysis

## 1. Data Sourcing

Data Sourcing is the process of finding and loading the data into our system. Broadly there are two ways in which we can find data.

1. Private Data
2. Public Data

Private Data

As the name suggests, private data is given by private organizations. There are some security and privacy concerns attached to it. This type of data is used for mainly organizations internal analysis.

Public Data

This type of Data is available to everyone. We can find this in government websites and public organizations etc. Anyone can access this data, we do not need any special permissions or approval.

We can get public data on the following sites.

The very first step of EDA is Data Sourcing, we have seen how we can access data and load into our system. Now, the next step is how to clean the data.

## 2. Data Cleaning

After completing the Data Sourcing, the next step in the process of EDA is Data Cleaning. It is very important to get rid of the irregularities and clean the data after sourcing it into our system.

Irregularities are of different types of data.

• Missing Values
• Incorrect Format
• Anomalies/Outliers

To perform the data cleaning we are using a sample data set, which can be found here.

We are using Jupyter Notebook for analysis.

First, let’s import the necessary libraries and store the data in our system for analysis.

``````#import the useful libraries.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

# Read the data set of "Marketing Analysis" in data.

# Printing the data
data``````

Now, the data set looks like this,

If we observe the above dataset, there are some discrepancies in the Column header for the first 2 rows. The correct data is from the index number 1. So, we have to fix the first two rows.

This is called Fixing the Rows and Columns. Let’s ignore the first two rows and load the data again.

``````#import the useful libraries.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

# Read the file in data without first two rows as it is of no use.

#print the head of the data frame.

Now, the dataset looks like this, and it makes more sense.

Dataset after fixing the rows and columns

Following are the steps to be taken while Fixing Rows and Columns:

1. Delete Summary Rows and Columns in the Dataset.
2. Delete Header and Footer Rows on every page.
3. Delete Extra Rows like blank rows, page numbers, etc.
4. We can merge different columns if it makes for better understanding of the data
5. Similarly, we can also split one column into multiple columns based on our requirements or understanding.
6. Add Column names, it is very important to have column names to the dataset.

Now if we observe the above dataset, the `customerid` column has of no importance to our analysis, and also the `jobedu` column has both the information of `job` and `education` in it.

So, what we’ll do is, we’ll drop the `customerid` column and we’ll split the `jobedu` column into two other columns `job` and `education` and after that, we’ll drop the `jobedu` column as well.

``````# Drop the customer id as it is of no use.
data.drop('customerid', axis = 1, inplace = True)

#Extract job  & Education in newly from "jobedu" column.
data['job']= data["jobedu"].apply(lambda x: x.split(",")[0])
data['education']= data["jobedu"].apply(lambda x: x.split(",")[1])

# Drop the "jobedu" column from the dataframe.
data.drop('jobedu', axis = 1, inplace = True)

# Printing the Dataset
data``````

Now, the dataset looks like this,

Dropping `Customerid `and jobedu columns and adding job and education columns

Missing Values

If there are missing values in the Dataset before doing any statistical analysis, we need to handle those missing values.

There are mainly three types of missing values.

1. MCAR(Missing completely at random): These values do not depend on any other features.
2. MAR(Missing at random): These values may be dependent on some other features.
3. MNAR(Missing not at random): These missing values have some reason for why they are missing.

Let’s see which columns have missing values in the dataset.

``````# Checking the missing values
data.isnull().sum()``````

The output will be,

As we can see three columns contain missing values. Let’s see how to handle the missing values. We can handle missing values by dropping the missing records or by imputing the values.

Drop the missing Values

Let’s handle missing values in the `age` column.

``````# Dropping the records with age missing in data dataframe.
data = data[~data.age.isnull()].copy()

# Checking the missing values in the dataset.
data.isnull().sum()``````

Let’s check the missing values in the dataset now.

Let’s impute values to the missing values for the month column.

Since the month column is of an object type, let’s calculate the mode of that column and impute those values to the missing values.

``````# Find the mode of month in data
month_mode = data.month.mode()[0]

# Fill the missing values with mode value of month in data.
data.month.fillna(month_mode, inplace = True)

# Let's see the null values in the month column.
data.month.isnull().sum()``````

Now output is,

``````# Mode of month is
'may, 2017'
# Null values in month column after imputing with mode
0``````

Handling the missing values in the Response column. Since, our target column is Response Column, if we impute the values to this column it’ll affect our analysis. So, it is better to drop the missing values from Response Column.

``````#drop the records with response missing in data.
data = data[~data.response.isnull()].copy()
# Calculate the missing values in each column of data frame
data.isnull().sum()``````

Let’s check whether the missing values in the dataset have been handled or not,

All the missing values have been handled

We can also, fill the missing values as ‘NaN’ so that while doing any statistical analysis, it won’t affect the outcome.

Handling Outliers

We have seen how to fix missing values, now let’s see how to handle outliers in the dataset.

Outliers are the values that are far beyond the next nearest data points.

There are two types of outliers:

1. Univariate outliers: Univariate outliers are the data points whose values lie beyond the range of expected values based on one variable.
2. Multivariate outliers: While plotting data, some values of one variable may not lie beyond the expected range, but when you plot the data with some other variable, these values may lie far from the expected value.

So, after understanding the causes of these outliers, we can handle them by dropping those records or imputing with the values or leaving them as is, if it makes more sense.

Standardizing Values

To perform data analysis on a set of values, we have to make sure the values in the same column should be on the same scale. For example, if the data contains the values of the top speed of different companies’ cars, then the whole column should be either in meters/sec scale or miles/sec scale.

Now, that we are clear on how to source and clean the data, let’s see how we can analyze the data.

## 3. Univariate Analysis

If we analyze data over a single variable/column from a dataset, it is known as Univariate Analysis.

Categorical Unordered Univariate Analysis:

An unordered variable is a categorical variable that has no defined order. If we take our data as an example, the job column in the dataset is divided into many sub-categories like technician, blue-collar, services, management, etc. There is no weight or measure given to any value in the ‘job’ column.

Now, let’s analyze the job category by using plots. Since Job is a category, we will plot the bar plot.

``````# Let's calculate the percentage of each job status category.
data.job.value_counts(normalize=True)

#plot the bar graph of percentage job categories
data.job.value_counts(normalize=True).plot.barh()
plt.show()``````

The output looks like this,

By the above bar plot, we can infer that the data set contains more number of blue-collar workers compared to other categories.

Categorical Ordered Univariate Analysis:

Ordered variables are those variables that have a natural rank of order. Some examples of categorical ordered variables from our dataset are:

• Month: Jan, Feb, March……
• Education: Primary, Secondary,……

Now, let’s analyze the Education Variable from the dataset. Since we’ve already seen a bar plot, let’s see how a Pie Chart looks like.

``````#calculate the percentage of each education category.
data.education.value_counts(normalize=True)

#plot the pie chart of education categories
data.education.value_counts(normalize=True).plot.pie()
plt.show()``````

The output will be,

By the above analysis, we can infer that the data set has a large number of them belongs to secondary education after that tertiary and next primary. Also, a very small percentage of them have been unknown.

This is how we analyze univariate categorical analysis. If the column or variable is of numerical then we’ll analyze by calculating its mean, median, std, etc. We can get those values by using the describe function.

``data.salary.describe()``

The output will be,

## 4. Bivariate Analysis

If we analyze data by taking two variables/columns into consideration from a dataset, it is known as Bivariate Analysis.

a) Numeric-Numeric Analysis:

Analyzing the two numeric variables from a dataset is known as numeric-numeric analysis. We can analyze it in three different ways.

• Scatter Plot
• Pair Plot
• Correlation Matrix

Scatter Plot

Let’s take three columns ‘Balance’, ‘Age’ and ‘Salary’ from our dataset and see what we can infer by plotting to scatter plot between `salary` `balance` and `age` `balance`

``````#plot the scatter plot of balance and salary variable in data
plt.scatter(data.salary,data.balance)
plt.show()

#plot the scatter plot of balance and age variable in data
data.plot.scatter(x="age",y="balance")
plt.show()``````

Now, the scatter plots looks like,

Pair Plot

Now, let’s plot Pair Plots for the three columns we used in plotting Scatter plots. We’ll use the seaborn library for plotting Pair Plots.

``````#plot the pair plot of salary, balance and age in data dataframe.
sns.pairplot(data = data, vars=['salary','balance','age'])
plt.show()``````

The Pair Plot looks like this,

Correlation Matrix

Since we cannot use more than two variables as x-axis and y-axis in Scatter and Pair Plots, it is difficult to see the relation between three numerical variables in a single graph. In those cases, we’ll use the correlation matrix.

``````# Creating a matrix using age, salry, balance as rows and columns
data[['age','salary','balance']].corr()

#plot the correlation matrix of salary, balance and age in data dataframe.
sns.heatmap(data[['age','salary','balance']].corr(), annot=True, cmap = 'Reds')
plt.show()``````

First, we created a matrix using age, salary, and balance. After that, we are plotting the heatmap using the seaborn library of the matrix.

b) Numeric - Categorical Analysis

Analyzing the one numeric variable and one categorical variable from a dataset is known as numeric-categorical analysis. We analyze them mainly using mean, median, and box plots.

Let’s take `salary` and `response` columns from our dataset.

First check for mean value using `groupby`

``````#groupby the response to find the mean of the salary with response no & yes separately.
data.groupby('response')['salary'].mean()``````

The output will be,

There is not much of a difference between the yes and no response based on the salary.

Let’s calculate the median,

``````#groupby the response to find the median of the salary with response no & yes separately.
data.groupby('response')['salary'].median()``````

The output will be,

By both mean and median we can say that the response of yes and no remains the same irrespective of the person’s salary. But, is it truly behaving like that, let’s plot the box plot for them and check the behavior.

``````#plot the box plot of salary for yes & no responses.
sns.boxplot(data.response, data.salary)
plt.show()``````

The box plot looks like this,

As we can see, when we plot the Box Plot, it paints a very different picture compared to mean and median. The IQR for customers who gave a positive response is on the higher salary side.

This is how we analyze Numeric-Categorical variables, we use mean, median, and Box Plots to draw some sort of conclusions.

c) Categorical — Categorical Analysis

Since our target variable/column is the Response rate, we’ll see how the different categories like Education, Marital Status, etc., are associated with the Response column. So instead of ‘Yes’ and ‘No’ we will convert them into ‘1’ and ‘0’, by doing that we’ll get the “Response Rate”.

``````#create response_rate of numerical data type where response "yes"= 1, "no"= 0
data['response_rate'] = np.where(data.response=='yes',1,0)
data.response_rate.value_counts()``````

The output looks like this,

Let’s see how the response rate varies for different categories in marital status.

``````#plot the bar graph of marital status with average value of response_rate
data.groupby('marital')['response_rate'].mean().plot.bar()
plt.show()``````

The graph looks like this,

By the above graph, we can infer that the positive response is more for Single status members in the data set. Similarly, we can plot the graphs for Loan vs Response rate, Housing Loans vs Response rate, etc.

## 5. Multivariate Analysis

If we analyze data by taking more than two variables/columns into consideration from a dataset, it is known as Multivariate Analysis.

Let’s see how ‘Education’, ‘Marital’, and ‘Response_rate’ vary with each other.

First, we’ll create a pivot table with the three columns and after that, we’ll create a heatmap.

``````result = pd.pivot_table(data=data, index='education', columns='marital',values='response_rate')
print(result)

#create heat map of education vs marital vs response_rate
sns.heatmap(result, annot=True, cmap = 'RdYlGn', center=0.117)
plt.show()``````

The Pivot table and heatmap looks like this,

Based on the Heatmap we can infer that the married people with primary education are less likely to respond positively for the survey and single people with tertiary education are most likely to respond positively to the survey.

Similarly, we can plot the graphs for Job vs marital vs response, Education vs poutcome vs response, etc.

Conclusion

This is how we’ll do Exploratory Data Analysis. Exploratory Data Analysis (EDA) helps us to look beyond the data. The more we explore the data, the more the insights we draw from it. As a data analyst, almost 80% of our time will be spent understanding data and solving various business problems through EDA.

Thank you for reading and Happy Coding!!!

#dataanalysis #python

1595059664

## How long does it take to develop/build an app?

With more of us using smartphones, the popularity of mobile applications has exploded. In the digital era, the number of people looking for products and services online is growing rapidly. Smartphone owners look for mobile applications that give them quick access to companies’ products and services. As a result, mobile apps provide customers with a lot of benefits in just one device.

Likewise, companies use mobile apps to increase customer loyalty and improve their services. Mobile Developers are in high demand as companies use apps not only to create brand awareness but also to gather information. For that reason, mobile apps are used as tools to collect valuable data from customers to help companies improve their offer.

There are many types of mobile applications, each with its own advantages. For example, native apps perform better, while web apps don’t need to be customized for the platform or operating system (OS). Likewise, hybrid apps provide users with comfortable user experience. However, you may be wondering how long it takes to develop an app.

To give you an idea of how long the app development process takes, here’s a short guide.

## App Idea & Research

_Average time spent: two to five weeks _

This is the initial stage and a crucial step in setting the project in the right direction. In this stage, you brainstorm ideas and select the best one. Apart from that, you’ll need to do some research to see if your idea is viable. Remember that coming up with an idea is easy; the hard part is to make it a reality.

All your ideas may seem viable, but you still have to run some tests to keep it as real as possible. For that reason, when Web Developers are building a web app, they analyze the available ideas to see which one is the best match for the targeted audience.

Targeting the right audience is crucial when you are developing an app. It saves time when shaping the app in the right direction as you have a clear set of objectives. Likewise, analyzing how the app affects the market is essential. During the research process, App Developers must gather information about potential competitors and threats. This helps the app owners develop strategies to tackle difficulties that come up after the launch.

The research process can take several weeks, but it determines how successful your app can be. For that reason, you must take your time to know all the weaknesses and strengths of the competitors, possible app strategies, and targeted audience.

The outcomes of this stage are app prototypes and the minimum feasible product.

#android app #frontend #ios app #minimum viable product (mvp) #mobile app development #web development #android app development #app development #app development for ios and android #app development process #ios and android app development #ios app development #stages in app development

1595491178

## Best Electric Bikes and Scooters for Rental Business or Campus Facility

The electric scooter revolution has caught on super-fast taking many cities across the globe by storm. eScooters, a renovated version of old-school scooters now turned into electric vehicles are an environmentally friendly solution to current on-demand commute problems. They work on engines, like cars, enabling short traveling distances without hassle. The result is that these groundbreaking electric machines can now provide faster transport for less — cheaper than Uber and faster than Metro.

Since they are durable, fast, easy to operate and maintain, and are more convenient to park compared to four-wheelers, the eScooters trend has and continues to spike interest as a promising growth area. Several companies and universities are increasingly setting up shop to provide eScooter services realizing a would-be profitable business model and a ready customer base that is university students or residents in need of faster and cheap travel going about their business in school, town, and other surrounding areas.

### Electric Scooters Trends and Statistics

In many countries including the U.S., Canada, Mexico, U.K., Germany, France, China, Japan, India, Brazil and Mexico and more, a growing number of eScooter users both locals and tourists can now be seen effortlessly passing lines of drivers stuck in the endless and unmoving traffic.

A recent report by McKinsey revealed that the E-Scooter industry will be worth― \$200 billion to \$300 billion in the United States, \$100 billion to \$150 billion in Europe, and \$30 billion to \$50 billion in China in 2030. The e-Scooter revenue model will also spike and is projected to rise by more than 20% amounting to approximately \$5 billion.

And, with a necessity to move people away from high carbon prints, traffic and congestion issues brought about by car-centric transport systems in cities, more and more city planners are developing more bike/scooter lanes and adopting zero-emission plans. This is the force behind the booming electric scooter market and the numbers will only go higher and higher.

Companies that have taken advantage of the growing eScooter trend develop an appthat allows them to provide efficient eScooter services. Such an app enables them to be able to locate bike pick-up and drop points through fully integrated google maps.

## List of Best Electric Bikes for Rental Business or Campus Facility 2020:

It’s clear that e scooters will increasingly become more common and the e-scooter business model will continue to grab the attention of manufacturers, investors, entrepreneurs. All this should go ahead with a quest to know what are some of the best electric bikes in the market especially for anyone who would want to get started in the electric bikes/scooters rental business.

We have done a comprehensive list of the best electric bikes! Each bike has been reviewed in depth and includes a full list of specs and a photo.

### Billy eBike

To start us off is the Billy eBike, a powerful go-anywhere urban electric bike that’s specially designed to offer an exciting ride like no other whether you want to ride to the grocery store, cafe, work or school. The Billy eBike comes in 4 color options – Billy Blue, Polished aluminium, Artic white, and Stealth black.

Price: \$2490

Available countries

Available in the USA, Europe, Asia, South Africa and Australia.This item ships from the USA. Buyers are therefore responsible for any taxes and/or customs duties incurred once it arrives in your country.

Features

• Control – Ride with confidence with our ultra-wide BMX bars and a hyper-responsive twist throttle.
• Stealth- Ride like a ninja with our Gates carbon drive that’s as smooth as butter and maintenance-free.
• Drive – Ride further with our high torque fat bike motor, giving a better climbing performance.
• Accelerate – Ride quicker with our 20-inch lightweight cutout rims for improved acceleration.
• Customize – Ride your own way with 5 levels of power control. Each level determines power and speed.
• Flickable – Ride harder with our BMX /MotoX inspired geometry and lightweight aluminum package

Specifications

• Maximum speed: 20 mph (32 km/h)
• Range per charge: 41 miles (66 km)
• Maximum Power: 500W
• Motor type: Fat Bike Motor: Bafang RM G060.500.DC
• Battery type: 13.6Ah Samsung lithium-ion,
• Battery capacity: On/off-bike charging available
• Weight: w/o batt. 48.5lbs (22kg), w/ batt. 54lbs (24.5kg)
• Built-in GPS

• Riding fun and excitement
• Better climbing ability and faster acceleration.
• Ride with confidence
• Billy folds for convenient storage and transportation.
• Shorty levers connect to disc brakes ensuring you stop on a dime
• belt drives are maintenance-free and clean (no oil or lubrication needed)

**Who Should Ride Billy? **

Both new and experienced riders

**Where to Buy? **Local distributors or ships from the USA.

### Genze 200 series e-Bike

Featuring a sleek and lightweight aluminum frame design, the 200-Series ebike takes your riding experience to greater heights. Available in both black and white this ebike comes with a connected app, which allows you to plan activities, map distances and routes while also allowing connections with fellow riders.

Price: \$2099.00

Available countries

The Genze 200 series e-Bike is available at GenZe retail locations across the U.S or online via GenZe.com website. Customers from outside the US can ship the product while incurring the relevant charges.

Features

• 2 Frame Options
• 2 Sizes
• Integrated/Removable Battery
• Throttle and Pedal Assist Ride Modes
• Integrated LCD Display
• Connected App
• 24 month warranty
• Bluetooth connectivity

Specifications

• Maximum speed: 20 mph with throttle
• Range per charge: 15-18 miles w/ throttle and 30-50 miles w/ pedal assist
• Charging time: 3.5 hours
• Motor type: Brushless Rear Hub Motor
• Gears: Microshift Thumb Shifter
• Battery type: Removable Samsung 36V, 9.6AH Li-Ion battery pack
• Battery capacity: 36V and 350 Wh
• Weight: 46 pounds
• Derailleur: 8-speed Shimano
• Brakes: Dual classic
• Wheels: 26 x 20 inches
• Frame: 16, and 18 inches
• Operating Mode: Analog mode 5 levels of Pedal Assist Thrott­le Mode

### Norco from eBikestore

The Norco VLT S2 is a front suspension e-Bike with solid components alongside the reliable Bosch Performance Line Power systems that offer precise pedal assistance during any riding situation.

Price: \$2,699.00

Available countries

This item is available via the various Norco bikes international distributors.

Features

• VLT aluminum frame- for stiffness and wheel security.
• Bosch e-bike system – for their reliability and performance.
• E-bike components – for added durability.
• Hydraulic disc brakes – offer riders more stopping power for safety and control at higher speeds.
• Practical design features – to add convenience and versatility.

Specifications

• Maximum speed: KMC X9 9spd
• Motor type: Bosch Active Line
• Gears: Shimano Altus RD-M2000, SGS, 9 Speed
• Battery type: Power Pack 400
• Battery capacity: 396Wh
• Suspension: SR Suntour suspension fork
• Frame: Norco VLT, Aluminum, 12x142mm TA Dropouts

### Bodo EV

http://www.bodoevs.com/bodoev/products_show.asp?product_id=13

Manufactured by Bodo Vehicle Group Limited, the Bodo EV is specially designed for strong power and extraordinary long service to facilitate super amazing rides. The Bodo Vehicle Company is a striking top in electric vehicles brand field in China and across the globe. Their Bodo EV will no doubt provide your riders with high-level riding satisfaction owing to its high-quality design, strength, breaking stability and speed.

Price: \$799

Available countries

This item ships from China with buyers bearing the shipping costs and other variables prior to delivery.

Features

• Reliable
• Environment friendly
• Comfortable riding
• Fashionable
• Economical
• Durable – long service life
• Braking stability
• LED lighting technology

Specifications

• Maximum speed: 45km/h
• Range per charge: 50km per person
• Charging time: 8 hours
• Maximum Power: 3000W
• Motor type: Brushless DC Motor
• Battery capacity: 60V 20AH
• Weight: w/o battery 47kg

1595494844

## How to start an electric scooter facility/fleet in a university campus/IT park

Are you leading an organization that has a large campus, e.g., a large university? You are probably thinking of introducing an electric scooter/bicycle fleet on the campus, and why wouldn’t you?

Introducing micro-mobility in your campus with the help of such a fleet would help the people on the campus significantly. People would save money since they don’t need to use a car for a short distance. Your campus will see a drastic reduction in congestion, moreover, its carbon footprint will reduce.

Micro-mobility is relatively new though and you would need help. You would need to select an appropriate fleet of vehicles. The people on your campus would need to find electric scooters or electric bikes for commuting, and you need to provide a solution for this.

To be more specific, you need a short-term electric bike rental app. With such an app, you will be able to easily offer micro-mobility to the people on the campus. We at Devathon have built Autorent exactly for this.

What does Autorent do and how can it help you? How does it enable you to introduce micro-mobility on your campus? We explain these in this article, however, we will touch upon a few basics first.

## Micro-mobility: What it is

You are probably thinking about micro-mobility relatively recently, aren’t you? A few relevant insights about it could help you to better appreciate its importance.

Micro-mobility is a new trend in transportation, and it uses vehicles that are considerably smaller than cars. Electric scooters (e-scooters) and electric bikes (e-bikes) are the most popular forms of micro-mobility, however, there are also e-unicycles and e-skateboards.

You might have already seen e-scooters, which are kick scooters that come with a motor. Thanks to its motor, an e-scooter can achieve a speed of up to 20 km/h. On the other hand, e-bikes are popular in China and Japan, and they come with a motor, and you can reach a speed of 40 km/h.

You obviously can’t use these vehicles for very long commutes, however, what if you need to travel a short distance? Even if you have a reasonable public transport facility in the city, it might not cover the route you need to take. Take the example of a large university campus. Such a campus is often at a considerable distance from the central business district of the city where it’s located. While public transport facilities may serve the central business district, they wouldn’t serve this large campus. Currently, many people drive their cars even for short distances.

As you know, that brings its own set of challenges. Vehicular traffic adds significantly to pollution, moreover, finding a parking spot can be hard in crowded urban districts.

Well, you can reduce your carbon footprint if you use an electric car. However, electric cars are still new, and many countries are still building the necessary infrastructure for them. Your large campus might not have the necessary infrastructure for them either. Presently, electric cars don’t represent a viable option in most geographies.

As a result, you need to buy and maintain a car even if your commute is short. In addition to dealing with parking problems, you need to spend significantly on your car.

All of these factors have combined to make people sit up and think seriously about cars. Many people are now seriously considering whether a car is really the best option even if they have to commute only a short distance.

This is where micro-mobility enters the picture. When you commute a short distance regularly, e-scooters or e-bikes are viable options. You limit your carbon footprints and you cut costs!

Businesses have seen this shift in thinking, and e-scooter companies like Lime and Bird have entered this field in a big way. They let you rent e-scooters by the minute. On the other hand, start-ups like Jump and Lyft have entered the e-bike market.

Think of your campus now! The people there might need to travel short distances within the campus, and e-scooters can really help them.

## How micro-mobility can benefit you

What advantages can you get from micro-mobility? Let’s take a deeper look into this question.

Micro-mobility can offer several advantages to the people on your campus, e.g.:

• Affordability: Shared e-scooters are cheaper than other mass transportation options. Remember that the people on your campus will use them on a shared basis, and they will pay for their short commutes only. Well, depending on your operating model, you might even let them use shared e-scooters or e-bikes for free!
• Convenience: Users don’t need to worry about finding parking spots for shared e-scooters since these are small. They can easily travel from point A to point B on your campus with the help of these e-scooters.
• Environmentally sustainable: Shared e-scooters reduce the carbon footprint, moreover, they decongest the roads. Statistics from the pilot programs in cities like Portland and Denver showimpressive gains around this key aspect.
• Safety: This one’s obvious, isn’t it? When people on your campus use small e-scooters or e-bikes instead of cars, the problem of overspeeding will disappear. you will see fewer accidents.

#android app #autorent #ios app #mobile app development #app like bird #app like bounce #app like lime #autorent #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime

1651033740

## ThruwayBundle: Bundle for Building Real-time Apps in Symfony

ThruwayBundle

This a Symfony Bundle for Thruway, which is a php implementation of WAMP (Web Application Messaging Protocol).

Note: This project is still undergoing a lot of changes, so the API will change.

Install the Thruway Bundle

``  \$ composer require "voryx/thruway-bundle"``

Update AppKernel.php (when using Symfony < 4)

``````\$bundles = array(
// ...
new Voryx\ThruwayBundle\VoryxThruwayBundle(),
// ...
);``````

### Configuration

``````#app/config/config.yml

voryx_thruway:
realm: 'realm1'
url: 'ws://127.0.0.1:8081' #The url that the clients will use to connect to the router
router:
ip: '127.0.0.1'  # the ip that the router should start on
port: '8080'  # public facing port.  If authentication is enabled, this port will be protected
trusted_port: '8081' # Bypasses all authentication.  Use this for trusted clients.
#        authentication: false # true will load the AuthenticationManager
locations:
bundles: ["AppBundle"]
#        files:
#            - "Acme\\DemoBundle\\Controller\\DemoController"
#
# For symfony 4, this bundle will automatically scan for annotated worker files in the src/Controller folder
``````

With Symfony 4 use a filename like: `config/packages/voryx.yaml`

If you are using the in-memory user provider, you'll need to add a `thruway` to the security firewall and set the `in_memory_user_provider`.

``````#app/config/security.yml

security:
firewalls:
thruway:
security: false	     ``````

You can also tag services with `thruway.resource` and any annotation will get picked up

``````<service id="some.service" class="Acme\Bundle\SomeService">
<tag name="thruway.resource"/>
</service>
``````

Note: tagging a service as `thruway.resource` will make it public.

``````services:
App\Worker\:
resource: '../src/Worker'
tags: ['thruway.resource']``````

### Authentication with FOSUserBundle via WampCRA

Change the Password Encoder (tricky on existing sites) to master wamp challenge

``````#app/config/security.yml

security:
...
encoders:
FOS\UserBundle\Model\UserInterface:
algorithm:            pbkdf2
hash_algorithm:       sha256
encode_as_base64:     true
iterations:           1000
key_length:           32``````

set voryx_thruway.user_provider to "fos_user.user_provider"

``````#app/config/config.yml

voryx_thruway:
``````

The WAMP-CRA service is already configured, we just need to add a tag to it to have the bundle install it:

``````    wamp_cra_auth:
class: Thruway\Authentication\WampCraAuthProvider
parent: voryx.thruway.wamp.cra.auth.client
tags:
- { name: thruway.internal_client }``````

### Custom Authorization Manager

You can set your own Authorization Manager in order to check if a user (identified by its authid) is allowed to publish | subscribe | call | register

Create your Authorization Manager service, extending RouterModuleClient and implementing RealmModuleInterface (see the Thruway doc for details)

``````// src/ACME/AppBundle/Security/MyAuthorizationManager.php

use Thruway\Event\MessageEvent;
use Thruway\Event\NewRealmEvent;
use Thruway\Module\RealmModuleInterface;
use Thruway\Module\RouterModuleClient;

class MyAuthorizationManager extends RouterModuleClient implements RealmModuleInterface
{
/**
* Listen for Router events.
* Required to add the authorization module to the realm
*
* @return array
*/
public static function getSubscribedEvents()
{
return [
'new_realm' => ['handleNewRealm', 10]
];
}

/**
* @param NewRealmEvent \$newRealmEvent
*/
public function handleNewRealm(NewRealmEvent \$newRealmEvent)
{
\$realm = \$newRealmEvent->realm;

if (\$realm->getRealmName() === \$this->getRealm()) {
}
}

/**
* @return array
*/
public function getSubscribedRealmEvents()
{
return [
'PublishMessageEvent'   => ['authorize', 100],
'SubscribeMessageEvent' => ['authorize', 100],
'RegisterMessageEvent'  => ['authorize', 100],
'CallMessageEvent'      => ['authorize', 100],
];
}

/**
* @param MessageEvent \$msg
* @return bool
*/
public function authorize(MessageEvent \$msg)
{
return true;
}
return false;
}
}``````

``````     my_authorization_manager:
class: ACME\AppBundle\Security\MyAuthorizationManager``````

``````#app/config/config.yml

voryx_thruway:
...
authorization: my_authorization_manager # insert the name of your custom authorizationManager
...``````

Restart the Thruway server; it will now check authorization upon publish | subscribe | call | register. Remember to catch error when you try to subscribe to a topic (or any other action) as it may now be denied and this will be returned as an error.

## Usage

#### Register RPC

``````    use Voryx\ThruwayBundle\Annotation\Register;

/**
*
*
*/
{
return \$num1 + \$num2;
}``````

#### Call RPC

``````    public function call(\$value)
{
\$client = \$this->container->get('thruway.client');
function (\$res) {
echo \$res[0];
}
);
}``````

#### Subscribe

``````     use Voryx\ThruwayBundle\Annotation\Subscribe;

/**
*
* @Subscribe("com.example.subscribe")
*
*/
public function subscribe(\$value)
{
echo \$value;
}``````

#### Publish

``````    public function publish(\$value)
{
\$client = \$this->container->get('thruway.client');
\$client->publish("com.myapp.hello_pubsub", [\$value]);
}``````

It uses Symfony Serializer, so it can serialize and deserialize Entities

``````         use Voryx\ThruwayBundle\Annotation\Register;

/**
*
*
*/
{
//Do something to \$post

return \$post;
}``````

#### Start the Thruway Process

You can start the default Thruway workers (router and client workers), without any additional configuration.

``````\$ nohup php app/console thruway:process start &
``````

By default, the router starts on ws://127.0.0.1:8080

## Workers

The Thruway bundle will start up a separate process for the router and each defined worker. If you haven't defined any workers, all of the annotated calls and subscriptions will be started within the `default` worker.

There are two main ways to break your application apart into multiple workers.

Use the `worker` property on the `Register` and `Subscribe` annotations. The following RPC will be added to the `posts` worker.

``````  use Voryx\ThruwayBundle\Annotation\Register;

/**
*/

Use the `@Worker` annotation on the class. The following annotation will create a worker called `chat` that can have a max of 5 instances.

``````  use Voryx\ThruwayBundle\Annotation\Worker;

/**
* @Worker("chat", maxProcesses="5")
*/
class ChatController``````

If a worker is shut down with anything other than `SIGTERM`, it will automatically be restarted.

## More Commands

To see a list of running processes (workers)

``````\$ php app/console thruway:process status
``````

Stop a process, i.e. `default`

``````\$ php app/console thruway:process stop default
``````

Start a process, i.e. `default`

``````\$ php app/console thruway:process start default
``````

### Javascript Client

For the client, you can use AutobahnJS or any other WAMPv2 compatible client.

Here are some examples

Symfony 4 Quick Start

``composer create-project symfony/skeleton my_project``
``cd my_project``
``composer require symfony/expression-language``
``composer require symfony/annotations-pack``
``composer require voryx/thruway-bundle:dev-master``

Create config/packages/my_project.yml with the following config:

``````voryx_thruway:
realm: 'realm1'
url: 'ws://127.0.0.1:8081' #The url that the clients will use to connect to the router
router:
ip: '127.0.0.1'  # the ip that the router should start on
port: '8080'  # public facing port.  If authentication is enabled, this port will be protected
trusted_port: '8081' # Bypasses all authentication.  Use this for trusted clients.``````

Create the controller src/Controller/TestController.php

``````<?php
namespace App\Controller;

use Voryx\ThruwayBundle\Annotation\Register;

class TestController
{
/**
*/
{
return \$num1 + \$num2;
}
}``````

Test to see if the RPC has been configured correctly `bin/console thruway:debug`

`````` URI             Type Worker  File                                                  Method
For more debug info for the RPC we created: `bin/console thruway:debug com.example.add`
Start everything: `bin/console thruway:process start`
The RPC `com.example.add` is now available to any WAMP client connected to ws://127.0.0.1:8081 on realm1.